From 013ead19170ffaa92219d3b72a0ec399dd46adc0 Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 19 Jul 2025 14:01:58 +0100 Subject: [PATCH 01/11] upd --- bun.lock | 3 - dist/index.js | 65053 ++++++++++++++++++ src/common/managers/BlockManagerRegistry.ts | 8 +- src/common/managers/DeploymentManager.ts | 2 +- src/common/managers/NetworkManager.ts | 36 +- src/common/managers/RpcManager.ts | 118 +- src/common/managers/ViemClientManager.ts | 11 +- src/common/utils/HttpClient.ts | 110 +- src/common/utils/fetchNetworkConfigs.ts | 47 +- src/common/utils/initializeManagers.ts | 32 +- src/constants/globalConfig.ts | 2 +- src/types/ManagerConfigs.ts | 1 + 12 files changed, 65164 insertions(+), 259 deletions(-) create mode 100644 dist/index.js diff --git a/bun.lock b/bun.lock index 8c5bf5b..c504b85 100644 --- a/bun.lock +++ b/bun.lock @@ -5,7 +5,6 @@ "name": "concero-v2-operators", "dependencies": { "@concero/contract-utils": "github:concero/contract-utils", - "@concero/v2-networks": "github:concero/v2-networks", "@prisma/client": "^5.12.0", "@slack/web-api": "^7.9.1", "@types/jest": "^29.5.14", @@ -115,8 +114,6 @@ "@concero/contract-utils": ["@concero/contract-utils@github:concero/contract-utils#c10d675", { "dependencies": { "viem": "2.26.2" } }, "concero-contract-utils-c10d675"], - "@concero/v2-networks": ["@concero/v2-networks@github:concero/v2-networks#631fb75", {}, "concero-v2-networks-631fb75"], - "@dabh/diagnostics": ["@dabh/diagnostics@2.0.3", "", { "dependencies": { "colorspace": "1.1.x", "enabled": "2.0.x", "kuler": "^2.0.0" } }, "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA=="], "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.6", "", { "os": "aix", "cpu": "ppc64" }, "sha512-ShbM/3XxwuxjFiuVBHA+d3j5dyac0aEVVq1oluIDf71hUw0aRF59dV/efUsIwFnR6m8JNM2FjZOzmaZ8yG61kw=="], diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..861ecce --- /dev/null +++ b/dist/index.js @@ -0,0 +1,65053 @@ +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 __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, { + get: (a, b2) => (typeof require !== "undefined" ? require : a)[b2] +}) : x2)(function(x2) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x2 + '" is not supported'); +}); +var __esm = (fn2, res) => function __init() { + return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res; +}; +var __commonJS = (cb, mod2) => function __require2() { + return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; +}; +var __export = (target, all3) => { + for (var name in all3) + __defProp(target, name, { get: all3[name], enumerable: true }); +}; +var __copyProps = (to2, from5, except, desc) => { + if (from5 && typeof from5 === "object" || typeof from5 === "function") { + for (let key of __getOwnPropNames(from5)) + if (!__hasOwnProp.call(to2, key) && key !== except) + __defProp(to2, key, { get: () => from5[key], enumerable: !(desc = __getOwnPropDesc(from5, key)) || desc.enumerable }); + } + return to2; +}; +var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __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 || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, + mod2 +)); + +// node_modules/dotenv/package.json +var require_package = __commonJS({ + "node_modules/dotenv/package.json"(exports2, module2) { + module2.exports = { + name: "dotenv", + version: "16.5.0", + description: "Loads environment variables from .env file", + main: "lib/main.js", + types: "lib/main.d.ts", + exports: { + ".": { + types: "./lib/main.d.ts", + require: "./lib/main.js", + default: "./lib/main.js" + }, + "./config": "./config.js", + "./config.js": "./config.js", + "./lib/env-options": "./lib/env-options.js", + "./lib/env-options.js": "./lib/env-options.js", + "./lib/cli-options": "./lib/cli-options.js", + "./lib/cli-options.js": "./lib/cli-options.js", + "./package.json": "./package.json" + }, + scripts: { + "dts-check": "tsc --project tests/types/tsconfig.json", + lint: "standard", + pretest: "npm run lint && npm run dts-check", + test: "tap run --allow-empty-coverage --disable-coverage --timeout=60000", + "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=lcov", + prerelease: "npm test", + release: "standard-version" + }, + repository: { + type: "git", + url: "git://github.com/motdotla/dotenv.git" + }, + homepage: "https://github.com/motdotla/dotenv#readme", + funding: "https://dotenvx.com", + keywords: [ + "dotenv", + "env", + ".env", + "environment", + "variables", + "config", + "settings" + ], + readmeFilename: "README.md", + license: "BSD-2-Clause", + devDependencies: { + "@types/node": "^18.11.3", + decache: "^4.6.2", + sinon: "^14.0.1", + standard: "^17.0.0", + "standard-version": "^9.5.0", + tap: "^19.2.0", + typescript: "^4.8.4" + }, + engines: { + node: ">=12" + }, + browser: { + fs: false + } + }; + } +}); + +// node_modules/dotenv/lib/main.js +var require_main = __commonJS({ + "node_modules/dotenv/lib/main.js"(exports2, module2) { + var fs2 = __require("fs"); + var path = __require("path"); + var os2 = __require("os"); + var crypto4 = __require("crypto"); + var packageJson = require_package(); + var version4 = packageJson.version; + var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; + function parse(src) { + const obj = {}; + let lines = src.toString(); + lines = lines.replace(/\r\n?/mg, "\n"); + let match; + while ((match = LINE.exec(lines)) != null) { + const key = match[1]; + let value = match[2] || ""; + value = value.trim(); + const maybeQuote = value[0]; + value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2"); + if (maybeQuote === '"') { + value = value.replace(/\\n/g, "\n"); + value = value.replace(/\\r/g, "\r"); + } + obj[key] = value; + } + return obj; + } + function _parseVault(options) { + const vaultPath = _vaultPath(options); + const result = DotenvModule.configDotenv({ path: vaultPath }); + if (!result.parsed) { + const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); + err.code = "MISSING_DATA"; + throw err; + } + const keys = _dotenvKey(options).split(","); + const length = keys.length; + let decrypted; + for (let i = 0; i < length; i++) { + try { + const key = keys[i].trim(); + const attrs = _instructions(result, key); + decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); + break; + } catch (error) { + if (i + 1 >= length) { + throw error; + } + } + } + return DotenvModule.parse(decrypted); + } + function _warn(message) { + console.log(`[dotenv@${version4}][WARN] ${message}`); + } + function _debug(message) { + console.log(`[dotenv@${version4}][DEBUG] ${message}`); + } + function _dotenvKey(options) { + if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { + return options.DOTENV_KEY; + } + if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { + return process.env.DOTENV_KEY; + } + return ""; + } + function _instructions(result, dotenvKey) { + let uri; + try { + uri = new URL(dotenvKey); + } catch (error) { + if (error.code === "ERR_INVALID_URL") { + const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } + throw error; + } + const key = uri.password; + if (!key) { + const err = new Error("INVALID_DOTENV_KEY: Missing key part"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } + const environment = uri.searchParams.get("environment"); + if (!environment) { + const err = new Error("INVALID_DOTENV_KEY: Missing environment part"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } + const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; + const ciphertext = result.parsed[environmentKey]; + if (!ciphertext) { + const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); + err.code = "NOT_FOUND_DOTENV_ENVIRONMENT"; + throw err; + } + return { ciphertext, key }; + } + function _vaultPath(options) { + let possibleVaultPath = null; + if (options && options.path && options.path.length > 0) { + if (Array.isArray(options.path)) { + for (const filepath of options.path) { + if (fs2.existsSync(filepath)) { + possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`; + } + } + } else { + possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`; + } + } else { + possibleVaultPath = path.resolve(process.cwd(), ".env.vault"); + } + if (fs2.existsSync(possibleVaultPath)) { + return possibleVaultPath; + } + return null; + } + function _resolveHome(envPath) { + return envPath[0] === "~" ? path.join(os2.homedir(), envPath.slice(1)) : envPath; + } + function _configVault(options) { + const debug = Boolean(options && options.debug); + if (debug) { + _debug("Loading env from encrypted .env.vault"); + } + const parsed = DotenvModule._parseVault(options); + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + DotenvModule.populate(processEnv, parsed, options); + return { parsed }; + } + function configDotenv(options) { + const dotenvPath = path.resolve(process.cwd(), ".env"); + let encoding = "utf8"; + const debug = Boolean(options && options.debug); + if (options && options.encoding) { + encoding = options.encoding; + } else { + if (debug) { + _debug("No encoding is specified. UTF-8 is used by default"); + } + } + let optionPaths = [dotenvPath]; + if (options && options.path) { + if (!Array.isArray(options.path)) { + optionPaths = [_resolveHome(options.path)]; + } else { + optionPaths = []; + for (const filepath of options.path) { + optionPaths.push(_resolveHome(filepath)); + } + } + } + let lastError; + const parsedAll = {}; + for (const path2 of optionPaths) { + try { + const parsed = DotenvModule.parse(fs2.readFileSync(path2, { encoding })); + DotenvModule.populate(parsedAll, parsed, options); + } catch (e) { + if (debug) { + _debug(`Failed to load ${path2} ${e.message}`); + } + lastError = e; + } + } + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + DotenvModule.populate(processEnv, parsedAll, options); + if (lastError) { + return { parsed: parsedAll, error: lastError }; + } else { + return { parsed: parsedAll }; + } + } + function config3(options) { + if (_dotenvKey(options).length === 0) { + return DotenvModule.configDotenv(options); + } + const vaultPath = _vaultPath(options); + if (!vaultPath) { + _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`); + return DotenvModule.configDotenv(options); + } + return DotenvModule._configVault(options); + } + function decrypt(encrypted, keyStr) { + const key = Buffer.from(keyStr.slice(-64), "hex"); + let ciphertext = Buffer.from(encrypted, "base64"); + const nonce = ciphertext.subarray(0, 12); + const authTag = ciphertext.subarray(-16); + ciphertext = ciphertext.subarray(12, -16); + try { + const aesgcm = crypto4.createDecipheriv("aes-256-gcm", key, nonce); + aesgcm.setAuthTag(authTag); + return `${aesgcm.update(ciphertext)}${aesgcm.final()}`; + } catch (error) { + const isRange = error instanceof RangeError; + const invalidKeyLength = error.message === "Invalid key length"; + const decryptionFailed = error.message === "Unsupported state or unable to authenticate data"; + if (isRange || invalidKeyLength) { + const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } else if (decryptionFailed) { + const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY"); + err.code = "DECRYPTION_FAILED"; + throw err; + } else { + throw error; + } + } + } + function populate(processEnv, parsed, options = {}) { + const debug = Boolean(options && options.debug); + const override = Boolean(options && options.override); + if (typeof parsed !== "object") { + const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate"); + err.code = "OBJECT_REQUIRED"; + throw err; + } + for (const key of Object.keys(parsed)) { + if (Object.prototype.hasOwnProperty.call(processEnv, key)) { + if (override === true) { + processEnv[key] = parsed[key]; + } + if (debug) { + if (override === true) { + _debug(`"${key}" is already defined and WAS overwritten`); + } else { + _debug(`"${key}" is already defined and was NOT overwritten`); + } + } + } else { + processEnv[key] = parsed[key]; + } + } + } + var DotenvModule = { + configDotenv, + _configVault, + _parseVault, + config: config3, + decrypt, + parse, + populate + }; + module2.exports.configDotenv = DotenvModule.configDotenv; + module2.exports._configVault = DotenvModule._configVault; + module2.exports._parseVault = DotenvModule._parseVault; + module2.exports.config = DotenvModule.config; + module2.exports.decrypt = DotenvModule.decrypt; + module2.exports.parse = DotenvModule.parse; + module2.exports.populate = DotenvModule.populate; + module2.exports = DotenvModule; + } +}); + +// node_modules/delayed-stream/lib/delayed_stream.js +var require_delayed_stream = __commonJS({ + "node_modules/delayed-stream/lib/delayed_stream.js"(exports2, module2) { + var Stream = __require("stream").Stream; + var util3 = __require("util"); + module2.exports = DelayedStream; + function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; + } + util3.inherits(DelayedStream, Stream); + DelayedStream.create = function(source, options) { + var delayedStream = new this(); + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } + delayedStream.source = source; + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + source.on("error", function() { + }); + if (delayedStream.pauseStream) { + source.pause(); + } + return delayedStream; + }; + Object.defineProperty(DelayedStream.prototype, "readable", { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } + }); + DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); + }; + DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } + this.source.resume(); + }; + DelayedStream.prototype.pause = function() { + this.source.pause(); + }; + DelayedStream.prototype.release = function() { + this._released = true; + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; + }; + DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; + }; + DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } + if (args[0] === "data") { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } + this._bufferedEvents.push(args); + }; + DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + if (this.dataSize <= this.maxDataSize) { + return; + } + this._maxDataSizeExceeded = true; + var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; + this.emit("error", new Error(message)); + }; + } +}); + +// node_modules/combined-stream/lib/combined_stream.js +var require_combined_stream = __commonJS({ + "node_modules/combined-stream/lib/combined_stream.js"(exports2, module2) { + var util3 = __require("util"); + var Stream = __require("stream").Stream; + var DelayedStream = require_delayed_stream(); + module2.exports = CombinedStream; + function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; + } + util3.inherits(CombinedStream, Stream); + CombinedStream.create = function(options) { + var combinedStream = new this(); + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + return combinedStream; + }; + CombinedStream.isStreamLike = function(stream4) { + return typeof stream4 !== "function" && typeof stream4 !== "string" && typeof stream4 !== "boolean" && typeof stream4 !== "number" && !Buffer.isBuffer(stream4); + }; + CombinedStream.prototype.append = function(stream4) { + var isStreamLike = CombinedStream.isStreamLike(stream4); + if (isStreamLike) { + if (!(stream4 instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream4, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams + }); + stream4.on("data", this._checkDataSize.bind(this)); + stream4 = newStream; + } + this._handleErrors(stream4); + if (this.pauseStreams) { + stream4.pause(); + } + } + this._streams.push(stream4); + return this; + }; + CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; + }; + CombinedStream.prototype._getNext = function() { + this._currentStream = null; + if (this._insideLoop) { + this._pendingNext = true; + return; + } + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } + }; + CombinedStream.prototype._realGetNext = function() { + var stream4 = this._streams.shift(); + if (typeof stream4 == "undefined") { + this.end(); + return; + } + if (typeof stream4 !== "function") { + this._pipeNext(stream4); + return; + } + var getStream = stream4; + getStream(function(stream5) { + var isStreamLike = CombinedStream.isStreamLike(stream5); + if (isStreamLike) { + stream5.on("data", this._checkDataSize.bind(this)); + this._handleErrors(stream5); + } + this._pipeNext(stream5); + }.bind(this)); + }; + CombinedStream.prototype._pipeNext = function(stream4) { + this._currentStream = stream4; + var isStreamLike = CombinedStream.isStreamLike(stream4); + if (isStreamLike) { + stream4.on("end", this._getNext.bind(this)); + stream4.pipe(this, { end: false }); + return; + } + var value = stream4; + this.write(value); + this._getNext(); + }; + CombinedStream.prototype._handleErrors = function(stream4) { + var self2 = this; + stream4.on("error", function(err) { + self2._emitError(err); + }); + }; + CombinedStream.prototype.write = function(data) { + this.emit("data", data); + }; + CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + if (this.pauseStreams && this._currentStream && typeof this._currentStream.pause == "function") this._currentStream.pause(); + this.emit("pause"); + }; + CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + if (this.pauseStreams && this._currentStream && typeof this._currentStream.resume == "function") this._currentStream.resume(); + this.emit("resume"); + }; + CombinedStream.prototype.end = function() { + this._reset(); + this.emit("end"); + }; + CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit("close"); + }; + CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; + }; + CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; + this._emitError(new Error(message)); + }; + CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + var self2 = this; + this._streams.forEach(function(stream4) { + if (!stream4.dataSize) { + return; + } + self2.dataSize += stream4.dataSize; + }); + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } + }; + CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit("error", err); + }; + } +}); + +// node_modules/mime-db/db.json +var require_db = __commonJS({ + "node_modules/mime-db/db.json"(exports2, module2) { + module2.exports = { + "application/1d-interleaved-parityfec": { + source: "iana" + }, + "application/3gpdash-qoe-report+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/3gpp-ims+xml": { + source: "iana", + compressible: true + }, + "application/3gpphal+json": { + source: "iana", + compressible: true + }, + "application/3gpphalforms+json": { + source: "iana", + compressible: true + }, + "application/a2l": { + source: "iana" + }, + "application/ace+cbor": { + source: "iana" + }, + "application/activemessage": { + source: "iana" + }, + "application/activity+json": { + source: "iana", + compressible: true + }, + "application/alto-costmap+json": { + source: "iana", + compressible: true + }, + "application/alto-costmapfilter+json": { + source: "iana", + compressible: true + }, + "application/alto-directory+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointcost+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointcostparams+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointprop+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointpropparams+json": { + source: "iana", + compressible: true + }, + "application/alto-error+json": { + source: "iana", + compressible: true + }, + "application/alto-networkmap+json": { + source: "iana", + compressible: true + }, + "application/alto-networkmapfilter+json": { + source: "iana", + compressible: true + }, + "application/alto-updatestreamcontrol+json": { + source: "iana", + compressible: true + }, + "application/alto-updatestreamparams+json": { + source: "iana", + compressible: true + }, + "application/aml": { + source: "iana" + }, + "application/andrew-inset": { + source: "iana", + extensions: ["ez"] + }, + "application/applefile": { + source: "iana" + }, + "application/applixware": { + source: "apache", + extensions: ["aw"] + }, + "application/at+jwt": { + source: "iana" + }, + "application/atf": { + source: "iana" + }, + "application/atfx": { + source: "iana" + }, + "application/atom+xml": { + source: "iana", + compressible: true, + extensions: ["atom"] + }, + "application/atomcat+xml": { + source: "iana", + compressible: true, + extensions: ["atomcat"] + }, + "application/atomdeleted+xml": { + source: "iana", + compressible: true, + extensions: ["atomdeleted"] + }, + "application/atomicmail": { + source: "iana" + }, + "application/atomsvc+xml": { + source: "iana", + compressible: true, + extensions: ["atomsvc"] + }, + "application/atsc-dwd+xml": { + source: "iana", + compressible: true, + extensions: ["dwd"] + }, + "application/atsc-dynamic-event-message": { + source: "iana" + }, + "application/atsc-held+xml": { + source: "iana", + compressible: true, + extensions: ["held"] + }, + "application/atsc-rdt+json": { + source: "iana", + compressible: true + }, + "application/atsc-rsat+xml": { + source: "iana", + compressible: true, + extensions: ["rsat"] + }, + "application/atxml": { + source: "iana" + }, + "application/auth-policy+xml": { + source: "iana", + compressible: true + }, + "application/bacnet-xdd+zip": { + source: "iana", + compressible: false + }, + "application/batch-smtp": { + source: "iana" + }, + "application/bdoc": { + compressible: false, + extensions: ["bdoc"] + }, + "application/beep+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/calendar+json": { + source: "iana", + compressible: true + }, + "application/calendar+xml": { + source: "iana", + compressible: true, + extensions: ["xcs"] + }, + "application/call-completion": { + source: "iana" + }, + "application/cals-1840": { + source: "iana" + }, + "application/captive+json": { + source: "iana", + compressible: true + }, + "application/cbor": { + source: "iana" + }, + "application/cbor-seq": { + source: "iana" + }, + "application/cccex": { + source: "iana" + }, + "application/ccmp+xml": { + source: "iana", + compressible: true + }, + "application/ccxml+xml": { + source: "iana", + compressible: true, + extensions: ["ccxml"] + }, + "application/cdfx+xml": { + source: "iana", + compressible: true, + extensions: ["cdfx"] + }, + "application/cdmi-capability": { + source: "iana", + extensions: ["cdmia"] + }, + "application/cdmi-container": { + source: "iana", + extensions: ["cdmic"] + }, + "application/cdmi-domain": { + source: "iana", + extensions: ["cdmid"] + }, + "application/cdmi-object": { + source: "iana", + extensions: ["cdmio"] + }, + "application/cdmi-queue": { + source: "iana", + extensions: ["cdmiq"] + }, + "application/cdni": { + source: "iana" + }, + "application/cea": { + source: "iana" + }, + "application/cea-2018+xml": { + source: "iana", + compressible: true + }, + "application/cellml+xml": { + source: "iana", + compressible: true + }, + "application/cfw": { + source: "iana" + }, + "application/city+json": { + source: "iana", + compressible: true + }, + "application/clr": { + source: "iana" + }, + "application/clue+xml": { + source: "iana", + compressible: true + }, + "application/clue_info+xml": { + source: "iana", + compressible: true + }, + "application/cms": { + source: "iana" + }, + "application/cnrp+xml": { + source: "iana", + compressible: true + }, + "application/coap-group+json": { + source: "iana", + compressible: true + }, + "application/coap-payload": { + source: "iana" + }, + "application/commonground": { + source: "iana" + }, + "application/conference-info+xml": { + source: "iana", + compressible: true + }, + "application/cose": { + source: "iana" + }, + "application/cose-key": { + source: "iana" + }, + "application/cose-key-set": { + source: "iana" + }, + "application/cpl+xml": { + source: "iana", + compressible: true, + extensions: ["cpl"] + }, + "application/csrattrs": { + source: "iana" + }, + "application/csta+xml": { + source: "iana", + compressible: true + }, + "application/cstadata+xml": { + source: "iana", + compressible: true + }, + "application/csvm+json": { + source: "iana", + compressible: true + }, + "application/cu-seeme": { + source: "apache", + extensions: ["cu"] + }, + "application/cwt": { + source: "iana" + }, + "application/cybercash": { + source: "iana" + }, + "application/dart": { + compressible: true + }, + "application/dash+xml": { + source: "iana", + compressible: true, + extensions: ["mpd"] + }, + "application/dash-patch+xml": { + source: "iana", + compressible: true, + extensions: ["mpp"] + }, + "application/dashdelta": { + source: "iana" + }, + "application/davmount+xml": { + source: "iana", + compressible: true, + extensions: ["davmount"] + }, + "application/dca-rft": { + source: "iana" + }, + "application/dcd": { + source: "iana" + }, + "application/dec-dx": { + source: "iana" + }, + "application/dialog-info+xml": { + source: "iana", + compressible: true + }, + "application/dicom": { + source: "iana" + }, + "application/dicom+json": { + source: "iana", + compressible: true + }, + "application/dicom+xml": { + source: "iana", + compressible: true + }, + "application/dii": { + source: "iana" + }, + "application/dit": { + source: "iana" + }, + "application/dns": { + source: "iana" + }, + "application/dns+json": { + source: "iana", + compressible: true + }, + "application/dns-message": { + source: "iana" + }, + "application/docbook+xml": { + source: "apache", + compressible: true, + extensions: ["dbk"] + }, + "application/dots+cbor": { + source: "iana" + }, + "application/dskpp+xml": { + source: "iana", + compressible: true + }, + "application/dssc+der": { + source: "iana", + extensions: ["dssc"] + }, + "application/dssc+xml": { + source: "iana", + compressible: true, + extensions: ["xdssc"] + }, + "application/dvcs": { + source: "iana" + }, + "application/ecmascript": { + source: "iana", + compressible: true, + extensions: ["es", "ecma"] + }, + "application/edi-consent": { + source: "iana" + }, + "application/edi-x12": { + source: "iana", + compressible: false + }, + "application/edifact": { + source: "iana", + compressible: false + }, + "application/efi": { + source: "iana" + }, + "application/elm+json": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/elm+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.cap+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/emergencycalldata.comment+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.control+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.deviceinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.ecall.msd": { + source: "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.serviceinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.subscriberinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.veds+xml": { + source: "iana", + compressible: true + }, + "application/emma+xml": { + source: "iana", + compressible: true, + extensions: ["emma"] + }, + "application/emotionml+xml": { + source: "iana", + compressible: true, + extensions: ["emotionml"] + }, + "application/encaprtp": { + source: "iana" + }, + "application/epp+xml": { + source: "iana", + compressible: true + }, + "application/epub+zip": { + source: "iana", + compressible: false, + extensions: ["epub"] + }, + "application/eshop": { + source: "iana" + }, + "application/exi": { + source: "iana", + extensions: ["exi"] + }, + "application/expect-ct-report+json": { + source: "iana", + compressible: true + }, + "application/express": { + source: "iana", + extensions: ["exp"] + }, + "application/fastinfoset": { + source: "iana" + }, + "application/fastsoap": { + source: "iana" + }, + "application/fdt+xml": { + source: "iana", + compressible: true, + extensions: ["fdt"] + }, + "application/fhir+json": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/fhir+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/fido.trusted-apps+json": { + compressible: true + }, + "application/fits": { + source: "iana" + }, + "application/flexfec": { + source: "iana" + }, + "application/font-sfnt": { + source: "iana" + }, + "application/font-tdpfr": { + source: "iana", + extensions: ["pfr"] + }, + "application/font-woff": { + source: "iana", + compressible: false + }, + "application/framework-attributes+xml": { + source: "iana", + compressible: true + }, + "application/geo+json": { + source: "iana", + compressible: true, + extensions: ["geojson"] + }, + "application/geo+json-seq": { + source: "iana" + }, + "application/geopackage+sqlite3": { + source: "iana" + }, + "application/geoxacml+xml": { + source: "iana", + compressible: true + }, + "application/gltf-buffer": { + source: "iana" + }, + "application/gml+xml": { + source: "iana", + compressible: true, + extensions: ["gml"] + }, + "application/gpx+xml": { + source: "apache", + compressible: true, + extensions: ["gpx"] + }, + "application/gxf": { + source: "apache", + extensions: ["gxf"] + }, + "application/gzip": { + source: "iana", + compressible: false, + extensions: ["gz"] + }, + "application/h224": { + source: "iana" + }, + "application/held+xml": { + source: "iana", + compressible: true + }, + "application/hjson": { + extensions: ["hjson"] + }, + "application/http": { + source: "iana" + }, + "application/hyperstudio": { + source: "iana", + extensions: ["stk"] + }, + "application/ibe-key-request+xml": { + source: "iana", + compressible: true + }, + "application/ibe-pkg-reply+xml": { + source: "iana", + compressible: true + }, + "application/ibe-pp-data": { + source: "iana" + }, + "application/iges": { + source: "iana" + }, + "application/im-iscomposing+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/index": { + source: "iana" + }, + "application/index.cmd": { + source: "iana" + }, + "application/index.obj": { + source: "iana" + }, + "application/index.response": { + source: "iana" + }, + "application/index.vnd": { + source: "iana" + }, + "application/inkml+xml": { + source: "iana", + compressible: true, + extensions: ["ink", "inkml"] + }, + "application/iotp": { + source: "iana" + }, + "application/ipfix": { + source: "iana", + extensions: ["ipfix"] + }, + "application/ipp": { + source: "iana" + }, + "application/isup": { + source: "iana" + }, + "application/its+xml": { + source: "iana", + compressible: true, + extensions: ["its"] + }, + "application/java-archive": { + source: "apache", + compressible: false, + extensions: ["jar", "war", "ear"] + }, + "application/java-serialized-object": { + source: "apache", + compressible: false, + extensions: ["ser"] + }, + "application/java-vm": { + source: "apache", + compressible: false, + extensions: ["class"] + }, + "application/javascript": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["js", "mjs"] + }, + "application/jf2feed+json": { + source: "iana", + compressible: true + }, + "application/jose": { + source: "iana" + }, + "application/jose+json": { + source: "iana", + compressible: true + }, + "application/jrd+json": { + source: "iana", + compressible: true + }, + "application/jscalendar+json": { + source: "iana", + compressible: true + }, + "application/json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["json", "map"] + }, + "application/json-patch+json": { + source: "iana", + compressible: true + }, + "application/json-seq": { + source: "iana" + }, + "application/json5": { + extensions: ["json5"] + }, + "application/jsonml+json": { + source: "apache", + compressible: true, + extensions: ["jsonml"] + }, + "application/jwk+json": { + source: "iana", + compressible: true + }, + "application/jwk-set+json": { + source: "iana", + compressible: true + }, + "application/jwt": { + source: "iana" + }, + "application/kpml-request+xml": { + source: "iana", + compressible: true + }, + "application/kpml-response+xml": { + source: "iana", + compressible: true + }, + "application/ld+json": { + source: "iana", + compressible: true, + extensions: ["jsonld"] + }, + "application/lgr+xml": { + source: "iana", + compressible: true, + extensions: ["lgr"] + }, + "application/link-format": { + source: "iana" + }, + "application/load-control+xml": { + source: "iana", + compressible: true + }, + "application/lost+xml": { + source: "iana", + compressible: true, + extensions: ["lostxml"] + }, + "application/lostsync+xml": { + source: "iana", + compressible: true + }, + "application/lpf+zip": { + source: "iana", + compressible: false + }, + "application/lxf": { + source: "iana" + }, + "application/mac-binhex40": { + source: "iana", + extensions: ["hqx"] + }, + "application/mac-compactpro": { + source: "apache", + extensions: ["cpt"] + }, + "application/macwriteii": { + source: "iana" + }, + "application/mads+xml": { + source: "iana", + compressible: true, + extensions: ["mads"] + }, + "application/manifest+json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["webmanifest"] + }, + "application/marc": { + source: "iana", + extensions: ["mrc"] + }, + "application/marcxml+xml": { + source: "iana", + compressible: true, + extensions: ["mrcx"] + }, + "application/mathematica": { + source: "iana", + extensions: ["ma", "nb", "mb"] + }, + "application/mathml+xml": { + source: "iana", + compressible: true, + extensions: ["mathml"] + }, + "application/mathml-content+xml": { + source: "iana", + compressible: true + }, + "application/mathml-presentation+xml": { + source: "iana", + compressible: true + }, + "application/mbms-associated-procedure-description+xml": { + source: "iana", + compressible: true + }, + "application/mbms-deregister+xml": { + source: "iana", + compressible: true + }, + "application/mbms-envelope+xml": { + source: "iana", + compressible: true + }, + "application/mbms-msk+xml": { + source: "iana", + compressible: true + }, + "application/mbms-msk-response+xml": { + source: "iana", + compressible: true + }, + "application/mbms-protection-description+xml": { + source: "iana", + compressible: true + }, + "application/mbms-reception-report+xml": { + source: "iana", + compressible: true + }, + "application/mbms-register+xml": { + source: "iana", + compressible: true + }, + "application/mbms-register-response+xml": { + source: "iana", + compressible: true + }, + "application/mbms-schedule+xml": { + source: "iana", + compressible: true + }, + "application/mbms-user-service-description+xml": { + source: "iana", + compressible: true + }, + "application/mbox": { + source: "iana", + extensions: ["mbox"] + }, + "application/media-policy-dataset+xml": { + source: "iana", + compressible: true, + extensions: ["mpf"] + }, + "application/media_control+xml": { + source: "iana", + compressible: true + }, + "application/mediaservercontrol+xml": { + source: "iana", + compressible: true, + extensions: ["mscml"] + }, + "application/merge-patch+json": { + source: "iana", + compressible: true + }, + "application/metalink+xml": { + source: "apache", + compressible: true, + extensions: ["metalink"] + }, + "application/metalink4+xml": { + source: "iana", + compressible: true, + extensions: ["meta4"] + }, + "application/mets+xml": { + source: "iana", + compressible: true, + extensions: ["mets"] + }, + "application/mf4": { + source: "iana" + }, + "application/mikey": { + source: "iana" + }, + "application/mipc": { + source: "iana" + }, + "application/missing-blocks+cbor-seq": { + source: "iana" + }, + "application/mmt-aei+xml": { + source: "iana", + compressible: true, + extensions: ["maei"] + }, + "application/mmt-usd+xml": { + source: "iana", + compressible: true, + extensions: ["musd"] + }, + "application/mods+xml": { + source: "iana", + compressible: true, + extensions: ["mods"] + }, + "application/moss-keys": { + source: "iana" + }, + "application/moss-signature": { + source: "iana" + }, + "application/mosskey-data": { + source: "iana" + }, + "application/mosskey-request": { + source: "iana" + }, + "application/mp21": { + source: "iana", + extensions: ["m21", "mp21"] + }, + "application/mp4": { + source: "iana", + extensions: ["mp4s", "m4p"] + }, + "application/mpeg4-generic": { + source: "iana" + }, + "application/mpeg4-iod": { + source: "iana" + }, + "application/mpeg4-iod-xmt": { + source: "iana" + }, + "application/mrb-consumer+xml": { + source: "iana", + compressible: true + }, + "application/mrb-publish+xml": { + source: "iana", + compressible: true + }, + "application/msc-ivr+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/msc-mixer+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/msword": { + source: "iana", + compressible: false, + extensions: ["doc", "dot"] + }, + "application/mud+json": { + source: "iana", + compressible: true + }, + "application/multipart-core": { + source: "iana" + }, + "application/mxf": { + source: "iana", + extensions: ["mxf"] + }, + "application/n-quads": { + source: "iana", + extensions: ["nq"] + }, + "application/n-triples": { + source: "iana", + extensions: ["nt"] + }, + "application/nasdata": { + source: "iana" + }, + "application/news-checkgroups": { + source: "iana", + charset: "US-ASCII" + }, + "application/news-groupinfo": { + source: "iana", + charset: "US-ASCII" + }, + "application/news-transmission": { + source: "iana" + }, + "application/nlsml+xml": { + source: "iana", + compressible: true + }, + "application/node": { + source: "iana", + extensions: ["cjs"] + }, + "application/nss": { + source: "iana" + }, + "application/oauth-authz-req+jwt": { + source: "iana" + }, + "application/oblivious-dns-message": { + source: "iana" + }, + "application/ocsp-request": { + source: "iana" + }, + "application/ocsp-response": { + source: "iana" + }, + "application/octet-stream": { + source: "iana", + compressible: false, + extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"] + }, + "application/oda": { + source: "iana", + extensions: ["oda"] + }, + "application/odm+xml": { + source: "iana", + compressible: true + }, + "application/odx": { + source: "iana" + }, + "application/oebps-package+xml": { + source: "iana", + compressible: true, + extensions: ["opf"] + }, + "application/ogg": { + source: "iana", + compressible: false, + extensions: ["ogx"] + }, + "application/omdoc+xml": { + source: "apache", + compressible: true, + extensions: ["omdoc"] + }, + "application/onenote": { + source: "apache", + extensions: ["onetoc", "onetoc2", "onetmp", "onepkg"] + }, + "application/opc-nodeset+xml": { + source: "iana", + compressible: true + }, + "application/oscore": { + source: "iana" + }, + "application/oxps": { + source: "iana", + extensions: ["oxps"] + }, + "application/p21": { + source: "iana" + }, + "application/p21+zip": { + source: "iana", + compressible: false + }, + "application/p2p-overlay+xml": { + source: "iana", + compressible: true, + extensions: ["relo"] + }, + "application/parityfec": { + source: "iana" + }, + "application/passport": { + source: "iana" + }, + "application/patch-ops-error+xml": { + source: "iana", + compressible: true, + extensions: ["xer"] + }, + "application/pdf": { + source: "iana", + compressible: false, + extensions: ["pdf"] + }, + "application/pdx": { + source: "iana" + }, + "application/pem-certificate-chain": { + source: "iana" + }, + "application/pgp-encrypted": { + source: "iana", + compressible: false, + extensions: ["pgp"] + }, + "application/pgp-keys": { + source: "iana", + extensions: ["asc"] + }, + "application/pgp-signature": { + source: "iana", + extensions: ["asc", "sig"] + }, + "application/pics-rules": { + source: "apache", + extensions: ["prf"] + }, + "application/pidf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/pidf-diff+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/pkcs10": { + source: "iana", + extensions: ["p10"] + }, + "application/pkcs12": { + source: "iana" + }, + "application/pkcs7-mime": { + source: "iana", + extensions: ["p7m", "p7c"] + }, + "application/pkcs7-signature": { + source: "iana", + extensions: ["p7s"] + }, + "application/pkcs8": { + source: "iana", + extensions: ["p8"] + }, + "application/pkcs8-encrypted": { + source: "iana" + }, + "application/pkix-attr-cert": { + source: "iana", + extensions: ["ac"] + }, + "application/pkix-cert": { + source: "iana", + extensions: ["cer"] + }, + "application/pkix-crl": { + source: "iana", + extensions: ["crl"] + }, + "application/pkix-pkipath": { + source: "iana", + extensions: ["pkipath"] + }, + "application/pkixcmp": { + source: "iana", + extensions: ["pki"] + }, + "application/pls+xml": { + source: "iana", + compressible: true, + extensions: ["pls"] + }, + "application/poc-settings+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/postscript": { + source: "iana", + compressible: true, + extensions: ["ai", "eps", "ps"] + }, + "application/ppsp-tracker+json": { + source: "iana", + compressible: true + }, + "application/problem+json": { + source: "iana", + compressible: true + }, + "application/problem+xml": { + source: "iana", + compressible: true + }, + "application/provenance+xml": { + source: "iana", + compressible: true, + extensions: ["provx"] + }, + "application/prs.alvestrand.titrax-sheet": { + source: "iana" + }, + "application/prs.cww": { + source: "iana", + extensions: ["cww"] + }, + "application/prs.cyn": { + source: "iana", + charset: "7-BIT" + }, + "application/prs.hpub+zip": { + source: "iana", + compressible: false + }, + "application/prs.nprend": { + source: "iana" + }, + "application/prs.plucker": { + source: "iana" + }, + "application/prs.rdf-xml-crypt": { + source: "iana" + }, + "application/prs.xsf+xml": { + source: "iana", + compressible: true + }, + "application/pskc+xml": { + source: "iana", + compressible: true, + extensions: ["pskcxml"] + }, + "application/pvd+json": { + source: "iana", + compressible: true + }, + "application/qsig": { + source: "iana" + }, + "application/raml+yaml": { + compressible: true, + extensions: ["raml"] + }, + "application/raptorfec": { + source: "iana" + }, + "application/rdap+json": { + source: "iana", + compressible: true + }, + "application/rdf+xml": { + source: "iana", + compressible: true, + extensions: ["rdf", "owl"] + }, + "application/reginfo+xml": { + source: "iana", + compressible: true, + extensions: ["rif"] + }, + "application/relax-ng-compact-syntax": { + source: "iana", + extensions: ["rnc"] + }, + "application/remote-printing": { + source: "iana" + }, + "application/reputon+json": { + source: "iana", + compressible: true + }, + "application/resource-lists+xml": { + source: "iana", + compressible: true, + extensions: ["rl"] + }, + "application/resource-lists-diff+xml": { + source: "iana", + compressible: true, + extensions: ["rld"] + }, + "application/rfc+xml": { + source: "iana", + compressible: true + }, + "application/riscos": { + source: "iana" + }, + "application/rlmi+xml": { + source: "iana", + compressible: true + }, + "application/rls-services+xml": { + source: "iana", + compressible: true, + extensions: ["rs"] + }, + "application/route-apd+xml": { + source: "iana", + compressible: true, + extensions: ["rapd"] + }, + "application/route-s-tsid+xml": { + source: "iana", + compressible: true, + extensions: ["sls"] + }, + "application/route-usd+xml": { + source: "iana", + compressible: true, + extensions: ["rusd"] + }, + "application/rpki-ghostbusters": { + source: "iana", + extensions: ["gbr"] + }, + "application/rpki-manifest": { + source: "iana", + extensions: ["mft"] + }, + "application/rpki-publication": { + source: "iana" + }, + "application/rpki-roa": { + source: "iana", + extensions: ["roa"] + }, + "application/rpki-updown": { + source: "iana" + }, + "application/rsd+xml": { + source: "apache", + compressible: true, + extensions: ["rsd"] + }, + "application/rss+xml": { + source: "apache", + compressible: true, + extensions: ["rss"] + }, + "application/rtf": { + source: "iana", + compressible: true, + extensions: ["rtf"] + }, + "application/rtploopback": { + source: "iana" + }, + "application/rtx": { + source: "iana" + }, + "application/samlassertion+xml": { + source: "iana", + compressible: true + }, + "application/samlmetadata+xml": { + source: "iana", + compressible: true + }, + "application/sarif+json": { + source: "iana", + compressible: true + }, + "application/sarif-external-properties+json": { + source: "iana", + compressible: true + }, + "application/sbe": { + source: "iana" + }, + "application/sbml+xml": { + source: "iana", + compressible: true, + extensions: ["sbml"] + }, + "application/scaip+xml": { + source: "iana", + compressible: true + }, + "application/scim+json": { + source: "iana", + compressible: true + }, + "application/scvp-cv-request": { + source: "iana", + extensions: ["scq"] + }, + "application/scvp-cv-response": { + source: "iana", + extensions: ["scs"] + }, + "application/scvp-vp-request": { + source: "iana", + extensions: ["spq"] + }, + "application/scvp-vp-response": { + source: "iana", + extensions: ["spp"] + }, + "application/sdp": { + source: "iana", + extensions: ["sdp"] + }, + "application/secevent+jwt": { + source: "iana" + }, + "application/senml+cbor": { + source: "iana" + }, + "application/senml+json": { + source: "iana", + compressible: true + }, + "application/senml+xml": { + source: "iana", + compressible: true, + extensions: ["senmlx"] + }, + "application/senml-etch+cbor": { + source: "iana" + }, + "application/senml-etch+json": { + source: "iana", + compressible: true + }, + "application/senml-exi": { + source: "iana" + }, + "application/sensml+cbor": { + source: "iana" + }, + "application/sensml+json": { + source: "iana", + compressible: true + }, + "application/sensml+xml": { + source: "iana", + compressible: true, + extensions: ["sensmlx"] + }, + "application/sensml-exi": { + source: "iana" + }, + "application/sep+xml": { + source: "iana", + compressible: true + }, + "application/sep-exi": { + source: "iana" + }, + "application/session-info": { + source: "iana" + }, + "application/set-payment": { + source: "iana" + }, + "application/set-payment-initiation": { + source: "iana", + extensions: ["setpay"] + }, + "application/set-registration": { + source: "iana" + }, + "application/set-registration-initiation": { + source: "iana", + extensions: ["setreg"] + }, + "application/sgml": { + source: "iana" + }, + "application/sgml-open-catalog": { + source: "iana" + }, + "application/shf+xml": { + source: "iana", + compressible: true, + extensions: ["shf"] + }, + "application/sieve": { + source: "iana", + extensions: ["siv", "sieve"] + }, + "application/simple-filter+xml": { + source: "iana", + compressible: true + }, + "application/simple-message-summary": { + source: "iana" + }, + "application/simplesymbolcontainer": { + source: "iana" + }, + "application/sipc": { + source: "iana" + }, + "application/slate": { + source: "iana" + }, + "application/smil": { + source: "iana" + }, + "application/smil+xml": { + source: "iana", + compressible: true, + extensions: ["smi", "smil"] + }, + "application/smpte336m": { + source: "iana" + }, + "application/soap+fastinfoset": { + source: "iana" + }, + "application/soap+xml": { + source: "iana", + compressible: true + }, + "application/sparql-query": { + source: "iana", + extensions: ["rq"] + }, + "application/sparql-results+xml": { + source: "iana", + compressible: true, + extensions: ["srx"] + }, + "application/spdx+json": { + source: "iana", + compressible: true + }, + "application/spirits-event+xml": { + source: "iana", + compressible: true + }, + "application/sql": { + source: "iana" + }, + "application/srgs": { + source: "iana", + extensions: ["gram"] + }, + "application/srgs+xml": { + source: "iana", + compressible: true, + extensions: ["grxml"] + }, + "application/sru+xml": { + source: "iana", + compressible: true, + extensions: ["sru"] + }, + "application/ssdl+xml": { + source: "apache", + compressible: true, + extensions: ["ssdl"] + }, + "application/ssml+xml": { + source: "iana", + compressible: true, + extensions: ["ssml"] + }, + "application/stix+json": { + source: "iana", + compressible: true + }, + "application/swid+xml": { + source: "iana", + compressible: true, + extensions: ["swidtag"] + }, + "application/tamp-apex-update": { + source: "iana" + }, + "application/tamp-apex-update-confirm": { + source: "iana" + }, + "application/tamp-community-update": { + source: "iana" + }, + "application/tamp-community-update-confirm": { + source: "iana" + }, + "application/tamp-error": { + source: "iana" + }, + "application/tamp-sequence-adjust": { + source: "iana" + }, + "application/tamp-sequence-adjust-confirm": { + source: "iana" + }, + "application/tamp-status-query": { + source: "iana" + }, + "application/tamp-status-response": { + source: "iana" + }, + "application/tamp-update": { + source: "iana" + }, + "application/tamp-update-confirm": { + source: "iana" + }, + "application/tar": { + compressible: true + }, + "application/taxii+json": { + source: "iana", + compressible: true + }, + "application/td+json": { + source: "iana", + compressible: true + }, + "application/tei+xml": { + source: "iana", + compressible: true, + extensions: ["tei", "teicorpus"] + }, + "application/tetra_isi": { + source: "iana" + }, + "application/thraud+xml": { + source: "iana", + compressible: true, + extensions: ["tfi"] + }, + "application/timestamp-query": { + source: "iana" + }, + "application/timestamp-reply": { + source: "iana" + }, + "application/timestamped-data": { + source: "iana", + extensions: ["tsd"] + }, + "application/tlsrpt+gzip": { + source: "iana" + }, + "application/tlsrpt+json": { + source: "iana", + compressible: true + }, + "application/tnauthlist": { + source: "iana" + }, + "application/token-introspection+jwt": { + source: "iana" + }, + "application/toml": { + compressible: true, + extensions: ["toml"] + }, + "application/trickle-ice-sdpfrag": { + source: "iana" + }, + "application/trig": { + source: "iana", + extensions: ["trig"] + }, + "application/ttml+xml": { + source: "iana", + compressible: true, + extensions: ["ttml"] + }, + "application/tve-trigger": { + source: "iana" + }, + "application/tzif": { + source: "iana" + }, + "application/tzif-leap": { + source: "iana" + }, + "application/ubjson": { + compressible: false, + extensions: ["ubj"] + }, + "application/ulpfec": { + source: "iana" + }, + "application/urc-grpsheet+xml": { + source: "iana", + compressible: true + }, + "application/urc-ressheet+xml": { + source: "iana", + compressible: true, + extensions: ["rsheet"] + }, + "application/urc-targetdesc+xml": { + source: "iana", + compressible: true, + extensions: ["td"] + }, + "application/urc-uisocketdesc+xml": { + source: "iana", + compressible: true + }, + "application/vcard+json": { + source: "iana", + compressible: true + }, + "application/vcard+xml": { + source: "iana", + compressible: true + }, + "application/vemmi": { + source: "iana" + }, + "application/vividence.scriptfile": { + source: "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + source: "iana", + compressible: true, + extensions: ["1km"] + }, + "application/vnd.3gpp-prose+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-v2x-local-service-information": { + source: "iana" + }, + "application/vnd.3gpp.5gnas": { + source: "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.bsf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.gmop+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.gtpc": { + source: "iana" + }, + "application/vnd.3gpp.interworking-data": { + source: "iana" + }, + "application/vnd.3gpp.lpp": { + source: "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-payload": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-signalling": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mid-call+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.ngap": { + source: "iana" + }, + "application/vnd.3gpp.pfcp": { + source: "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + source: "iana", + extensions: ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + source: "iana", + extensions: ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + source: "iana", + extensions: ["pvb"] + }, + "application/vnd.3gpp.s1ap": { + source: "iana" + }, + "application/vnd.3gpp.sms": { + source: "iana" + }, + "application/vnd.3gpp.sms+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.srvcc-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.ussd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp2.sms": { + source: "iana" + }, + "application/vnd.3gpp2.tcap": { + source: "iana", + extensions: ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + source: "iana" + }, + "application/vnd.3m.post-it-notes": { + source: "iana", + extensions: ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + source: "iana", + extensions: ["aso"] + }, + "application/vnd.accpac.simply.imp": { + source: "iana", + extensions: ["imp"] + }, + "application/vnd.acucobol": { + source: "iana", + extensions: ["acu"] + }, + "application/vnd.acucorp": { + source: "iana", + extensions: ["atc", "acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + source: "apache", + compressible: false, + extensions: ["air"] + }, + "application/vnd.adobe.flash.movie": { + source: "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + source: "iana", + extensions: ["fcdt"] + }, + "application/vnd.adobe.fxp": { + source: "iana", + extensions: ["fxp", "fxpl"] + }, + "application/vnd.adobe.partial-upload": { + source: "iana" + }, + "application/vnd.adobe.xdp+xml": { + source: "iana", + compressible: true, + extensions: ["xdp"] + }, + "application/vnd.adobe.xfdf": { + source: "iana", + extensions: ["xfdf"] + }, + "application/vnd.aether.imp": { + source: "iana" + }, + "application/vnd.afpc.afplinedata": { + source: "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + source: "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + source: "iana" + }, + "application/vnd.afpc.foca-charset": { + source: "iana" + }, + "application/vnd.afpc.foca-codedfont": { + source: "iana" + }, + "application/vnd.afpc.foca-codepage": { + source: "iana" + }, + "application/vnd.afpc.modca": { + source: "iana" + }, + "application/vnd.afpc.modca-cmtable": { + source: "iana" + }, + "application/vnd.afpc.modca-formdef": { + source: "iana" + }, + "application/vnd.afpc.modca-mediummap": { + source: "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + source: "iana" + }, + "application/vnd.afpc.modca-overlay": { + source: "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + source: "iana" + }, + "application/vnd.age": { + source: "iana", + extensions: ["age"] + }, + "application/vnd.ah-barcode": { + source: "iana" + }, + "application/vnd.ahead.space": { + source: "iana", + extensions: ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + source: "iana", + extensions: ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + source: "iana", + extensions: ["azs"] + }, + "application/vnd.amadeus+json": { + source: "iana", + compressible: true + }, + "application/vnd.amazon.ebook": { + source: "apache", + extensions: ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + source: "iana" + }, + "application/vnd.americandynamics.acc": { + source: "iana", + extensions: ["acc"] + }, + "application/vnd.amiga.ami": { + source: "iana", + extensions: ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + source: "iana", + compressible: true + }, + "application/vnd.android.ota": { + source: "iana" + }, + "application/vnd.android.package-archive": { + source: "apache", + compressible: false, + extensions: ["apk"] + }, + "application/vnd.anki": { + source: "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + source: "iana", + extensions: ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + source: "apache", + extensions: ["fti"] + }, + "application/vnd.antix.game-component": { + source: "iana", + extensions: ["atx"] + }, + "application/vnd.apache.arrow.file": { + source: "iana" + }, + "application/vnd.apache.arrow.stream": { + source: "iana" + }, + "application/vnd.apache.thrift.binary": { + source: "iana" + }, + "application/vnd.apache.thrift.compact": { + source: "iana" + }, + "application/vnd.apache.thrift.json": { + source: "iana" + }, + "application/vnd.api+json": { + source: "iana", + compressible: true + }, + "application/vnd.aplextor.warrp+json": { + source: "iana", + compressible: true + }, + "application/vnd.apothekende.reservation+json": { + source: "iana", + compressible: true + }, + "application/vnd.apple.installer+xml": { + source: "iana", + compressible: true, + extensions: ["mpkg"] + }, + "application/vnd.apple.keynote": { + source: "iana", + extensions: ["key"] + }, + "application/vnd.apple.mpegurl": { + source: "iana", + extensions: ["m3u8"] + }, + "application/vnd.apple.numbers": { + source: "iana", + extensions: ["numbers"] + }, + "application/vnd.apple.pages": { + source: "iana", + extensions: ["pages"] + }, + "application/vnd.apple.pkpass": { + compressible: false, + extensions: ["pkpass"] + }, + "application/vnd.arastra.swi": { + source: "iana" + }, + "application/vnd.aristanetworks.swi": { + source: "iana", + extensions: ["swi"] + }, + "application/vnd.artisan+json": { + source: "iana", + compressible: true + }, + "application/vnd.artsquare": { + source: "iana" + }, + "application/vnd.astraea-software.iota": { + source: "iana", + extensions: ["iota"] + }, + "application/vnd.audiograph": { + source: "iana", + extensions: ["aep"] + }, + "application/vnd.autopackage": { + source: "iana" + }, + "application/vnd.avalon+json": { + source: "iana", + compressible: true + }, + "application/vnd.avistar+xml": { + source: "iana", + compressible: true + }, + "application/vnd.balsamiq.bmml+xml": { + source: "iana", + compressible: true, + extensions: ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + source: "iana" + }, + "application/vnd.banana-accounting": { + source: "iana" + }, + "application/vnd.bbf.usp.error": { + source: "iana" + }, + "application/vnd.bbf.usp.msg": { + source: "iana" + }, + "application/vnd.bbf.usp.msg+json": { + source: "iana", + compressible: true + }, + "application/vnd.bekitzur-stech+json": { + source: "iana", + compressible: true + }, + "application/vnd.bint.med-content": { + source: "iana" + }, + "application/vnd.biopax.rdf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.blink-idb-value-wrapper": { + source: "iana" + }, + "application/vnd.blueice.multipass": { + source: "iana", + extensions: ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + source: "iana" + }, + "application/vnd.bluetooth.le.oob": { + source: "iana" + }, + "application/vnd.bmi": { + source: "iana", + extensions: ["bmi"] + }, + "application/vnd.bpf": { + source: "iana" + }, + "application/vnd.bpf3": { + source: "iana" + }, + "application/vnd.businessobjects": { + source: "iana", + extensions: ["rep"] + }, + "application/vnd.byu.uapi+json": { + source: "iana", + compressible: true + }, + "application/vnd.cab-jscript": { + source: "iana" + }, + "application/vnd.canon-cpdl": { + source: "iana" + }, + "application/vnd.canon-lips": { + source: "iana" + }, + "application/vnd.capasystems-pg+json": { + source: "iana", + compressible: true + }, + "application/vnd.cendio.thinlinc.clientconf": { + source: "iana" + }, + "application/vnd.century-systems.tcp_stream": { + source: "iana" + }, + "application/vnd.chemdraw+xml": { + source: "iana", + compressible: true, + extensions: ["cdxml"] + }, + "application/vnd.chess-pgn": { + source: "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + source: "iana", + extensions: ["mmd"] + }, + "application/vnd.ciedi": { + source: "iana" + }, + "application/vnd.cinderella": { + source: "iana", + extensions: ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + source: "iana" + }, + "application/vnd.citationstyles.style+xml": { + source: "iana", + compressible: true, + extensions: ["csl"] + }, + "application/vnd.claymore": { + source: "iana", + extensions: ["cla"] + }, + "application/vnd.cloanto.rp9": { + source: "iana", + extensions: ["rp9"] + }, + "application/vnd.clonk.c4group": { + source: "iana", + extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + source: "iana", + extensions: ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + source: "iana", + extensions: ["c11amz"] + }, + "application/vnd.coffeescript": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.document": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + source: "iana" + }, + "application/vnd.collection+json": { + source: "iana", + compressible: true + }, + "application/vnd.collection.doc+json": { + source: "iana", + compressible: true + }, + "application/vnd.collection.next+json": { + source: "iana", + compressible: true + }, + "application/vnd.comicbook+zip": { + source: "iana", + compressible: false + }, + "application/vnd.comicbook-rar": { + source: "iana" + }, + "application/vnd.commerce-battelle": { + source: "iana" + }, + "application/vnd.commonspace": { + source: "iana", + extensions: ["csp"] + }, + "application/vnd.contact.cmsg": { + source: "iana", + extensions: ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + source: "iana", + compressible: true + }, + "application/vnd.cosmocaller": { + source: "iana", + extensions: ["cmc"] + }, + "application/vnd.crick.clicker": { + source: "iana", + extensions: ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + source: "iana", + extensions: ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + source: "iana", + extensions: ["clkp"] + }, + "application/vnd.crick.clicker.template": { + source: "iana", + extensions: ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + source: "iana", + extensions: ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + source: "iana", + compressible: true, + extensions: ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + source: "iana", + compressible: true + }, + "application/vnd.crypto-shade-file": { + source: "iana" + }, + "application/vnd.cryptomator.encrypted": { + source: "iana" + }, + "application/vnd.cryptomator.vault": { + source: "iana" + }, + "application/vnd.ctc-posml": { + source: "iana", + extensions: ["pml"] + }, + "application/vnd.ctct.ws+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cups-pdf": { + source: "iana" + }, + "application/vnd.cups-postscript": { + source: "iana" + }, + "application/vnd.cups-ppd": { + source: "iana", + extensions: ["ppd"] + }, + "application/vnd.cups-raster": { + source: "iana" + }, + "application/vnd.cups-raw": { + source: "iana" + }, + "application/vnd.curl": { + source: "iana" + }, + "application/vnd.curl.car": { + source: "apache", + extensions: ["car"] + }, + "application/vnd.curl.pcurl": { + source: "apache", + extensions: ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cybank": { + source: "iana" + }, + "application/vnd.cyclonedx+json": { + source: "iana", + compressible: true + }, + "application/vnd.cyclonedx+xml": { + source: "iana", + compressible: true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + source: "iana", + compressible: false + }, + "application/vnd.d3m-dataset": { + source: "iana" + }, + "application/vnd.d3m-problem": { + source: "iana" + }, + "application/vnd.dart": { + source: "iana", + compressible: true, + extensions: ["dart"] + }, + "application/vnd.data-vision.rdz": { + source: "iana", + extensions: ["rdz"] + }, + "application/vnd.datapackage+json": { + source: "iana", + compressible: true + }, + "application/vnd.dataresource+json": { + source: "iana", + compressible: true + }, + "application/vnd.dbf": { + source: "iana", + extensions: ["dbf"] + }, + "application/vnd.debian.binary-package": { + source: "iana" + }, + "application/vnd.dece.data": { + source: "iana", + extensions: ["uvf", "uvvf", "uvd", "uvvd"] + }, + "application/vnd.dece.ttml+xml": { + source: "iana", + compressible: true, + extensions: ["uvt", "uvvt"] + }, + "application/vnd.dece.unspecified": { + source: "iana", + extensions: ["uvx", "uvvx"] + }, + "application/vnd.dece.zip": { + source: "iana", + extensions: ["uvz", "uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + source: "iana", + extensions: ["fe_launch"] + }, + "application/vnd.desmume.movie": { + source: "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + source: "iana" + }, + "application/vnd.dm.delegation+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dna": { + source: "iana", + extensions: ["dna"] + }, + "application/vnd.document+json": { + source: "iana", + compressible: true + }, + "application/vnd.dolby.mlp": { + source: "apache", + extensions: ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + source: "iana" + }, + "application/vnd.dolby.mobile.2": { + source: "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + source: "iana" + }, + "application/vnd.dpgraph": { + source: "iana", + extensions: ["dpg"] + }, + "application/vnd.dreamfactory": { + source: "iana", + extensions: ["dfac"] + }, + "application/vnd.drive+json": { + source: "iana", + compressible: true + }, + "application/vnd.ds-keypoint": { + source: "apache", + extensions: ["kpxx"] + }, + "application/vnd.dtg.local": { + source: "iana" + }, + "application/vnd.dtg.local.flash": { + source: "iana" + }, + "application/vnd.dtg.local.html": { + source: "iana" + }, + "application/vnd.dvb.ait": { + source: "iana", + extensions: ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.dvbj": { + source: "iana" + }, + "application/vnd.dvb.esgcontainer": { + source: "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + source: "iana" + }, + "application/vnd.dvb.ipdcroaming": { + source: "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + source: "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + source: "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-container+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-generic+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-init+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.pfr": { + source: "iana" + }, + "application/vnd.dvb.service": { + source: "iana", + extensions: ["svc"] + }, + "application/vnd.dxr": { + source: "iana" + }, + "application/vnd.dynageo": { + source: "iana", + extensions: ["geo"] + }, + "application/vnd.dzr": { + source: "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + source: "iana" + }, + "application/vnd.ecdis-update": { + source: "iana" + }, + "application/vnd.ecip.rlp": { + source: "iana" + }, + "application/vnd.eclipse.ditto+json": { + source: "iana", + compressible: true + }, + "application/vnd.ecowin.chart": { + source: "iana", + extensions: ["mag"] + }, + "application/vnd.ecowin.filerequest": { + source: "iana" + }, + "application/vnd.ecowin.fileupdate": { + source: "iana" + }, + "application/vnd.ecowin.series": { + source: "iana" + }, + "application/vnd.ecowin.seriesrequest": { + source: "iana" + }, + "application/vnd.ecowin.seriesupdate": { + source: "iana" + }, + "application/vnd.efi.img": { + source: "iana" + }, + "application/vnd.efi.iso": { + source: "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + source: "iana", + compressible: true + }, + "application/vnd.enliven": { + source: "iana", + extensions: ["nml"] + }, + "application/vnd.enphase.envoy": { + source: "iana" + }, + "application/vnd.eprints.data+xml": { + source: "iana", + compressible: true + }, + "application/vnd.epson.esf": { + source: "iana", + extensions: ["esf"] + }, + "application/vnd.epson.msf": { + source: "iana", + extensions: ["msf"] + }, + "application/vnd.epson.quickanime": { + source: "iana", + extensions: ["qam"] + }, + "application/vnd.epson.salt": { + source: "iana", + extensions: ["slt"] + }, + "application/vnd.epson.ssf": { + source: "iana", + extensions: ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + source: "iana" + }, + "application/vnd.espass-espass+zip": { + source: "iana", + compressible: false + }, + "application/vnd.eszigno3+xml": { + source: "iana", + compressible: true, + extensions: ["es3", "et3"] + }, + "application/vnd.etsi.aoc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.asic-e+zip": { + source: "iana", + compressible: false + }, + "application/vnd.etsi.asic-s+zip": { + source: "iana", + compressible: false + }, + "application/vnd.etsi.cug+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvcommand+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvservice+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsync+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvueprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.mcid+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.mheg5": { + source: "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.pstn+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.sci+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.simservs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.timestamp-token": { + source: "iana" + }, + "application/vnd.etsi.tsl+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.tsl.der": { + source: "iana" + }, + "application/vnd.eu.kasparian.car+json": { + source: "iana", + compressible: true + }, + "application/vnd.eudora.data": { + source: "iana" + }, + "application/vnd.evolv.ecig.profile": { + source: "iana" + }, + "application/vnd.evolv.ecig.settings": { + source: "iana" + }, + "application/vnd.evolv.ecig.theme": { + source: "iana" + }, + "application/vnd.exstream-empower+zip": { + source: "iana", + compressible: false + }, + "application/vnd.exstream-package": { + source: "iana" + }, + "application/vnd.ezpix-album": { + source: "iana", + extensions: ["ez2"] + }, + "application/vnd.ezpix-package": { + source: "iana", + extensions: ["ez3"] + }, + "application/vnd.f-secure.mobile": { + source: "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + source: "iana", + compressible: false + }, + "application/vnd.fastcopy-disk-image": { + source: "iana" + }, + "application/vnd.fdf": { + source: "iana", + extensions: ["fdf"] + }, + "application/vnd.fdsn.mseed": { + source: "iana", + extensions: ["mseed"] + }, + "application/vnd.fdsn.seed": { + source: "iana", + extensions: ["seed", "dataless"] + }, + "application/vnd.ffsns": { + source: "iana" + }, + "application/vnd.ficlab.flb+zip": { + source: "iana", + compressible: false + }, + "application/vnd.filmit.zfc": { + source: "iana" + }, + "application/vnd.fints": { + source: "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + source: "iana" + }, + "application/vnd.flographit": { + source: "iana", + extensions: ["gph"] + }, + "application/vnd.fluxtime.clip": { + source: "iana", + extensions: ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + source: "iana" + }, + "application/vnd.framemaker": { + source: "iana", + extensions: ["fm", "frame", "maker", "book"] + }, + "application/vnd.frogans.fnc": { + source: "iana", + extensions: ["fnc"] + }, + "application/vnd.frogans.ltf": { + source: "iana", + extensions: ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + source: "iana", + extensions: ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + source: "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + source: "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + source: "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + source: "iana", + compressible: true + }, + "application/vnd.fujitsu.oasys": { + source: "iana", + extensions: ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + source: "iana", + extensions: ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + source: "iana", + extensions: ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + source: "iana", + extensions: ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + source: "iana", + extensions: ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + source: "iana" + }, + "application/vnd.fujixerox.art4": { + source: "iana" + }, + "application/vnd.fujixerox.ddd": { + source: "iana", + extensions: ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + source: "iana", + extensions: ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + source: "iana", + extensions: ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + source: "iana" + }, + "application/vnd.fujixerox.hbpl": { + source: "iana" + }, + "application/vnd.fut-misnet": { + source: "iana" + }, + "application/vnd.futoin+cbor": { + source: "iana" + }, + "application/vnd.futoin+json": { + source: "iana", + compressible: true + }, + "application/vnd.fuzzysheet": { + source: "iana", + extensions: ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + source: "iana", + extensions: ["txd"] + }, + "application/vnd.gentics.grd+json": { + source: "iana", + compressible: true + }, + "application/vnd.geo+json": { + source: "iana", + compressible: true + }, + "application/vnd.geocube+xml": { + source: "iana", + compressible: true + }, + "application/vnd.geogebra.file": { + source: "iana", + extensions: ["ggb"] + }, + "application/vnd.geogebra.slides": { + source: "iana" + }, + "application/vnd.geogebra.tool": { + source: "iana", + extensions: ["ggt"] + }, + "application/vnd.geometry-explorer": { + source: "iana", + extensions: ["gex", "gre"] + }, + "application/vnd.geonext": { + source: "iana", + extensions: ["gxt"] + }, + "application/vnd.geoplan": { + source: "iana", + extensions: ["g2w"] + }, + "application/vnd.geospace": { + source: "iana", + extensions: ["g3w"] + }, + "application/vnd.gerber": { + source: "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + source: "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + source: "iana" + }, + "application/vnd.gmx": { + source: "iana", + extensions: ["gmx"] + }, + "application/vnd.google-apps.document": { + compressible: false, + extensions: ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + compressible: false, + extensions: ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + compressible: false, + extensions: ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + source: "iana", + compressible: true, + extensions: ["kml"] + }, + "application/vnd.google-earth.kmz": { + source: "iana", + compressible: false, + extensions: ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + source: "iana", + compressible: true + }, + "application/vnd.gov.sk.e-form+zip": { + source: "iana", + compressible: false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + source: "iana", + compressible: true + }, + "application/vnd.grafeq": { + source: "iana", + extensions: ["gqf", "gqs"] + }, + "application/vnd.gridmp": { + source: "iana" + }, + "application/vnd.groove-account": { + source: "iana", + extensions: ["gac"] + }, + "application/vnd.groove-help": { + source: "iana", + extensions: ["ghf"] + }, + "application/vnd.groove-identity-message": { + source: "iana", + extensions: ["gim"] + }, + "application/vnd.groove-injector": { + source: "iana", + extensions: ["grv"] + }, + "application/vnd.groove-tool-message": { + source: "iana", + extensions: ["gtm"] + }, + "application/vnd.groove-tool-template": { + source: "iana", + extensions: ["tpl"] + }, + "application/vnd.groove-vcard": { + source: "iana", + extensions: ["vcg"] + }, + "application/vnd.hal+json": { + source: "iana", + compressible: true + }, + "application/vnd.hal+xml": { + source: "iana", + compressible: true, + extensions: ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + source: "iana", + compressible: true, + extensions: ["zmm"] + }, + "application/vnd.hbci": { + source: "iana", + extensions: ["hbci"] + }, + "application/vnd.hc+json": { + source: "iana", + compressible: true + }, + "application/vnd.hcl-bireports": { + source: "iana" + }, + "application/vnd.hdt": { + source: "iana" + }, + "application/vnd.heroku+json": { + source: "iana", + compressible: true + }, + "application/vnd.hhe.lesson-player": { + source: "iana", + extensions: ["les"] + }, + "application/vnd.hl7cda+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.hl7v2+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.hp-hpgl": { + source: "iana", + extensions: ["hpgl"] + }, + "application/vnd.hp-hpid": { + source: "iana", + extensions: ["hpid"] + }, + "application/vnd.hp-hps": { + source: "iana", + extensions: ["hps"] + }, + "application/vnd.hp-jlyt": { + source: "iana", + extensions: ["jlt"] + }, + "application/vnd.hp-pcl": { + source: "iana", + extensions: ["pcl"] + }, + "application/vnd.hp-pclxl": { + source: "iana", + extensions: ["pclxl"] + }, + "application/vnd.httphone": { + source: "iana" + }, + "application/vnd.hydrostatix.sof-data": { + source: "iana", + extensions: ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + source: "iana", + compressible: true + }, + "application/vnd.hyper-item+json": { + source: "iana", + compressible: true + }, + "application/vnd.hyperdrive+json": { + source: "iana", + compressible: true + }, + "application/vnd.hzn-3d-crossword": { + source: "iana" + }, + "application/vnd.ibm.afplinedata": { + source: "iana" + }, + "application/vnd.ibm.electronic-media": { + source: "iana" + }, + "application/vnd.ibm.minipay": { + source: "iana", + extensions: ["mpy"] + }, + "application/vnd.ibm.modcap": { + source: "iana", + extensions: ["afp", "listafp", "list3820"] + }, + "application/vnd.ibm.rights-management": { + source: "iana", + extensions: ["irm"] + }, + "application/vnd.ibm.secure-container": { + source: "iana", + extensions: ["sc"] + }, + "application/vnd.iccprofile": { + source: "iana", + extensions: ["icc", "icm"] + }, + "application/vnd.ieee.1905": { + source: "iana" + }, + "application/vnd.igloader": { + source: "iana", + extensions: ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + source: "iana", + compressible: false + }, + "application/vnd.imagemeter.image+zip": { + source: "iana", + compressible: false + }, + "application/vnd.immervision-ivp": { + source: "iana", + extensions: ["ivp"] + }, + "application/vnd.immervision-ivu": { + source: "iana", + extensions: ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + source: "iana" + }, + "application/vnd.ims.imsccv1p2": { + source: "iana" + }, + "application/vnd.ims.imsccv1p3": { + source: "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + source: "iana", + compressible: true + }, + "application/vnd.informedcontrol.rms+xml": { + source: "iana", + compressible: true + }, + "application/vnd.informix-visionary": { + source: "iana" + }, + "application/vnd.infotech.project": { + source: "iana" + }, + "application/vnd.infotech.project+xml": { + source: "iana", + compressible: true + }, + "application/vnd.innopath.wamp.notification": { + source: "iana" + }, + "application/vnd.insors.igm": { + source: "iana", + extensions: ["igm"] + }, + "application/vnd.intercon.formnet": { + source: "iana", + extensions: ["xpw", "xpx"] + }, + "application/vnd.intergeo": { + source: "iana", + extensions: ["i2g"] + }, + "application/vnd.intertrust.digibox": { + source: "iana" + }, + "application/vnd.intertrust.nncp": { + source: "iana" + }, + "application/vnd.intu.qbo": { + source: "iana", + extensions: ["qbo"] + }, + "application/vnd.intu.qfx": { + source: "iana", + extensions: ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.newsitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.packageitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.planningitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ipunplugged.rcprofile": { + source: "iana", + extensions: ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + source: "iana", + compressible: true, + extensions: ["irp"] + }, + "application/vnd.is-xpr": { + source: "iana", + extensions: ["xpr"] + }, + "application/vnd.isac.fcs": { + source: "iana", + extensions: ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + source: "iana", + compressible: false + }, + "application/vnd.jam": { + source: "iana", + extensions: ["jam"] + }, + "application/vnd.japannet-directory-service": { + source: "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + source: "iana" + }, + "application/vnd.japannet-payment-wakeup": { + source: "iana" + }, + "application/vnd.japannet-registration": { + source: "iana" + }, + "application/vnd.japannet-registration-wakeup": { + source: "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + source: "iana" + }, + "application/vnd.japannet-verification": { + source: "iana" + }, + "application/vnd.japannet-verification-wakeup": { + source: "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + source: "iana", + extensions: ["rms"] + }, + "application/vnd.jisp": { + source: "iana", + extensions: ["jisp"] + }, + "application/vnd.joost.joda-archive": { + source: "iana", + extensions: ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + source: "iana" + }, + "application/vnd.kahootz": { + source: "iana", + extensions: ["ktz", "ktr"] + }, + "application/vnd.kde.karbon": { + source: "iana", + extensions: ["karbon"] + }, + "application/vnd.kde.kchart": { + source: "iana", + extensions: ["chrt"] + }, + "application/vnd.kde.kformula": { + source: "iana", + extensions: ["kfo"] + }, + "application/vnd.kde.kivio": { + source: "iana", + extensions: ["flw"] + }, + "application/vnd.kde.kontour": { + source: "iana", + extensions: ["kon"] + }, + "application/vnd.kde.kpresenter": { + source: "iana", + extensions: ["kpr", "kpt"] + }, + "application/vnd.kde.kspread": { + source: "iana", + extensions: ["ksp"] + }, + "application/vnd.kde.kword": { + source: "iana", + extensions: ["kwd", "kwt"] + }, + "application/vnd.kenameaapp": { + source: "iana", + extensions: ["htke"] + }, + "application/vnd.kidspiration": { + source: "iana", + extensions: ["kia"] + }, + "application/vnd.kinar": { + source: "iana", + extensions: ["kne", "knp"] + }, + "application/vnd.koan": { + source: "iana", + extensions: ["skp", "skd", "skt", "skm"] + }, + "application/vnd.kodak-descriptor": { + source: "iana", + extensions: ["sse"] + }, + "application/vnd.las": { + source: "iana" + }, + "application/vnd.las.las+json": { + source: "iana", + compressible: true + }, + "application/vnd.las.las+xml": { + source: "iana", + compressible: true, + extensions: ["lasxml"] + }, + "application/vnd.laszip": { + source: "iana" + }, + "application/vnd.leap+json": { + source: "iana", + compressible: true + }, + "application/vnd.liberty-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + source: "iana", + extensions: ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + source: "iana", + compressible: true, + extensions: ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + source: "iana", + compressible: false + }, + "application/vnd.loom": { + source: "iana" + }, + "application/vnd.lotus-1-2-3": { + source: "iana", + extensions: ["123"] + }, + "application/vnd.lotus-approach": { + source: "iana", + extensions: ["apr"] + }, + "application/vnd.lotus-freelance": { + source: "iana", + extensions: ["pre"] + }, + "application/vnd.lotus-notes": { + source: "iana", + extensions: ["nsf"] + }, + "application/vnd.lotus-organizer": { + source: "iana", + extensions: ["org"] + }, + "application/vnd.lotus-screencam": { + source: "iana", + extensions: ["scm"] + }, + "application/vnd.lotus-wordpro": { + source: "iana", + extensions: ["lwp"] + }, + "application/vnd.macports.portpkg": { + source: "iana", + extensions: ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + source: "iana", + extensions: ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.conftoken+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.license+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.mdcf": { + source: "iana" + }, + "application/vnd.mason+json": { + source: "iana", + compressible: true + }, + "application/vnd.maxar.archive.3tz+zip": { + source: "iana", + compressible: false + }, + "application/vnd.maxmind.maxmind-db": { + source: "iana" + }, + "application/vnd.mcd": { + source: "iana", + extensions: ["mcd"] + }, + "application/vnd.medcalcdata": { + source: "iana", + extensions: ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + source: "iana", + extensions: ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + source: "iana" + }, + "application/vnd.mfer": { + source: "iana", + extensions: ["mwf"] + }, + "application/vnd.mfmp": { + source: "iana", + extensions: ["mfm"] + }, + "application/vnd.micro+json": { + source: "iana", + compressible: true + }, + "application/vnd.micrografx.flo": { + source: "iana", + extensions: ["flo"] + }, + "application/vnd.micrografx.igx": { + source: "iana", + extensions: ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + source: "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + source: "iana" + }, + "application/vnd.miele+json": { + source: "iana", + compressible: true + }, + "application/vnd.mif": { + source: "iana", + extensions: ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + source: "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + source: "iana" + }, + "application/vnd.mobius.daf": { + source: "iana", + extensions: ["daf"] + }, + "application/vnd.mobius.dis": { + source: "iana", + extensions: ["dis"] + }, + "application/vnd.mobius.mbk": { + source: "iana", + extensions: ["mbk"] + }, + "application/vnd.mobius.mqy": { + source: "iana", + extensions: ["mqy"] + }, + "application/vnd.mobius.msl": { + source: "iana", + extensions: ["msl"] + }, + "application/vnd.mobius.plc": { + source: "iana", + extensions: ["plc"] + }, + "application/vnd.mobius.txf": { + source: "iana", + extensions: ["txf"] + }, + "application/vnd.mophun.application": { + source: "iana", + extensions: ["mpn"] + }, + "application/vnd.mophun.certificate": { + source: "iana", + extensions: ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + source: "iana" + }, + "application/vnd.motorola.iprm": { + source: "iana" + }, + "application/vnd.mozilla.xul+xml": { + source: "iana", + compressible: true, + extensions: ["xul"] + }, + "application/vnd.ms-3mfdocument": { + source: "iana" + }, + "application/vnd.ms-artgalry": { + source: "iana", + extensions: ["cil"] + }, + "application/vnd.ms-asf": { + source: "iana" + }, + "application/vnd.ms-cab-compressed": { + source: "iana", + extensions: ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + source: "apache" + }, + "application/vnd.ms-excel": { + source: "iana", + compressible: false, + extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + source: "iana", + extensions: ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + source: "iana", + extensions: ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + source: "iana", + extensions: ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + source: "iana", + extensions: ["xltm"] + }, + "application/vnd.ms-fontobject": { + source: "iana", + compressible: true, + extensions: ["eot"] + }, + "application/vnd.ms-htmlhelp": { + source: "iana", + extensions: ["chm"] + }, + "application/vnd.ms-ims": { + source: "iana", + extensions: ["ims"] + }, + "application/vnd.ms-lrm": { + source: "iana", + extensions: ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-officetheme": { + source: "iana", + extensions: ["thmx"] + }, + "application/vnd.ms-opentype": { + source: "apache", + compressible: true + }, + "application/vnd.ms-outlook": { + compressible: false, + extensions: ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + source: "apache" + }, + "application/vnd.ms-pki.seccat": { + source: "apache", + extensions: ["cat"] + }, + "application/vnd.ms-pki.stl": { + source: "apache", + extensions: ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-powerpoint": { + source: "iana", + compressible: false, + extensions: ["ppt", "pps", "pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + source: "iana", + extensions: ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + source: "iana", + extensions: ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + source: "iana", + extensions: ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + source: "iana", + extensions: ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + source: "iana", + extensions: ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-printing.printticket+xml": { + source: "apache", + compressible: true + }, + "application/vnd.ms-printschematicket+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-project": { + source: "iana", + extensions: ["mpp", "mpt"] + }, + "application/vnd.ms-tnef": { + source: "iana" + }, + "application/vnd.ms-windows.devicepairing": { + source: "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + source: "iana" + }, + "application/vnd.ms-windows.printerpairing": { + source: "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + source: "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + source: "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + source: "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + source: "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + source: "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + source: "iana", + extensions: ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + source: "iana", + extensions: ["dotm"] + }, + "application/vnd.ms-works": { + source: "iana", + extensions: ["wps", "wks", "wcm", "wdb"] + }, + "application/vnd.ms-wpl": { + source: "iana", + extensions: ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + source: "iana", + compressible: false, + extensions: ["xps"] + }, + "application/vnd.msa-disk-image": { + source: "iana" + }, + "application/vnd.mseq": { + source: "iana", + extensions: ["mseq"] + }, + "application/vnd.msign": { + source: "iana" + }, + "application/vnd.multiad.creator": { + source: "iana" + }, + "application/vnd.multiad.creator.cif": { + source: "iana" + }, + "application/vnd.music-niff": { + source: "iana" + }, + "application/vnd.musician": { + source: "iana", + extensions: ["mus"] + }, + "application/vnd.muvee.style": { + source: "iana", + extensions: ["msty"] + }, + "application/vnd.mynfc": { + source: "iana", + extensions: ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + source: "iana", + compressible: true + }, + "application/vnd.ncd.control": { + source: "iana" + }, + "application/vnd.ncd.reference": { + source: "iana" + }, + "application/vnd.nearst.inv+json": { + source: "iana", + compressible: true + }, + "application/vnd.nebumind.line": { + source: "iana" + }, + "application/vnd.nervana": { + source: "iana" + }, + "application/vnd.netfpx": { + source: "iana" + }, + "application/vnd.neurolanguage.nlu": { + source: "iana", + extensions: ["nlu"] + }, + "application/vnd.nimn": { + source: "iana" + }, + "application/vnd.nintendo.nitro.rom": { + source: "iana" + }, + "application/vnd.nintendo.snes.rom": { + source: "iana" + }, + "application/vnd.nitf": { + source: "iana", + extensions: ["ntf", "nitf"] + }, + "application/vnd.noblenet-directory": { + source: "iana", + extensions: ["nnd"] + }, + "application/vnd.noblenet-sealer": { + source: "iana", + extensions: ["nns"] + }, + "application/vnd.noblenet-web": { + source: "iana", + extensions: ["nnw"] + }, + "application/vnd.nokia.catalogs": { + source: "iana" + }, + "application/vnd.nokia.conml+wbxml": { + source: "iana" + }, + "application/vnd.nokia.conml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.iptv.config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.isds-radio-presets": { + source: "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + source: "iana" + }, + "application/vnd.nokia.landmark+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.landmarkcollection+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.n-gage.ac+xml": { + source: "iana", + compressible: true, + extensions: ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + source: "iana", + extensions: ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + source: "iana", + extensions: ["n-gage"] + }, + "application/vnd.nokia.ncd": { + source: "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + source: "iana" + }, + "application/vnd.nokia.pcd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.radio-preset": { + source: "iana", + extensions: ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + source: "iana", + extensions: ["rpss"] + }, + "application/vnd.novadigm.edm": { + source: "iana", + extensions: ["edm"] + }, + "application/vnd.novadigm.edx": { + source: "iana", + extensions: ["edx"] + }, + "application/vnd.novadigm.ext": { + source: "iana", + extensions: ["ext"] + }, + "application/vnd.ntt-local.content-share": { + source: "iana" + }, + "application/vnd.ntt-local.file-transfer": { + source: "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + source: "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + source: "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + source: "iana" + }, + "application/vnd.oasis.opendocument.chart": { + source: "iana", + extensions: ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + source: "iana", + extensions: ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + source: "iana", + extensions: ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + source: "iana", + extensions: ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + source: "iana", + extensions: ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + source: "iana", + compressible: false, + extensions: ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + source: "iana", + extensions: ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + source: "iana", + extensions: ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + source: "iana", + extensions: ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + source: "iana", + compressible: false, + extensions: ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + source: "iana", + extensions: ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + source: "iana", + compressible: false, + extensions: ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + source: "iana", + extensions: ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + source: "iana", + compressible: false, + extensions: ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + source: "iana", + extensions: ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + source: "iana", + extensions: ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + source: "iana", + extensions: ["oth"] + }, + "application/vnd.obn": { + source: "iana" + }, + "application/vnd.ocf+cbor": { + source: "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + source: "iana", + compressible: true + }, + "application/vnd.oftn.l10n+json": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.cspg-hexbinary": { + source: "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.dae.xhtml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.pae.gem": { + source: "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.spdlist+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.ueprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.userprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.olpc-sugar": { + source: "iana", + extensions: ["xo"] + }, + "application/vnd.oma-scws-config": { + source: "iana" + }, + "application/vnd.oma-scws-http-request": { + source: "iana" + }, + "application/vnd.oma-scws-http-response": { + source: "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.imd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.ltkm": { + source: "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + source: "iana" + }, + "application/vnd.oma.bcast.sgboot": { + source: "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.sgdu": { + source: "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + source: "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.sprov+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.stkm": { + source: "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-feature-handler+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-pcc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-subs-invite+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-user-prefs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.dcd": { + source: "iana" + }, + "application/vnd.oma.dcdc": { + source: "iana" + }, + "application/vnd.oma.dd2+xml": { + source: "iana", + compressible: true, + extensions: ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.group-usage-list+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.lwm2m+cbor": { + source: "iana" + }, + "application/vnd.oma.lwm2m+json": { + source: "iana", + compressible: true + }, + "application/vnd.oma.lwm2m+tlv": { + source: "iana" + }, + "application/vnd.oma.pal+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.final-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.groups+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.push": { + source: "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.xcap-directory+xml": { + source: "iana", + compressible: true + }, + "application/vnd.omads-email+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omads-file+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omads-folder+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omaloc-supl-init": { + source: "iana" + }, + "application/vnd.onepager": { + source: "iana" + }, + "application/vnd.onepagertamp": { + source: "iana" + }, + "application/vnd.onepagertamx": { + source: "iana" + }, + "application/vnd.onepagertat": { + source: "iana" + }, + "application/vnd.onepagertatp": { + source: "iana" + }, + "application/vnd.onepagertatx": { + source: "iana" + }, + "application/vnd.openblox.game+xml": { + source: "iana", + compressible: true, + extensions: ["obgx"] + }, + "application/vnd.openblox.game-binary": { + source: "iana" + }, + "application/vnd.openeye.oeb": { + source: "iana" + }, + "application/vnd.openofficeorg.extension": { + source: "apache", + extensions: ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + source: "iana", + compressible: true, + extensions: ["osm"] + }, + "application/vnd.opentimestamps.ots": { + source: "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + source: "iana", + compressible: false, + extensions: ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + source: "iana", + extensions: ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + source: "iana", + extensions: ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + source: "iana", + extensions: ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + source: "iana", + compressible: false, + extensions: ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + source: "iana", + extensions: ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + source: "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + source: "iana", + compressible: false, + extensions: ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + source: "iana", + extensions: ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oracle.resource+json": { + source: "iana", + compressible: true + }, + "application/vnd.orange.indata": { + source: "iana" + }, + "application/vnd.osa.netdeploy": { + source: "iana" + }, + "application/vnd.osgeo.mapguide.package": { + source: "iana", + extensions: ["mgp"] + }, + "application/vnd.osgi.bundle": { + source: "iana" + }, + "application/vnd.osgi.dp": { + source: "iana", + extensions: ["dp"] + }, + "application/vnd.osgi.subsystem": { + source: "iana", + extensions: ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oxli.countgraph": { + source: "iana" + }, + "application/vnd.pagerduty+json": { + source: "iana", + compressible: true + }, + "application/vnd.palm": { + source: "iana", + extensions: ["pdb", "pqa", "oprc"] + }, + "application/vnd.panoply": { + source: "iana" + }, + "application/vnd.paos.xml": { + source: "iana" + }, + "application/vnd.patentdive": { + source: "iana" + }, + "application/vnd.patientecommsdoc": { + source: "iana" + }, + "application/vnd.pawaafile": { + source: "iana", + extensions: ["paw"] + }, + "application/vnd.pcos": { + source: "iana" + }, + "application/vnd.pg.format": { + source: "iana", + extensions: ["str"] + }, + "application/vnd.pg.osasli": { + source: "iana", + extensions: ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + source: "iana" + }, + "application/vnd.picsel": { + source: "iana", + extensions: ["efif"] + }, + "application/vnd.pmi.widget": { + source: "iana", + extensions: ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + source: "iana", + compressible: true + }, + "application/vnd.pocketlearn": { + source: "iana", + extensions: ["plf"] + }, + "application/vnd.powerbuilder6": { + source: "iana", + extensions: ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + source: "iana" + }, + "application/vnd.powerbuilder7": { + source: "iana" + }, + "application/vnd.powerbuilder7-s": { + source: "iana" + }, + "application/vnd.powerbuilder75": { + source: "iana" + }, + "application/vnd.powerbuilder75-s": { + source: "iana" + }, + "application/vnd.preminet": { + source: "iana" + }, + "application/vnd.previewsystems.box": { + source: "iana", + extensions: ["box"] + }, + "application/vnd.proteus.magazine": { + source: "iana", + extensions: ["mgz"] + }, + "application/vnd.psfs": { + source: "iana" + }, + "application/vnd.publishare-delta-tree": { + source: "iana", + extensions: ["qps"] + }, + "application/vnd.pvi.ptid1": { + source: "iana", + extensions: ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + source: "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + source: "iana", + compressible: true + }, + "application/vnd.qualcomm.brew-app-res": { + source: "iana" + }, + "application/vnd.quarantainenet": { + source: "iana" + }, + "application/vnd.quark.quarkxpress": { + source: "iana", + extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"] + }, + "application/vnd.quobject-quoxdocument": { + source: "iana" + }, + "application/vnd.radisys.moml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-conf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + source: "iana", + compressible: true + }, + "application/vnd.rainstor.data": { + source: "iana" + }, + "application/vnd.rapid": { + source: "iana" + }, + "application/vnd.rar": { + source: "iana", + extensions: ["rar"] + }, + "application/vnd.realvnc.bed": { + source: "iana", + extensions: ["bed"] + }, + "application/vnd.recordare.musicxml": { + source: "iana", + extensions: ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + source: "iana", + compressible: true, + extensions: ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + source: "iana" + }, + "application/vnd.resilient.logic": { + source: "iana" + }, + "application/vnd.restful+json": { + source: "iana", + compressible: true + }, + "application/vnd.rig.cryptonote": { + source: "iana", + extensions: ["cryptonote"] + }, + "application/vnd.rim.cod": { + source: "apache", + extensions: ["cod"] + }, + "application/vnd.rn-realmedia": { + source: "apache", + extensions: ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + source: "apache", + extensions: ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + source: "iana", + compressible: true, + extensions: ["link66"] + }, + "application/vnd.rs-274x": { + source: "iana" + }, + "application/vnd.ruckus.download": { + source: "iana" + }, + "application/vnd.s3sms": { + source: "iana" + }, + "application/vnd.sailingtracker.track": { + source: "iana", + extensions: ["st"] + }, + "application/vnd.sar": { + source: "iana" + }, + "application/vnd.sbm.cid": { + source: "iana" + }, + "application/vnd.sbm.mid2": { + source: "iana" + }, + "application/vnd.scribus": { + source: "iana" + }, + "application/vnd.sealed.3df": { + source: "iana" + }, + "application/vnd.sealed.csf": { + source: "iana" + }, + "application/vnd.sealed.doc": { + source: "iana" + }, + "application/vnd.sealed.eml": { + source: "iana" + }, + "application/vnd.sealed.mht": { + source: "iana" + }, + "application/vnd.sealed.net": { + source: "iana" + }, + "application/vnd.sealed.ppt": { + source: "iana" + }, + "application/vnd.sealed.tiff": { + source: "iana" + }, + "application/vnd.sealed.xls": { + source: "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + source: "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + source: "iana" + }, + "application/vnd.seemail": { + source: "iana", + extensions: ["see"] + }, + "application/vnd.seis+json": { + source: "iana", + compressible: true + }, + "application/vnd.sema": { + source: "iana", + extensions: ["sema"] + }, + "application/vnd.semd": { + source: "iana", + extensions: ["semd"] + }, + "application/vnd.semf": { + source: "iana", + extensions: ["semf"] + }, + "application/vnd.shade-save-file": { + source: "iana" + }, + "application/vnd.shana.informed.formdata": { + source: "iana", + extensions: ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + source: "iana", + extensions: ["itp"] + }, + "application/vnd.shana.informed.interchange": { + source: "iana", + extensions: ["iif"] + }, + "application/vnd.shana.informed.package": { + source: "iana", + extensions: ["ipk"] + }, + "application/vnd.shootproof+json": { + source: "iana", + compressible: true + }, + "application/vnd.shopkick+json": { + source: "iana", + compressible: true + }, + "application/vnd.shp": { + source: "iana" + }, + "application/vnd.shx": { + source: "iana" + }, + "application/vnd.sigrok.session": { + source: "iana" + }, + "application/vnd.simtech-mindmapper": { + source: "iana", + extensions: ["twd", "twds"] + }, + "application/vnd.siren+json": { + source: "iana", + compressible: true + }, + "application/vnd.smaf": { + source: "iana", + extensions: ["mmf"] + }, + "application/vnd.smart.notebook": { + source: "iana" + }, + "application/vnd.smart.teacher": { + source: "iana", + extensions: ["teacher"] + }, + "application/vnd.snesdev-page-table": { + source: "iana" + }, + "application/vnd.software602.filler.form+xml": { + source: "iana", + compressible: true, + extensions: ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + source: "iana" + }, + "application/vnd.solent.sdkm+xml": { + source: "iana", + compressible: true, + extensions: ["sdkm", "sdkd"] + }, + "application/vnd.spotfire.dxp": { + source: "iana", + extensions: ["dxp"] + }, + "application/vnd.spotfire.sfs": { + source: "iana", + extensions: ["sfs"] + }, + "application/vnd.sqlite3": { + source: "iana" + }, + "application/vnd.sss-cod": { + source: "iana" + }, + "application/vnd.sss-dtf": { + source: "iana" + }, + "application/vnd.sss-ntf": { + source: "iana" + }, + "application/vnd.stardivision.calc": { + source: "apache", + extensions: ["sdc"] + }, + "application/vnd.stardivision.draw": { + source: "apache", + extensions: ["sda"] + }, + "application/vnd.stardivision.impress": { + source: "apache", + extensions: ["sdd"] + }, + "application/vnd.stardivision.math": { + source: "apache", + extensions: ["smf"] + }, + "application/vnd.stardivision.writer": { + source: "apache", + extensions: ["sdw", "vor"] + }, + "application/vnd.stardivision.writer-global": { + source: "apache", + extensions: ["sgl"] + }, + "application/vnd.stepmania.package": { + source: "iana", + extensions: ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + source: "iana", + extensions: ["sm"] + }, + "application/vnd.street-stream": { + source: "iana" + }, + "application/vnd.sun.wadl+xml": { + source: "iana", + compressible: true, + extensions: ["wadl"] + }, + "application/vnd.sun.xml.calc": { + source: "apache", + extensions: ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + source: "apache", + extensions: ["stc"] + }, + "application/vnd.sun.xml.draw": { + source: "apache", + extensions: ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + source: "apache", + extensions: ["std"] + }, + "application/vnd.sun.xml.impress": { + source: "apache", + extensions: ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + source: "apache", + extensions: ["sti"] + }, + "application/vnd.sun.xml.math": { + source: "apache", + extensions: ["sxm"] + }, + "application/vnd.sun.xml.writer": { + source: "apache", + extensions: ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + source: "apache", + extensions: ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + source: "apache", + extensions: ["stw"] + }, + "application/vnd.sus-calendar": { + source: "iana", + extensions: ["sus", "susp"] + }, + "application/vnd.svd": { + source: "iana", + extensions: ["svd"] + }, + "application/vnd.swiftview-ics": { + source: "iana" + }, + "application/vnd.sycle+xml": { + source: "iana", + compressible: true + }, + "application/vnd.syft+json": { + source: "iana", + compressible: true + }, + "application/vnd.symbian.install": { + source: "apache", + extensions: ["sis", "sisx"] + }, + "application/vnd.syncml+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + source: "iana", + charset: "UTF-8", + extensions: ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + source: "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + source: "iana" + }, + "application/vnd.syncml.dmddf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + source: "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.syncml.ds.notification": { + source: "iana" + }, + "application/vnd.tableschema+json": { + source: "iana", + compressible: true + }, + "application/vnd.tao.intent-module-archive": { + source: "iana", + extensions: ["tao"] + }, + "application/vnd.tcpdump.pcap": { + source: "iana", + extensions: ["pcap", "cap", "dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + source: "iana", + compressible: true + }, + "application/vnd.tmd.mediaflex.api+xml": { + source: "iana", + compressible: true + }, + "application/vnd.tml": { + source: "iana" + }, + "application/vnd.tmobile-livetv": { + source: "iana", + extensions: ["tmo"] + }, + "application/vnd.tri.onesource": { + source: "iana" + }, + "application/vnd.trid.tpt": { + source: "iana", + extensions: ["tpt"] + }, + "application/vnd.triscape.mxs": { + source: "iana", + extensions: ["mxs"] + }, + "application/vnd.trueapp": { + source: "iana", + extensions: ["tra"] + }, + "application/vnd.truedoc": { + source: "iana" + }, + "application/vnd.ubisoft.webplayer": { + source: "iana" + }, + "application/vnd.ufdl": { + source: "iana", + extensions: ["ufd", "ufdl"] + }, + "application/vnd.uiq.theme": { + source: "iana", + extensions: ["utz"] + }, + "application/vnd.umajin": { + source: "iana", + extensions: ["umj"] + }, + "application/vnd.unity": { + source: "iana", + extensions: ["unityweb"] + }, + "application/vnd.uoml+xml": { + source: "iana", + compressible: true, + extensions: ["uoml"] + }, + "application/vnd.uplanet.alert": { + source: "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.bearer-choice": { + source: "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.cacheop": { + source: "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.channel": { + source: "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.list": { + source: "iana" + }, + "application/vnd.uplanet.list-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.listcmd": { + source: "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.signal": { + source: "iana" + }, + "application/vnd.uri-map": { + source: "iana" + }, + "application/vnd.valve.source.material": { + source: "iana" + }, + "application/vnd.vcx": { + source: "iana", + extensions: ["vcx"] + }, + "application/vnd.vd-study": { + source: "iana" + }, + "application/vnd.vectorworks": { + source: "iana" + }, + "application/vnd.vel+json": { + source: "iana", + compressible: true + }, + "application/vnd.verimatrix.vcas": { + source: "iana" + }, + "application/vnd.veritone.aion+json": { + source: "iana", + compressible: true + }, + "application/vnd.veryant.thin": { + source: "iana" + }, + "application/vnd.ves.encrypted": { + source: "iana" + }, + "application/vnd.vidsoft.vidconference": { + source: "iana" + }, + "application/vnd.visio": { + source: "iana", + extensions: ["vsd", "vst", "vss", "vsw"] + }, + "application/vnd.visionary": { + source: "iana", + extensions: ["vis"] + }, + "application/vnd.vividence.scriptfile": { + source: "iana" + }, + "application/vnd.vsf": { + source: "iana", + extensions: ["vsf"] + }, + "application/vnd.wap.sic": { + source: "iana" + }, + "application/vnd.wap.slc": { + source: "iana" + }, + "application/vnd.wap.wbxml": { + source: "iana", + charset: "UTF-8", + extensions: ["wbxml"] + }, + "application/vnd.wap.wmlc": { + source: "iana", + extensions: ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + source: "iana", + extensions: ["wmlsc"] + }, + "application/vnd.webturbo": { + source: "iana", + extensions: ["wtb"] + }, + "application/vnd.wfa.dpp": { + source: "iana" + }, + "application/vnd.wfa.p2p": { + source: "iana" + }, + "application/vnd.wfa.wsc": { + source: "iana" + }, + "application/vnd.windows.devicepairing": { + source: "iana" + }, + "application/vnd.wmc": { + source: "iana" + }, + "application/vnd.wmf.bootstrap": { + source: "iana" + }, + "application/vnd.wolfram.mathematica": { + source: "iana" + }, + "application/vnd.wolfram.mathematica.package": { + source: "iana" + }, + "application/vnd.wolfram.player": { + source: "iana", + extensions: ["nbp"] + }, + "application/vnd.wordperfect": { + source: "iana", + extensions: ["wpd"] + }, + "application/vnd.wqd": { + source: "iana", + extensions: ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + source: "iana" + }, + "application/vnd.wt.stf": { + source: "iana", + extensions: ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + source: "iana" + }, + "application/vnd.wv.csp+xml": { + source: "iana", + compressible: true + }, + "application/vnd.wv.ssp+xml": { + source: "iana", + compressible: true + }, + "application/vnd.xacml+json": { + source: "iana", + compressible: true + }, + "application/vnd.xara": { + source: "iana", + extensions: ["xar"] + }, + "application/vnd.xfdl": { + source: "iana", + extensions: ["xfdl"] + }, + "application/vnd.xfdl.webform": { + source: "iana" + }, + "application/vnd.xmi+xml": { + source: "iana", + compressible: true + }, + "application/vnd.xmpie.cpkg": { + source: "iana" + }, + "application/vnd.xmpie.dpkg": { + source: "iana" + }, + "application/vnd.xmpie.plan": { + source: "iana" + }, + "application/vnd.xmpie.ppkg": { + source: "iana" + }, + "application/vnd.xmpie.xlim": { + source: "iana" + }, + "application/vnd.yamaha.hv-dic": { + source: "iana", + extensions: ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + source: "iana", + extensions: ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + source: "iana", + extensions: ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + source: "iana", + extensions: ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + source: "iana", + compressible: true, + extensions: ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + source: "iana" + }, + "application/vnd.yamaha.smaf-audio": { + source: "iana", + extensions: ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + source: "iana", + extensions: ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + source: "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + source: "iana" + }, + "application/vnd.yaoweme": { + source: "iana" + }, + "application/vnd.yellowriver-custom-menu": { + source: "iana", + extensions: ["cmp"] + }, + "application/vnd.youtube.yt": { + source: "iana" + }, + "application/vnd.zul": { + source: "iana", + extensions: ["zir", "zirz"] + }, + "application/vnd.zzazz.deck+xml": { + source: "iana", + compressible: true, + extensions: ["zaz"] + }, + "application/voicexml+xml": { + source: "iana", + compressible: true, + extensions: ["vxml"] + }, + "application/voucher-cms+json": { + source: "iana", + compressible: true + }, + "application/vq-rtcpxr": { + source: "iana" + }, + "application/wasm": { + source: "iana", + compressible: true, + extensions: ["wasm"] + }, + "application/watcherinfo+xml": { + source: "iana", + compressible: true, + extensions: ["wif"] + }, + "application/webpush-options+json": { + source: "iana", + compressible: true + }, + "application/whoispp-query": { + source: "iana" + }, + "application/whoispp-response": { + source: "iana" + }, + "application/widget": { + source: "iana", + extensions: ["wgt"] + }, + "application/winhlp": { + source: "apache", + extensions: ["hlp"] + }, + "application/wita": { + source: "iana" + }, + "application/wordperfect5.1": { + source: "iana" + }, + "application/wsdl+xml": { + source: "iana", + compressible: true, + extensions: ["wsdl"] + }, + "application/wspolicy+xml": { + source: "iana", + compressible: true, + extensions: ["wspolicy"] + }, + "application/x-7z-compressed": { + source: "apache", + compressible: false, + extensions: ["7z"] + }, + "application/x-abiword": { + source: "apache", + extensions: ["abw"] + }, + "application/x-ace-compressed": { + source: "apache", + extensions: ["ace"] + }, + "application/x-amf": { + source: "apache" + }, + "application/x-apple-diskimage": { + source: "apache", + extensions: ["dmg"] + }, + "application/x-arj": { + compressible: false, + extensions: ["arj"] + }, + "application/x-authorware-bin": { + source: "apache", + extensions: ["aab", "x32", "u32", "vox"] + }, + "application/x-authorware-map": { + source: "apache", + extensions: ["aam"] + }, + "application/x-authorware-seg": { + source: "apache", + extensions: ["aas"] + }, + "application/x-bcpio": { + source: "apache", + extensions: ["bcpio"] + }, + "application/x-bdoc": { + compressible: false, + extensions: ["bdoc"] + }, + "application/x-bittorrent": { + source: "apache", + extensions: ["torrent"] + }, + "application/x-blorb": { + source: "apache", + extensions: ["blb", "blorb"] + }, + "application/x-bzip": { + source: "apache", + compressible: false, + extensions: ["bz"] + }, + "application/x-bzip2": { + source: "apache", + compressible: false, + extensions: ["bz2", "boz"] + }, + "application/x-cbr": { + source: "apache", + extensions: ["cbr", "cba", "cbt", "cbz", "cb7"] + }, + "application/x-cdlink": { + source: "apache", + extensions: ["vcd"] + }, + "application/x-cfs-compressed": { + source: "apache", + extensions: ["cfs"] + }, + "application/x-chat": { + source: "apache", + extensions: ["chat"] + }, + "application/x-chess-pgn": { + source: "apache", + extensions: ["pgn"] + }, + "application/x-chrome-extension": { + extensions: ["crx"] + }, + "application/x-cocoa": { + source: "nginx", + extensions: ["cco"] + }, + "application/x-compress": { + source: "apache" + }, + "application/x-conference": { + source: "apache", + extensions: ["nsc"] + }, + "application/x-cpio": { + source: "apache", + extensions: ["cpio"] + }, + "application/x-csh": { + source: "apache", + extensions: ["csh"] + }, + "application/x-deb": { + compressible: false + }, + "application/x-debian-package": { + source: "apache", + extensions: ["deb", "udeb"] + }, + "application/x-dgc-compressed": { + source: "apache", + extensions: ["dgc"] + }, + "application/x-director": { + source: "apache", + extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"] + }, + "application/x-doom": { + source: "apache", + extensions: ["wad"] + }, + "application/x-dtbncx+xml": { + source: "apache", + compressible: true, + extensions: ["ncx"] + }, + "application/x-dtbook+xml": { + source: "apache", + compressible: true, + extensions: ["dtb"] + }, + "application/x-dtbresource+xml": { + source: "apache", + compressible: true, + extensions: ["res"] + }, + "application/x-dvi": { + source: "apache", + compressible: false, + extensions: ["dvi"] + }, + "application/x-envoy": { + source: "apache", + extensions: ["evy"] + }, + "application/x-eva": { + source: "apache", + extensions: ["eva"] + }, + "application/x-font-bdf": { + source: "apache", + extensions: ["bdf"] + }, + "application/x-font-dos": { + source: "apache" + }, + "application/x-font-framemaker": { + source: "apache" + }, + "application/x-font-ghostscript": { + source: "apache", + extensions: ["gsf"] + }, + "application/x-font-libgrx": { + source: "apache" + }, + "application/x-font-linux-psf": { + source: "apache", + extensions: ["psf"] + }, + "application/x-font-pcf": { + source: "apache", + extensions: ["pcf"] + }, + "application/x-font-snf": { + source: "apache", + extensions: ["snf"] + }, + "application/x-font-speedo": { + source: "apache" + }, + "application/x-font-sunos-news": { + source: "apache" + }, + "application/x-font-type1": { + source: "apache", + extensions: ["pfa", "pfb", "pfm", "afm"] + }, + "application/x-font-vfont": { + source: "apache" + }, + "application/x-freearc": { + source: "apache", + extensions: ["arc"] + }, + "application/x-futuresplash": { + source: "apache", + extensions: ["spl"] + }, + "application/x-gca-compressed": { + source: "apache", + extensions: ["gca"] + }, + "application/x-glulx": { + source: "apache", + extensions: ["ulx"] + }, + "application/x-gnumeric": { + source: "apache", + extensions: ["gnumeric"] + }, + "application/x-gramps-xml": { + source: "apache", + extensions: ["gramps"] + }, + "application/x-gtar": { + source: "apache", + extensions: ["gtar"] + }, + "application/x-gzip": { + source: "apache" + }, + "application/x-hdf": { + source: "apache", + extensions: ["hdf"] + }, + "application/x-httpd-php": { + compressible: true, + extensions: ["php"] + }, + "application/x-install-instructions": { + source: "apache", + extensions: ["install"] + }, + "application/x-iso9660-image": { + source: "apache", + extensions: ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + extensions: ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + extensions: ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + extensions: ["pages"] + }, + "application/x-java-archive-diff": { + source: "nginx", + extensions: ["jardiff"] + }, + "application/x-java-jnlp-file": { + source: "apache", + compressible: false, + extensions: ["jnlp"] + }, + "application/x-javascript": { + compressible: true + }, + "application/x-keepass2": { + extensions: ["kdbx"] + }, + "application/x-latex": { + source: "apache", + compressible: false, + extensions: ["latex"] + }, + "application/x-lua-bytecode": { + extensions: ["luac"] + }, + "application/x-lzh-compressed": { + source: "apache", + extensions: ["lzh", "lha"] + }, + "application/x-makeself": { + source: "nginx", + extensions: ["run"] + }, + "application/x-mie": { + source: "apache", + extensions: ["mie"] + }, + "application/x-mobipocket-ebook": { + source: "apache", + extensions: ["prc", "mobi"] + }, + "application/x-mpegurl": { + compressible: false + }, + "application/x-ms-application": { + source: "apache", + extensions: ["application"] + }, + "application/x-ms-shortcut": { + source: "apache", + extensions: ["lnk"] + }, + "application/x-ms-wmd": { + source: "apache", + extensions: ["wmd"] + }, + "application/x-ms-wmz": { + source: "apache", + extensions: ["wmz"] + }, + "application/x-ms-xbap": { + source: "apache", + extensions: ["xbap"] + }, + "application/x-msaccess": { + source: "apache", + extensions: ["mdb"] + }, + "application/x-msbinder": { + source: "apache", + extensions: ["obd"] + }, + "application/x-mscardfile": { + source: "apache", + extensions: ["crd"] + }, + "application/x-msclip": { + source: "apache", + extensions: ["clp"] + }, + "application/x-msdos-program": { + extensions: ["exe"] + }, + "application/x-msdownload": { + source: "apache", + extensions: ["exe", "dll", "com", "bat", "msi"] + }, + "application/x-msmediaview": { + source: "apache", + extensions: ["mvb", "m13", "m14"] + }, + "application/x-msmetafile": { + source: "apache", + extensions: ["wmf", "wmz", "emf", "emz"] + }, + "application/x-msmoney": { + source: "apache", + extensions: ["mny"] + }, + "application/x-mspublisher": { + source: "apache", + extensions: ["pub"] + }, + "application/x-msschedule": { + source: "apache", + extensions: ["scd"] + }, + "application/x-msterminal": { + source: "apache", + extensions: ["trm"] + }, + "application/x-mswrite": { + source: "apache", + extensions: ["wri"] + }, + "application/x-netcdf": { + source: "apache", + extensions: ["nc", "cdf"] + }, + "application/x-ns-proxy-autoconfig": { + compressible: true, + extensions: ["pac"] + }, + "application/x-nzb": { + source: "apache", + extensions: ["nzb"] + }, + "application/x-perl": { + source: "nginx", + extensions: ["pl", "pm"] + }, + "application/x-pilot": { + source: "nginx", + extensions: ["prc", "pdb"] + }, + "application/x-pkcs12": { + source: "apache", + compressible: false, + extensions: ["p12", "pfx"] + }, + "application/x-pkcs7-certificates": { + source: "apache", + extensions: ["p7b", "spc"] + }, + "application/x-pkcs7-certreqresp": { + source: "apache", + extensions: ["p7r"] + }, + "application/x-pki-message": { + source: "iana" + }, + "application/x-rar-compressed": { + source: "apache", + compressible: false, + extensions: ["rar"] + }, + "application/x-redhat-package-manager": { + source: "nginx", + extensions: ["rpm"] + }, + "application/x-research-info-systems": { + source: "apache", + extensions: ["ris"] + }, + "application/x-sea": { + source: "nginx", + extensions: ["sea"] + }, + "application/x-sh": { + source: "apache", + compressible: true, + extensions: ["sh"] + }, + "application/x-shar": { + source: "apache", + extensions: ["shar"] + }, + "application/x-shockwave-flash": { + source: "apache", + compressible: false, + extensions: ["swf"] + }, + "application/x-silverlight-app": { + source: "apache", + extensions: ["xap"] + }, + "application/x-sql": { + source: "apache", + extensions: ["sql"] + }, + "application/x-stuffit": { + source: "apache", + compressible: false, + extensions: ["sit"] + }, + "application/x-stuffitx": { + source: "apache", + extensions: ["sitx"] + }, + "application/x-subrip": { + source: "apache", + extensions: ["srt"] + }, + "application/x-sv4cpio": { + source: "apache", + extensions: ["sv4cpio"] + }, + "application/x-sv4crc": { + source: "apache", + extensions: ["sv4crc"] + }, + "application/x-t3vm-image": { + source: "apache", + extensions: ["t3"] + }, + "application/x-tads": { + source: "apache", + extensions: ["gam"] + }, + "application/x-tar": { + source: "apache", + compressible: true, + extensions: ["tar"] + }, + "application/x-tcl": { + source: "apache", + extensions: ["tcl", "tk"] + }, + "application/x-tex": { + source: "apache", + extensions: ["tex"] + }, + "application/x-tex-tfm": { + source: "apache", + extensions: ["tfm"] + }, + "application/x-texinfo": { + source: "apache", + extensions: ["texinfo", "texi"] + }, + "application/x-tgif": { + source: "apache", + extensions: ["obj"] + }, + "application/x-ustar": { + source: "apache", + extensions: ["ustar"] + }, + "application/x-virtualbox-hdd": { + compressible: true, + extensions: ["hdd"] + }, + "application/x-virtualbox-ova": { + compressible: true, + extensions: ["ova"] + }, + "application/x-virtualbox-ovf": { + compressible: true, + extensions: ["ovf"] + }, + "application/x-virtualbox-vbox": { + compressible: true, + extensions: ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + compressible: false, + extensions: ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + compressible: true, + extensions: ["vdi"] + }, + "application/x-virtualbox-vhd": { + compressible: true, + extensions: ["vhd"] + }, + "application/x-virtualbox-vmdk": { + compressible: true, + extensions: ["vmdk"] + }, + "application/x-wais-source": { + source: "apache", + extensions: ["src"] + }, + "application/x-web-app-manifest+json": { + compressible: true, + extensions: ["webapp"] + }, + "application/x-www-form-urlencoded": { + source: "iana", + compressible: true + }, + "application/x-x509-ca-cert": { + source: "iana", + extensions: ["der", "crt", "pem"] + }, + "application/x-x509-ca-ra-cert": { + source: "iana" + }, + "application/x-x509-next-ca-cert": { + source: "iana" + }, + "application/x-xfig": { + source: "apache", + extensions: ["fig"] + }, + "application/x-xliff+xml": { + source: "apache", + compressible: true, + extensions: ["xlf"] + }, + "application/x-xpinstall": { + source: "apache", + compressible: false, + extensions: ["xpi"] + }, + "application/x-xz": { + source: "apache", + extensions: ["xz"] + }, + "application/x-zmachine": { + source: "apache", + extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"] + }, + "application/x400-bp": { + source: "iana" + }, + "application/xacml+xml": { + source: "iana", + compressible: true + }, + "application/xaml+xml": { + source: "apache", + compressible: true, + extensions: ["xaml"] + }, + "application/xcap-att+xml": { + source: "iana", + compressible: true, + extensions: ["xav"] + }, + "application/xcap-caps+xml": { + source: "iana", + compressible: true, + extensions: ["xca"] + }, + "application/xcap-diff+xml": { + source: "iana", + compressible: true, + extensions: ["xdf"] + }, + "application/xcap-el+xml": { + source: "iana", + compressible: true, + extensions: ["xel"] + }, + "application/xcap-error+xml": { + source: "iana", + compressible: true + }, + "application/xcap-ns+xml": { + source: "iana", + compressible: true, + extensions: ["xns"] + }, + "application/xcon-conference-info+xml": { + source: "iana", + compressible: true + }, + "application/xcon-conference-info-diff+xml": { + source: "iana", + compressible: true + }, + "application/xenc+xml": { + source: "iana", + compressible: true, + extensions: ["xenc"] + }, + "application/xhtml+xml": { + source: "iana", + compressible: true, + extensions: ["xhtml", "xht"] + }, + "application/xhtml-voice+xml": { + source: "apache", + compressible: true + }, + "application/xliff+xml": { + source: "iana", + compressible: true, + extensions: ["xlf"] + }, + "application/xml": { + source: "iana", + compressible: true, + extensions: ["xml", "xsl", "xsd", "rng"] + }, + "application/xml-dtd": { + source: "iana", + compressible: true, + extensions: ["dtd"] + }, + "application/xml-external-parsed-entity": { + source: "iana" + }, + "application/xml-patch+xml": { + source: "iana", + compressible: true + }, + "application/xmpp+xml": { + source: "iana", + compressible: true + }, + "application/xop+xml": { + source: "iana", + compressible: true, + extensions: ["xop"] + }, + "application/xproc+xml": { + source: "apache", + compressible: true, + extensions: ["xpl"] + }, + "application/xslt+xml": { + source: "iana", + compressible: true, + extensions: ["xsl", "xslt"] + }, + "application/xspf+xml": { + source: "apache", + compressible: true, + extensions: ["xspf"] + }, + "application/xv+xml": { + source: "iana", + compressible: true, + extensions: ["mxml", "xhvml", "xvml", "xvm"] + }, + "application/yang": { + source: "iana", + extensions: ["yang"] + }, + "application/yang-data+json": { + source: "iana", + compressible: true + }, + "application/yang-data+xml": { + source: "iana", + compressible: true + }, + "application/yang-patch+json": { + source: "iana", + compressible: true + }, + "application/yang-patch+xml": { + source: "iana", + compressible: true + }, + "application/yin+xml": { + source: "iana", + compressible: true, + extensions: ["yin"] + }, + "application/zip": { + source: "iana", + compressible: false, + extensions: ["zip"] + }, + "application/zlib": { + source: "iana" + }, + "application/zstd": { + source: "iana" + }, + "audio/1d-interleaved-parityfec": { + source: "iana" + }, + "audio/32kadpcm": { + source: "iana" + }, + "audio/3gpp": { + source: "iana", + compressible: false, + extensions: ["3gpp"] + }, + "audio/3gpp2": { + source: "iana" + }, + "audio/aac": { + source: "iana" + }, + "audio/ac3": { + source: "iana" + }, + "audio/adpcm": { + source: "apache", + extensions: ["adp"] + }, + "audio/amr": { + source: "iana", + extensions: ["amr"] + }, + "audio/amr-wb": { + source: "iana" + }, + "audio/amr-wb+": { + source: "iana" + }, + "audio/aptx": { + source: "iana" + }, + "audio/asc": { + source: "iana" + }, + "audio/atrac-advanced-lossless": { + source: "iana" + }, + "audio/atrac-x": { + source: "iana" + }, + "audio/atrac3": { + source: "iana" + }, + "audio/basic": { + source: "iana", + compressible: false, + extensions: ["au", "snd"] + }, + "audio/bv16": { + source: "iana" + }, + "audio/bv32": { + source: "iana" + }, + "audio/clearmode": { + source: "iana" + }, + "audio/cn": { + source: "iana" + }, + "audio/dat12": { + source: "iana" + }, + "audio/dls": { + source: "iana" + }, + "audio/dsr-es201108": { + source: "iana" + }, + "audio/dsr-es202050": { + source: "iana" + }, + "audio/dsr-es202211": { + source: "iana" + }, + "audio/dsr-es202212": { + source: "iana" + }, + "audio/dv": { + source: "iana" + }, + "audio/dvi4": { + source: "iana" + }, + "audio/eac3": { + source: "iana" + }, + "audio/encaprtp": { + source: "iana" + }, + "audio/evrc": { + source: "iana" + }, + "audio/evrc-qcp": { + source: "iana" + }, + "audio/evrc0": { + source: "iana" + }, + "audio/evrc1": { + source: "iana" + }, + "audio/evrcb": { + source: "iana" + }, + "audio/evrcb0": { + source: "iana" + }, + "audio/evrcb1": { + source: "iana" + }, + "audio/evrcnw": { + source: "iana" + }, + "audio/evrcnw0": { + source: "iana" + }, + "audio/evrcnw1": { + source: "iana" + }, + "audio/evrcwb": { + source: "iana" + }, + "audio/evrcwb0": { + source: "iana" + }, + "audio/evrcwb1": { + source: "iana" + }, + "audio/evs": { + source: "iana" + }, + "audio/flexfec": { + source: "iana" + }, + "audio/fwdred": { + source: "iana" + }, + "audio/g711-0": { + source: "iana" + }, + "audio/g719": { + source: "iana" + }, + "audio/g722": { + source: "iana" + }, + "audio/g7221": { + source: "iana" + }, + "audio/g723": { + source: "iana" + }, + "audio/g726-16": { + source: "iana" + }, + "audio/g726-24": { + source: "iana" + }, + "audio/g726-32": { + source: "iana" + }, + "audio/g726-40": { + source: "iana" + }, + "audio/g728": { + source: "iana" + }, + "audio/g729": { + source: "iana" + }, + "audio/g7291": { + source: "iana" + }, + "audio/g729d": { + source: "iana" + }, + "audio/g729e": { + source: "iana" + }, + "audio/gsm": { + source: "iana" + }, + "audio/gsm-efr": { + source: "iana" + }, + "audio/gsm-hr-08": { + source: "iana" + }, + "audio/ilbc": { + source: "iana" + }, + "audio/ip-mr_v2.5": { + source: "iana" + }, + "audio/isac": { + source: "apache" + }, + "audio/l16": { + source: "iana" + }, + "audio/l20": { + source: "iana" + }, + "audio/l24": { + source: "iana", + compressible: false + }, + "audio/l8": { + source: "iana" + }, + "audio/lpc": { + source: "iana" + }, + "audio/melp": { + source: "iana" + }, + "audio/melp1200": { + source: "iana" + }, + "audio/melp2400": { + source: "iana" + }, + "audio/melp600": { + source: "iana" + }, + "audio/mhas": { + source: "iana" + }, + "audio/midi": { + source: "apache", + extensions: ["mid", "midi", "kar", "rmi"] + }, + "audio/mobile-xmf": { + source: "iana", + extensions: ["mxmf"] + }, + "audio/mp3": { + compressible: false, + extensions: ["mp3"] + }, + "audio/mp4": { + source: "iana", + compressible: false, + extensions: ["m4a", "mp4a"] + }, + "audio/mp4a-latm": { + source: "iana" + }, + "audio/mpa": { + source: "iana" + }, + "audio/mpa-robust": { + source: "iana" + }, + "audio/mpeg": { + source: "iana", + compressible: false, + extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"] + }, + "audio/mpeg4-generic": { + source: "iana" + }, + "audio/musepack": { + source: "apache" + }, + "audio/ogg": { + source: "iana", + compressible: false, + extensions: ["oga", "ogg", "spx", "opus"] + }, + "audio/opus": { + source: "iana" + }, + "audio/parityfec": { + source: "iana" + }, + "audio/pcma": { + source: "iana" + }, + "audio/pcma-wb": { + source: "iana" + }, + "audio/pcmu": { + source: "iana" + }, + "audio/pcmu-wb": { + source: "iana" + }, + "audio/prs.sid": { + source: "iana" + }, + "audio/qcelp": { + source: "iana" + }, + "audio/raptorfec": { + source: "iana" + }, + "audio/red": { + source: "iana" + }, + "audio/rtp-enc-aescm128": { + source: "iana" + }, + "audio/rtp-midi": { + source: "iana" + }, + "audio/rtploopback": { + source: "iana" + }, + "audio/rtx": { + source: "iana" + }, + "audio/s3m": { + source: "apache", + extensions: ["s3m"] + }, + "audio/scip": { + source: "iana" + }, + "audio/silk": { + source: "apache", + extensions: ["sil"] + }, + "audio/smv": { + source: "iana" + }, + "audio/smv-qcp": { + source: "iana" + }, + "audio/smv0": { + source: "iana" + }, + "audio/sofa": { + source: "iana" + }, + "audio/sp-midi": { + source: "iana" + }, + "audio/speex": { + source: "iana" + }, + "audio/t140c": { + source: "iana" + }, + "audio/t38": { + source: "iana" + }, + "audio/telephone-event": { + source: "iana" + }, + "audio/tetra_acelp": { + source: "iana" + }, + "audio/tetra_acelp_bb": { + source: "iana" + }, + "audio/tone": { + source: "iana" + }, + "audio/tsvcis": { + source: "iana" + }, + "audio/uemclip": { + source: "iana" + }, + "audio/ulpfec": { + source: "iana" + }, + "audio/usac": { + source: "iana" + }, + "audio/vdvi": { + source: "iana" + }, + "audio/vmr-wb": { + source: "iana" + }, + "audio/vnd.3gpp.iufp": { + source: "iana" + }, + "audio/vnd.4sb": { + source: "iana" + }, + "audio/vnd.audiokoz": { + source: "iana" + }, + "audio/vnd.celp": { + source: "iana" + }, + "audio/vnd.cisco.nse": { + source: "iana" + }, + "audio/vnd.cmles.radio-events": { + source: "iana" + }, + "audio/vnd.cns.anp1": { + source: "iana" + }, + "audio/vnd.cns.inf1": { + source: "iana" + }, + "audio/vnd.dece.audio": { + source: "iana", + extensions: ["uva", "uvva"] + }, + "audio/vnd.digital-winds": { + source: "iana", + extensions: ["eol"] + }, + "audio/vnd.dlna.adts": { + source: "iana" + }, + "audio/vnd.dolby.heaac.1": { + source: "iana" + }, + "audio/vnd.dolby.heaac.2": { + source: "iana" + }, + "audio/vnd.dolby.mlp": { + source: "iana" + }, + "audio/vnd.dolby.mps": { + source: "iana" + }, + "audio/vnd.dolby.pl2": { + source: "iana" + }, + "audio/vnd.dolby.pl2x": { + source: "iana" + }, + "audio/vnd.dolby.pl2z": { + source: "iana" + }, + "audio/vnd.dolby.pulse.1": { + source: "iana" + }, + "audio/vnd.dra": { + source: "iana", + extensions: ["dra"] + }, + "audio/vnd.dts": { + source: "iana", + extensions: ["dts"] + }, + "audio/vnd.dts.hd": { + source: "iana", + extensions: ["dtshd"] + }, + "audio/vnd.dts.uhd": { + source: "iana" + }, + "audio/vnd.dvb.file": { + source: "iana" + }, + "audio/vnd.everad.plj": { + source: "iana" + }, + "audio/vnd.hns.audio": { + source: "iana" + }, + "audio/vnd.lucent.voice": { + source: "iana", + extensions: ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + source: "iana", + extensions: ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + source: "iana" + }, + "audio/vnd.nortel.vbk": { + source: "iana" + }, + "audio/vnd.nuera.ecelp4800": { + source: "iana", + extensions: ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + source: "iana", + extensions: ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + source: "iana", + extensions: ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + source: "iana" + }, + "audio/vnd.presonus.multitrack": { + source: "iana" + }, + "audio/vnd.qcelp": { + source: "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + source: "iana" + }, + "audio/vnd.rip": { + source: "iana", + extensions: ["rip"] + }, + "audio/vnd.rn-realaudio": { + compressible: false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + source: "iana" + }, + "audio/vnd.vmx.cvsd": { + source: "iana" + }, + "audio/vnd.wave": { + compressible: false + }, + "audio/vorbis": { + source: "iana", + compressible: false + }, + "audio/vorbis-config": { + source: "iana" + }, + "audio/wav": { + compressible: false, + extensions: ["wav"] + }, + "audio/wave": { + compressible: false, + extensions: ["wav"] + }, + "audio/webm": { + source: "apache", + compressible: false, + extensions: ["weba"] + }, + "audio/x-aac": { + source: "apache", + compressible: false, + extensions: ["aac"] + }, + "audio/x-aiff": { + source: "apache", + extensions: ["aif", "aiff", "aifc"] + }, + "audio/x-caf": { + source: "apache", + compressible: false, + extensions: ["caf"] + }, + "audio/x-flac": { + source: "apache", + extensions: ["flac"] + }, + "audio/x-m4a": { + source: "nginx", + extensions: ["m4a"] + }, + "audio/x-matroska": { + source: "apache", + extensions: ["mka"] + }, + "audio/x-mpegurl": { + source: "apache", + extensions: ["m3u"] + }, + "audio/x-ms-wax": { + source: "apache", + extensions: ["wax"] + }, + "audio/x-ms-wma": { + source: "apache", + extensions: ["wma"] + }, + "audio/x-pn-realaudio": { + source: "apache", + extensions: ["ram", "ra"] + }, + "audio/x-pn-realaudio-plugin": { + source: "apache", + extensions: ["rmp"] + }, + "audio/x-realaudio": { + source: "nginx", + extensions: ["ra"] + }, + "audio/x-tta": { + source: "apache" + }, + "audio/x-wav": { + source: "apache", + extensions: ["wav"] + }, + "audio/xm": { + source: "apache", + extensions: ["xm"] + }, + "chemical/x-cdx": { + source: "apache", + extensions: ["cdx"] + }, + "chemical/x-cif": { + source: "apache", + extensions: ["cif"] + }, + "chemical/x-cmdf": { + source: "apache", + extensions: ["cmdf"] + }, + "chemical/x-cml": { + source: "apache", + extensions: ["cml"] + }, + "chemical/x-csml": { + source: "apache", + extensions: ["csml"] + }, + "chemical/x-pdb": { + source: "apache" + }, + "chemical/x-xyz": { + source: "apache", + extensions: ["xyz"] + }, + "font/collection": { + source: "iana", + extensions: ["ttc"] + }, + "font/otf": { + source: "iana", + compressible: true, + extensions: ["otf"] + }, + "font/sfnt": { + source: "iana" + }, + "font/ttf": { + source: "iana", + compressible: true, + extensions: ["ttf"] + }, + "font/woff": { + source: "iana", + extensions: ["woff"] + }, + "font/woff2": { + source: "iana", + extensions: ["woff2"] + }, + "image/aces": { + source: "iana", + extensions: ["exr"] + }, + "image/apng": { + compressible: false, + extensions: ["apng"] + }, + "image/avci": { + source: "iana", + extensions: ["avci"] + }, + "image/avcs": { + source: "iana", + extensions: ["avcs"] + }, + "image/avif": { + source: "iana", + compressible: false, + extensions: ["avif"] + }, + "image/bmp": { + source: "iana", + compressible: true, + extensions: ["bmp"] + }, + "image/cgm": { + source: "iana", + extensions: ["cgm"] + }, + "image/dicom-rle": { + source: "iana", + extensions: ["drle"] + }, + "image/emf": { + source: "iana", + extensions: ["emf"] + }, + "image/fits": { + source: "iana", + extensions: ["fits"] + }, + "image/g3fax": { + source: "iana", + extensions: ["g3"] + }, + "image/gif": { + source: "iana", + compressible: false, + extensions: ["gif"] + }, + "image/heic": { + source: "iana", + extensions: ["heic"] + }, + "image/heic-sequence": { + source: "iana", + extensions: ["heics"] + }, + "image/heif": { + source: "iana", + extensions: ["heif"] + }, + "image/heif-sequence": { + source: "iana", + extensions: ["heifs"] + }, + "image/hej2k": { + source: "iana", + extensions: ["hej2"] + }, + "image/hsj2": { + source: "iana", + extensions: ["hsj2"] + }, + "image/ief": { + source: "iana", + extensions: ["ief"] + }, + "image/jls": { + source: "iana", + extensions: ["jls"] + }, + "image/jp2": { + source: "iana", + compressible: false, + extensions: ["jp2", "jpg2"] + }, + "image/jpeg": { + source: "iana", + compressible: false, + extensions: ["jpeg", "jpg", "jpe"] + }, + "image/jph": { + source: "iana", + extensions: ["jph"] + }, + "image/jphc": { + source: "iana", + extensions: ["jhc"] + }, + "image/jpm": { + source: "iana", + compressible: false, + extensions: ["jpm"] + }, + "image/jpx": { + source: "iana", + compressible: false, + extensions: ["jpx", "jpf"] + }, + "image/jxr": { + source: "iana", + extensions: ["jxr"] + }, + "image/jxra": { + source: "iana", + extensions: ["jxra"] + }, + "image/jxrs": { + source: "iana", + extensions: ["jxrs"] + }, + "image/jxs": { + source: "iana", + extensions: ["jxs"] + }, + "image/jxsc": { + source: "iana", + extensions: ["jxsc"] + }, + "image/jxsi": { + source: "iana", + extensions: ["jxsi"] + }, + "image/jxss": { + source: "iana", + extensions: ["jxss"] + }, + "image/ktx": { + source: "iana", + extensions: ["ktx"] + }, + "image/ktx2": { + source: "iana", + extensions: ["ktx2"] + }, + "image/naplps": { + source: "iana" + }, + "image/pjpeg": { + compressible: false + }, + "image/png": { + source: "iana", + compressible: false, + extensions: ["png"] + }, + "image/prs.btif": { + source: "iana", + extensions: ["btif"] + }, + "image/prs.pti": { + source: "iana", + extensions: ["pti"] + }, + "image/pwg-raster": { + source: "iana" + }, + "image/sgi": { + source: "apache", + extensions: ["sgi"] + }, + "image/svg+xml": { + source: "iana", + compressible: true, + extensions: ["svg", "svgz"] + }, + "image/t38": { + source: "iana", + extensions: ["t38"] + }, + "image/tiff": { + source: "iana", + compressible: false, + extensions: ["tif", "tiff"] + }, + "image/tiff-fx": { + source: "iana", + extensions: ["tfx"] + }, + "image/vnd.adobe.photoshop": { + source: "iana", + compressible: true, + extensions: ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + source: "iana", + extensions: ["azv"] + }, + "image/vnd.cns.inf2": { + source: "iana" + }, + "image/vnd.dece.graphic": { + source: "iana", + extensions: ["uvi", "uvvi", "uvg", "uvvg"] + }, + "image/vnd.djvu": { + source: "iana", + extensions: ["djvu", "djv"] + }, + "image/vnd.dvb.subtitle": { + source: "iana", + extensions: ["sub"] + }, + "image/vnd.dwg": { + source: "iana", + extensions: ["dwg"] + }, + "image/vnd.dxf": { + source: "iana", + extensions: ["dxf"] + }, + "image/vnd.fastbidsheet": { + source: "iana", + extensions: ["fbs"] + }, + "image/vnd.fpx": { + source: "iana", + extensions: ["fpx"] + }, + "image/vnd.fst": { + source: "iana", + extensions: ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + source: "iana", + extensions: ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + source: "iana", + extensions: ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + source: "iana" + }, + "image/vnd.microsoft.icon": { + source: "iana", + compressible: true, + extensions: ["ico"] + }, + "image/vnd.mix": { + source: "iana" + }, + "image/vnd.mozilla.apng": { + source: "iana" + }, + "image/vnd.ms-dds": { + compressible: true, + extensions: ["dds"] + }, + "image/vnd.ms-modi": { + source: "iana", + extensions: ["mdi"] + }, + "image/vnd.ms-photo": { + source: "apache", + extensions: ["wdp"] + }, + "image/vnd.net-fpx": { + source: "iana", + extensions: ["npx"] + }, + "image/vnd.pco.b16": { + source: "iana", + extensions: ["b16"] + }, + "image/vnd.radiance": { + source: "iana" + }, + "image/vnd.sealed.png": { + source: "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + source: "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + source: "iana" + }, + "image/vnd.svf": { + source: "iana" + }, + "image/vnd.tencent.tap": { + source: "iana", + extensions: ["tap"] + }, + "image/vnd.valve.source.texture": { + source: "iana", + extensions: ["vtf"] + }, + "image/vnd.wap.wbmp": { + source: "iana", + extensions: ["wbmp"] + }, + "image/vnd.xiff": { + source: "iana", + extensions: ["xif"] + }, + "image/vnd.zbrush.pcx": { + source: "iana", + extensions: ["pcx"] + }, + "image/webp": { + source: "apache", + extensions: ["webp"] + }, + "image/wmf": { + source: "iana", + extensions: ["wmf"] + }, + "image/x-3ds": { + source: "apache", + extensions: ["3ds"] + }, + "image/x-cmu-raster": { + source: "apache", + extensions: ["ras"] + }, + "image/x-cmx": { + source: "apache", + extensions: ["cmx"] + }, + "image/x-freehand": { + source: "apache", + extensions: ["fh", "fhc", "fh4", "fh5", "fh7"] + }, + "image/x-icon": { + source: "apache", + compressible: true, + extensions: ["ico"] + }, + "image/x-jng": { + source: "nginx", + extensions: ["jng"] + }, + "image/x-mrsid-image": { + source: "apache", + extensions: ["sid"] + }, + "image/x-ms-bmp": { + source: "nginx", + compressible: true, + extensions: ["bmp"] + }, + "image/x-pcx": { + source: "apache", + extensions: ["pcx"] + }, + "image/x-pict": { + source: "apache", + extensions: ["pic", "pct"] + }, + "image/x-portable-anymap": { + source: "apache", + extensions: ["pnm"] + }, + "image/x-portable-bitmap": { + source: "apache", + extensions: ["pbm"] + }, + "image/x-portable-graymap": { + source: "apache", + extensions: ["pgm"] + }, + "image/x-portable-pixmap": { + source: "apache", + extensions: ["ppm"] + }, + "image/x-rgb": { + source: "apache", + extensions: ["rgb"] + }, + "image/x-tga": { + source: "apache", + extensions: ["tga"] + }, + "image/x-xbitmap": { + source: "apache", + extensions: ["xbm"] + }, + "image/x-xcf": { + compressible: false + }, + "image/x-xpixmap": { + source: "apache", + extensions: ["xpm"] + }, + "image/x-xwindowdump": { + source: "apache", + extensions: ["xwd"] + }, + "message/cpim": { + source: "iana" + }, + "message/delivery-status": { + source: "iana" + }, + "message/disposition-notification": { + source: "iana", + extensions: [ + "disposition-notification" + ] + }, + "message/external-body": { + source: "iana" + }, + "message/feedback-report": { + source: "iana" + }, + "message/global": { + source: "iana", + extensions: ["u8msg"] + }, + "message/global-delivery-status": { + source: "iana", + extensions: ["u8dsn"] + }, + "message/global-disposition-notification": { + source: "iana", + extensions: ["u8mdn"] + }, + "message/global-headers": { + source: "iana", + extensions: ["u8hdr"] + }, + "message/http": { + source: "iana", + compressible: false + }, + "message/imdn+xml": { + source: "iana", + compressible: true + }, + "message/news": { + source: "iana" + }, + "message/partial": { + source: "iana", + compressible: false + }, + "message/rfc822": { + source: "iana", + compressible: true, + extensions: ["eml", "mime"] + }, + "message/s-http": { + source: "iana" + }, + "message/sip": { + source: "iana" + }, + "message/sipfrag": { + source: "iana" + }, + "message/tracking-status": { + source: "iana" + }, + "message/vnd.si.simp": { + source: "iana" + }, + "message/vnd.wfa.wsc": { + source: "iana", + extensions: ["wsc"] + }, + "model/3mf": { + source: "iana", + extensions: ["3mf"] + }, + "model/e57": { + source: "iana" + }, + "model/gltf+json": { + source: "iana", + compressible: true, + extensions: ["gltf"] + }, + "model/gltf-binary": { + source: "iana", + compressible: true, + extensions: ["glb"] + }, + "model/iges": { + source: "iana", + compressible: false, + extensions: ["igs", "iges"] + }, + "model/mesh": { + source: "iana", + compressible: false, + extensions: ["msh", "mesh", "silo"] + }, + "model/mtl": { + source: "iana", + extensions: ["mtl"] + }, + "model/obj": { + source: "iana", + extensions: ["obj"] + }, + "model/step": { + source: "iana" + }, + "model/step+xml": { + source: "iana", + compressible: true, + extensions: ["stpx"] + }, + "model/step+zip": { + source: "iana", + compressible: false, + extensions: ["stpz"] + }, + "model/step-xml+zip": { + source: "iana", + compressible: false, + extensions: ["stpxz"] + }, + "model/stl": { + source: "iana", + extensions: ["stl"] + }, + "model/vnd.collada+xml": { + source: "iana", + compressible: true, + extensions: ["dae"] + }, + "model/vnd.dwf": { + source: "iana", + extensions: ["dwf"] + }, + "model/vnd.flatland.3dml": { + source: "iana" + }, + "model/vnd.gdl": { + source: "iana", + extensions: ["gdl"] + }, + "model/vnd.gs-gdl": { + source: "apache" + }, + "model/vnd.gs.gdl": { + source: "iana" + }, + "model/vnd.gtw": { + source: "iana", + extensions: ["gtw"] + }, + "model/vnd.moml+xml": { + source: "iana", + compressible: true + }, + "model/vnd.mts": { + source: "iana", + extensions: ["mts"] + }, + "model/vnd.opengex": { + source: "iana", + extensions: ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + source: "iana", + extensions: ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + source: "iana", + extensions: ["x_t"] + }, + "model/vnd.pytha.pyox": { + source: "iana" + }, + "model/vnd.rosette.annotated-data-model": { + source: "iana" + }, + "model/vnd.sap.vds": { + source: "iana", + extensions: ["vds"] + }, + "model/vnd.usdz+zip": { + source: "iana", + compressible: false, + extensions: ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + source: "iana", + extensions: ["bsp"] + }, + "model/vnd.vtu": { + source: "iana", + extensions: ["vtu"] + }, + "model/vrml": { + source: "iana", + compressible: false, + extensions: ["wrl", "vrml"] + }, + "model/x3d+binary": { + source: "apache", + compressible: false, + extensions: ["x3db", "x3dbz"] + }, + "model/x3d+fastinfoset": { + source: "iana", + extensions: ["x3db"] + }, + "model/x3d+vrml": { + source: "apache", + compressible: false, + extensions: ["x3dv", "x3dvz"] + }, + "model/x3d+xml": { + source: "iana", + compressible: true, + extensions: ["x3d", "x3dz"] + }, + "model/x3d-vrml": { + source: "iana", + extensions: ["x3dv"] + }, + "multipart/alternative": { + source: "iana", + compressible: false + }, + "multipart/appledouble": { + source: "iana" + }, + "multipart/byteranges": { + source: "iana" + }, + "multipart/digest": { + source: "iana" + }, + "multipart/encrypted": { + source: "iana", + compressible: false + }, + "multipart/form-data": { + source: "iana", + compressible: false + }, + "multipart/header-set": { + source: "iana" + }, + "multipart/mixed": { + source: "iana" + }, + "multipart/multilingual": { + source: "iana" + }, + "multipart/parallel": { + source: "iana" + }, + "multipart/related": { + source: "iana", + compressible: false + }, + "multipart/report": { + source: "iana" + }, + "multipart/signed": { + source: "iana", + compressible: false + }, + "multipart/vnd.bint.med-plus": { + source: "iana" + }, + "multipart/voice-message": { + source: "iana" + }, + "multipart/x-mixed-replace": { + source: "iana" + }, + "text/1d-interleaved-parityfec": { + source: "iana" + }, + "text/cache-manifest": { + source: "iana", + compressible: true, + extensions: ["appcache", "manifest"] + }, + "text/calendar": { + source: "iana", + extensions: ["ics", "ifb"] + }, + "text/calender": { + compressible: true + }, + "text/cmd": { + compressible: true + }, + "text/coffeescript": { + extensions: ["coffee", "litcoffee"] + }, + "text/cql": { + source: "iana" + }, + "text/cql-expression": { + source: "iana" + }, + "text/cql-identifier": { + source: "iana" + }, + "text/css": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["css"] + }, + "text/csv": { + source: "iana", + compressible: true, + extensions: ["csv"] + }, + "text/csv-schema": { + source: "iana" + }, + "text/directory": { + source: "iana" + }, + "text/dns": { + source: "iana" + }, + "text/ecmascript": { + source: "iana" + }, + "text/encaprtp": { + source: "iana" + }, + "text/enriched": { + source: "iana" + }, + "text/fhirpath": { + source: "iana" + }, + "text/flexfec": { + source: "iana" + }, + "text/fwdred": { + source: "iana" + }, + "text/gff3": { + source: "iana" + }, + "text/grammar-ref-list": { + source: "iana" + }, + "text/html": { + source: "iana", + compressible: true, + extensions: ["html", "htm", "shtml"] + }, + "text/jade": { + extensions: ["jade"] + }, + "text/javascript": { + source: "iana", + compressible: true + }, + "text/jcr-cnd": { + source: "iana" + }, + "text/jsx": { + compressible: true, + extensions: ["jsx"] + }, + "text/less": { + compressible: true, + extensions: ["less"] + }, + "text/markdown": { + source: "iana", + compressible: true, + extensions: ["markdown", "md"] + }, + "text/mathml": { + source: "nginx", + extensions: ["mml"] + }, + "text/mdx": { + compressible: true, + extensions: ["mdx"] + }, + "text/mizar": { + source: "iana" + }, + "text/n3": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["n3"] + }, + "text/parameters": { + source: "iana", + charset: "UTF-8" + }, + "text/parityfec": { + source: "iana" + }, + "text/plain": { + source: "iana", + compressible: true, + extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"] + }, + "text/provenance-notation": { + source: "iana", + charset: "UTF-8" + }, + "text/prs.fallenstein.rst": { + source: "iana" + }, + "text/prs.lines.tag": { + source: "iana", + extensions: ["dsc"] + }, + "text/prs.prop.logic": { + source: "iana" + }, + "text/raptorfec": { + source: "iana" + }, + "text/red": { + source: "iana" + }, + "text/rfc822-headers": { + source: "iana" + }, + "text/richtext": { + source: "iana", + compressible: true, + extensions: ["rtx"] + }, + "text/rtf": { + source: "iana", + compressible: true, + extensions: ["rtf"] + }, + "text/rtp-enc-aescm128": { + source: "iana" + }, + "text/rtploopback": { + source: "iana" + }, + "text/rtx": { + source: "iana" + }, + "text/sgml": { + source: "iana", + extensions: ["sgml", "sgm"] + }, + "text/shaclc": { + source: "iana" + }, + "text/shex": { + source: "iana", + extensions: ["shex"] + }, + "text/slim": { + extensions: ["slim", "slm"] + }, + "text/spdx": { + source: "iana", + extensions: ["spdx"] + }, + "text/strings": { + source: "iana" + }, + "text/stylus": { + extensions: ["stylus", "styl"] + }, + "text/t140": { + source: "iana" + }, + "text/tab-separated-values": { + source: "iana", + compressible: true, + extensions: ["tsv"] + }, + "text/troff": { + source: "iana", + extensions: ["t", "tr", "roff", "man", "me", "ms"] + }, + "text/turtle": { + source: "iana", + charset: "UTF-8", + extensions: ["ttl"] + }, + "text/ulpfec": { + source: "iana" + }, + "text/uri-list": { + source: "iana", + compressible: true, + extensions: ["uri", "uris", "urls"] + }, + "text/vcard": { + source: "iana", + compressible: true, + extensions: ["vcard"] + }, + "text/vnd.a": { + source: "iana" + }, + "text/vnd.abc": { + source: "iana" + }, + "text/vnd.ascii-art": { + source: "iana" + }, + "text/vnd.curl": { + source: "iana", + extensions: ["curl"] + }, + "text/vnd.curl.dcurl": { + source: "apache", + extensions: ["dcurl"] + }, + "text/vnd.curl.mcurl": { + source: "apache", + extensions: ["mcurl"] + }, + "text/vnd.curl.scurl": { + source: "apache", + extensions: ["scurl"] + }, + "text/vnd.debian.copyright": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.dmclientscript": { + source: "iana" + }, + "text/vnd.dvb.subtitle": { + source: "iana", + extensions: ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.familysearch.gedcom": { + source: "iana", + extensions: ["ged"] + }, + "text/vnd.ficlab.flt": { + source: "iana" + }, + "text/vnd.fly": { + source: "iana", + extensions: ["fly"] + }, + "text/vnd.fmi.flexstor": { + source: "iana", + extensions: ["flx"] + }, + "text/vnd.gml": { + source: "iana" + }, + "text/vnd.graphviz": { + source: "iana", + extensions: ["gv"] + }, + "text/vnd.hans": { + source: "iana" + }, + "text/vnd.hgl": { + source: "iana" + }, + "text/vnd.in3d.3dml": { + source: "iana", + extensions: ["3dml"] + }, + "text/vnd.in3d.spot": { + source: "iana", + extensions: ["spot"] + }, + "text/vnd.iptc.newsml": { + source: "iana" + }, + "text/vnd.iptc.nitf": { + source: "iana" + }, + "text/vnd.latex-z": { + source: "iana" + }, + "text/vnd.motorola.reflex": { + source: "iana" + }, + "text/vnd.ms-mediapackage": { + source: "iana" + }, + "text/vnd.net2phone.commcenter.command": { + source: "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + source: "iana" + }, + "text/vnd.senx.warpscript": { + source: "iana" + }, + "text/vnd.si.uricatalogue": { + source: "iana" + }, + "text/vnd.sosi": { + source: "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + source: "iana", + charset: "UTF-8", + extensions: ["jad"] + }, + "text/vnd.trolltech.linguist": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.wap.si": { + source: "iana" + }, + "text/vnd.wap.sl": { + source: "iana" + }, + "text/vnd.wap.wml": { + source: "iana", + extensions: ["wml"] + }, + "text/vnd.wap.wmlscript": { + source: "iana", + extensions: ["wmls"] + }, + "text/vtt": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["vtt"] + }, + "text/x-asm": { + source: "apache", + extensions: ["s", "asm"] + }, + "text/x-c": { + source: "apache", + extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"] + }, + "text/x-component": { + source: "nginx", + extensions: ["htc"] + }, + "text/x-fortran": { + source: "apache", + extensions: ["f", "for", "f77", "f90"] + }, + "text/x-gwt-rpc": { + compressible: true + }, + "text/x-handlebars-template": { + extensions: ["hbs"] + }, + "text/x-java-source": { + source: "apache", + extensions: ["java"] + }, + "text/x-jquery-tmpl": { + compressible: true + }, + "text/x-lua": { + extensions: ["lua"] + }, + "text/x-markdown": { + compressible: true, + extensions: ["mkd"] + }, + "text/x-nfo": { + source: "apache", + extensions: ["nfo"] + }, + "text/x-opml": { + source: "apache", + extensions: ["opml"] + }, + "text/x-org": { + compressible: true, + extensions: ["org"] + }, + "text/x-pascal": { + source: "apache", + extensions: ["p", "pas"] + }, + "text/x-processing": { + compressible: true, + extensions: ["pde"] + }, + "text/x-sass": { + extensions: ["sass"] + }, + "text/x-scss": { + extensions: ["scss"] + }, + "text/x-setext": { + source: "apache", + extensions: ["etx"] + }, + "text/x-sfv": { + source: "apache", + extensions: ["sfv"] + }, + "text/x-suse-ymp": { + compressible: true, + extensions: ["ymp"] + }, + "text/x-uuencode": { + source: "apache", + extensions: ["uu"] + }, + "text/x-vcalendar": { + source: "apache", + extensions: ["vcs"] + }, + "text/x-vcard": { + source: "apache", + extensions: ["vcf"] + }, + "text/xml": { + source: "iana", + compressible: true, + extensions: ["xml"] + }, + "text/xml-external-parsed-entity": { + source: "iana" + }, + "text/yaml": { + compressible: true, + extensions: ["yaml", "yml"] + }, + "video/1d-interleaved-parityfec": { + source: "iana" + }, + "video/3gpp": { + source: "iana", + extensions: ["3gp", "3gpp"] + }, + "video/3gpp-tt": { + source: "iana" + }, + "video/3gpp2": { + source: "iana", + extensions: ["3g2"] + }, + "video/av1": { + source: "iana" + }, + "video/bmpeg": { + source: "iana" + }, + "video/bt656": { + source: "iana" + }, + "video/celb": { + source: "iana" + }, + "video/dv": { + source: "iana" + }, + "video/encaprtp": { + source: "iana" + }, + "video/ffv1": { + source: "iana" + }, + "video/flexfec": { + source: "iana" + }, + "video/h261": { + source: "iana", + extensions: ["h261"] + }, + "video/h263": { + source: "iana", + extensions: ["h263"] + }, + "video/h263-1998": { + source: "iana" + }, + "video/h263-2000": { + source: "iana" + }, + "video/h264": { + source: "iana", + extensions: ["h264"] + }, + "video/h264-rcdo": { + source: "iana" + }, + "video/h264-svc": { + source: "iana" + }, + "video/h265": { + source: "iana" + }, + "video/iso.segment": { + source: "iana", + extensions: ["m4s"] + }, + "video/jpeg": { + source: "iana", + extensions: ["jpgv"] + }, + "video/jpeg2000": { + source: "iana" + }, + "video/jpm": { + source: "apache", + extensions: ["jpm", "jpgm"] + }, + "video/jxsv": { + source: "iana" + }, + "video/mj2": { + source: "iana", + extensions: ["mj2", "mjp2"] + }, + "video/mp1s": { + source: "iana" + }, + "video/mp2p": { + source: "iana" + }, + "video/mp2t": { + source: "iana", + extensions: ["ts"] + }, + "video/mp4": { + source: "iana", + compressible: false, + extensions: ["mp4", "mp4v", "mpg4"] + }, + "video/mp4v-es": { + source: "iana" + }, + "video/mpeg": { + source: "iana", + compressible: false, + extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"] + }, + "video/mpeg4-generic": { + source: "iana" + }, + "video/mpv": { + source: "iana" + }, + "video/nv": { + source: "iana" + }, + "video/ogg": { + source: "iana", + compressible: false, + extensions: ["ogv"] + }, + "video/parityfec": { + source: "iana" + }, + "video/pointer": { + source: "iana" + }, + "video/quicktime": { + source: "iana", + compressible: false, + extensions: ["qt", "mov"] + }, + "video/raptorfec": { + source: "iana" + }, + "video/raw": { + source: "iana" + }, + "video/rtp-enc-aescm128": { + source: "iana" + }, + "video/rtploopback": { + source: "iana" + }, + "video/rtx": { + source: "iana" + }, + "video/scip": { + source: "iana" + }, + "video/smpte291": { + source: "iana" + }, + "video/smpte292m": { + source: "iana" + }, + "video/ulpfec": { + source: "iana" + }, + "video/vc1": { + source: "iana" + }, + "video/vc2": { + source: "iana" + }, + "video/vnd.cctv": { + source: "iana" + }, + "video/vnd.dece.hd": { + source: "iana", + extensions: ["uvh", "uvvh"] + }, + "video/vnd.dece.mobile": { + source: "iana", + extensions: ["uvm", "uvvm"] + }, + "video/vnd.dece.mp4": { + source: "iana" + }, + "video/vnd.dece.pd": { + source: "iana", + extensions: ["uvp", "uvvp"] + }, + "video/vnd.dece.sd": { + source: "iana", + extensions: ["uvs", "uvvs"] + }, + "video/vnd.dece.video": { + source: "iana", + extensions: ["uvv", "uvvv"] + }, + "video/vnd.directv.mpeg": { + source: "iana" + }, + "video/vnd.directv.mpeg-tts": { + source: "iana" + }, + "video/vnd.dlna.mpeg-tts": { + source: "iana" + }, + "video/vnd.dvb.file": { + source: "iana", + extensions: ["dvb"] + }, + "video/vnd.fvt": { + source: "iana", + extensions: ["fvt"] + }, + "video/vnd.hns.video": { + source: "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + source: "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + source: "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + source: "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + source: "iana" + }, + "video/vnd.iptvforum.ttsavc": { + source: "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + source: "iana" + }, + "video/vnd.motorola.video": { + source: "iana" + }, + "video/vnd.motorola.videop": { + source: "iana" + }, + "video/vnd.mpegurl": { + source: "iana", + extensions: ["mxu", "m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + source: "iana", + extensions: ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + source: "iana" + }, + "video/vnd.nokia.mp4vr": { + source: "iana" + }, + "video/vnd.nokia.videovoip": { + source: "iana" + }, + "video/vnd.objectvideo": { + source: "iana" + }, + "video/vnd.radgamettools.bink": { + source: "iana" + }, + "video/vnd.radgamettools.smacker": { + source: "iana" + }, + "video/vnd.sealed.mpeg1": { + source: "iana" + }, + "video/vnd.sealed.mpeg4": { + source: "iana" + }, + "video/vnd.sealed.swf": { + source: "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + source: "iana" + }, + "video/vnd.uvvu.mp4": { + source: "iana", + extensions: ["uvu", "uvvu"] + }, + "video/vnd.vivo": { + source: "iana", + extensions: ["viv"] + }, + "video/vnd.youtube.yt": { + source: "iana" + }, + "video/vp8": { + source: "iana" + }, + "video/vp9": { + source: "iana" + }, + "video/webm": { + source: "apache", + compressible: false, + extensions: ["webm"] + }, + "video/x-f4v": { + source: "apache", + extensions: ["f4v"] + }, + "video/x-fli": { + source: "apache", + extensions: ["fli"] + }, + "video/x-flv": { + source: "apache", + compressible: false, + extensions: ["flv"] + }, + "video/x-m4v": { + source: "apache", + extensions: ["m4v"] + }, + "video/x-matroska": { + source: "apache", + compressible: false, + extensions: ["mkv", "mk3d", "mks"] + }, + "video/x-mng": { + source: "apache", + extensions: ["mng"] + }, + "video/x-ms-asf": { + source: "apache", + extensions: ["asf", "asx"] + }, + "video/x-ms-vob": { + source: "apache", + extensions: ["vob"] + }, + "video/x-ms-wm": { + source: "apache", + extensions: ["wm"] + }, + "video/x-ms-wmv": { + source: "apache", + compressible: false, + extensions: ["wmv"] + }, + "video/x-ms-wmx": { + source: "apache", + extensions: ["wmx"] + }, + "video/x-ms-wvx": { + source: "apache", + extensions: ["wvx"] + }, + "video/x-msvideo": { + source: "apache", + extensions: ["avi"] + }, + "video/x-sgi-movie": { + source: "apache", + extensions: ["movie"] + }, + "video/x-smv": { + source: "apache", + extensions: ["smv"] + }, + "x-conference/x-cooltalk": { + source: "apache", + extensions: ["ice"] + }, + "x-shader/x-fragment": { + compressible: true + }, + "x-shader/x-vertex": { + compressible: true + } + }; + } +}); + +// node_modules/mime-db/index.js +var require_mime_db = __commonJS({ + "node_modules/mime-db/index.js"(exports2, module2) { + module2.exports = require_db(); + } +}); + +// node_modules/mime-types/index.js +var require_mime_types = __commonJS({ + "node_modules/mime-types/index.js"(exports2) { + "use strict"; + var db = require_mime_db(); + var extname = __require("path").extname; + var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; + var TEXT_TYPE_REGEXP = /^text\//i; + exports2.charset = charset; + exports2.charsets = { lookup: charset }; + exports2.contentType = contentType; + exports2.extension = extension; + exports2.extensions = /* @__PURE__ */ Object.create(null); + exports2.lookup = lookup; + exports2.types = /* @__PURE__ */ Object.create(null); + populateMaps(exports2.extensions, exports2.types); + function charset(type) { + if (!type || typeof type !== "string") { + return false; + } + var match = EXTRACT_TYPE_REGEXP.exec(type); + var mime = match && db[match[1].toLowerCase()]; + if (mime && mime.charset) { + return mime.charset; + } + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return "UTF-8"; + } + return false; + } + function contentType(str) { + if (!str || typeof str !== "string") { + return false; + } + var mime = str.indexOf("/") === -1 ? exports2.lookup(str) : str; + if (!mime) { + return false; + } + if (mime.indexOf("charset") === -1) { + var charset2 = exports2.charset(mime); + if (charset2) mime += "; charset=" + charset2.toLowerCase(); + } + return mime; + } + function extension(type) { + if (!type || typeof type !== "string") { + return false; + } + var match = EXTRACT_TYPE_REGEXP.exec(type); + var exts = match && exports2.extensions[match[1].toLowerCase()]; + if (!exts || !exts.length) { + return false; + } + return exts[0]; + } + function lookup(path) { + if (!path || typeof path !== "string") { + return false; + } + var extension2 = extname("x." + path).toLowerCase().substr(1); + if (!extension2) { + return false; + } + return exports2.types[extension2] || false; + } + function populateMaps(extensions, types) { + var preference = ["nginx", "apache", void 0, "iana"]; + Object.keys(db).forEach(function forEachMimeType(type) { + var mime = db[type]; + var exts = mime.extensions; + if (!exts || !exts.length) { + return; + } + extensions[type] = exts; + for (var i = 0; i < exts.length; i++) { + var extension2 = exts[i]; + if (types[extension2]) { + var from5 = preference.indexOf(db[types[extension2]].source); + var to2 = preference.indexOf(mime.source); + if (types[extension2] !== "application/octet-stream" && (from5 > to2 || from5 === to2 && types[extension2].substr(0, 12) === "application/")) { + continue; + } + } + types[extension2] = type; + } + }); + } + } +}); + +// node_modules/asynckit/lib/defer.js +var require_defer = __commonJS({ + "node_modules/asynckit/lib/defer.js"(exports2, module2) { + module2.exports = defer; + function defer(fn2) { + var nextTick = typeof setImmediate == "function" ? setImmediate : typeof process == "object" && typeof process.nextTick == "function" ? process.nextTick : null; + if (nextTick) { + nextTick(fn2); + } else { + setTimeout(fn2, 0); + } + } + } +}); + +// node_modules/asynckit/lib/async.js +var require_async = __commonJS({ + "node_modules/asynckit/lib/async.js"(exports2, module2) { + var defer = require_defer(); + module2.exports = async; + function async(callback) { + var isAsync = false; + defer(function() { + isAsync = true; + }); + return function async_callback(err, result) { + if (isAsync) { + callback(err, result); + } else { + defer(function nextTick_callback() { + callback(err, result); + }); + } + }; + } + } +}); + +// node_modules/asynckit/lib/abort.js +var require_abort = __commonJS({ + "node_modules/asynckit/lib/abort.js"(exports2, module2) { + module2.exports = abort; + function abort(state) { + Object.keys(state.jobs).forEach(clean.bind(state)); + state.jobs = {}; + } + function clean(key) { + if (typeof this.jobs[key] == "function") { + this.jobs[key](); + } + } + } +}); + +// node_modules/asynckit/lib/iterate.js +var require_iterate = __commonJS({ + "node_modules/asynckit/lib/iterate.js"(exports2, module2) { + var async = require_async(); + var abort = require_abort(); + module2.exports = iterate; + function iterate(list, iterator2, state, callback) { + var key = state["keyedList"] ? state["keyedList"][state.index] : state.index; + state.jobs[key] = runJob(iterator2, key, list[key], function(error, output) { + if (!(key in state.jobs)) { + return; + } + delete state.jobs[key]; + if (error) { + abort(state); + } else { + state.results[key] = output; + } + callback(error, state.results); + }); + } + function runJob(iterator2, key, item, callback) { + var aborter; + if (iterator2.length == 2) { + aborter = iterator2(item, async(callback)); + } else { + aborter = iterator2(item, key, async(callback)); + } + return aborter; + } + } +}); + +// node_modules/asynckit/lib/state.js +var require_state = __commonJS({ + "node_modules/asynckit/lib/state.js"(exports2, module2) { + module2.exports = state; + function state(list, sortMethod) { + var isNamedList = !Array.isArray(list), initState = { + index: 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs: {}, + results: isNamedList ? {} : [], + size: isNamedList ? Object.keys(list).length : list.length + }; + if (sortMethod) { + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b2) { + return sortMethod(list[a], list[b2]); + }); + } + return initState; + } + } +}); + +// node_modules/asynckit/lib/terminator.js +var require_terminator = __commonJS({ + "node_modules/asynckit/lib/terminator.js"(exports2, module2) { + var abort = require_abort(); + var async = require_async(); + module2.exports = terminator; + function terminator(callback) { + if (!Object.keys(this.jobs).length) { + return; + } + this.index = this.size; + abort(this); + async(callback)(null, this.results); + } + } +}); + +// node_modules/asynckit/parallel.js +var require_parallel = __commonJS({ + "node_modules/asynckit/parallel.js"(exports2, module2) { + var iterate = require_iterate(); + var initState = require_state(); + var terminator = require_terminator(); + module2.exports = parallel; + function parallel(list, iterator2, callback) { + var state = initState(list); + while (state.index < (state["keyedList"] || list).length) { + iterate(list, iterator2, state, function(error, result) { + if (error) { + callback(error, result); + return; + } + if (Object.keys(state.jobs).length === 0) { + callback(null, state.results); + return; + } + }); + state.index++; + } + return terminator.bind(state, callback); + } + } +}); + +// node_modules/asynckit/serialOrdered.js +var require_serialOrdered = __commonJS({ + "node_modules/asynckit/serialOrdered.js"(exports2, module2) { + var iterate = require_iterate(); + var initState = require_state(); + var terminator = require_terminator(); + module2.exports = serialOrdered; + module2.exports.ascending = ascending; + module2.exports.descending = descending; + function serialOrdered(list, iterator2, sortMethod, callback) { + var state = initState(list, sortMethod); + iterate(list, iterator2, state, function iteratorHandler(error, result) { + if (error) { + callback(error, result); + return; + } + state.index++; + if (state.index < (state["keyedList"] || list).length) { + iterate(list, iterator2, state, iteratorHandler); + return; + } + callback(null, state.results); + }); + return terminator.bind(state, callback); + } + function ascending(a, b2) { + return a < b2 ? -1 : a > b2 ? 1 : 0; + } + function descending(a, b2) { + return -1 * ascending(a, b2); + } + } +}); + +// node_modules/asynckit/serial.js +var require_serial = __commonJS({ + "node_modules/asynckit/serial.js"(exports2, module2) { + var serialOrdered = require_serialOrdered(); + module2.exports = serial; + function serial(list, iterator2, callback) { + return serialOrdered(list, iterator2, null, callback); + } + } +}); + +// node_modules/asynckit/index.js +var require_asynckit = __commonJS({ + "node_modules/asynckit/index.js"(exports2, module2) { + module2.exports = { + parallel: require_parallel(), + serial: require_serial(), + serialOrdered: require_serialOrdered() + }; + } +}); + +// node_modules/es-object-atoms/index.js +var require_es_object_atoms = __commonJS({ + "node_modules/es-object-atoms/index.js"(exports2, module2) { + "use strict"; + module2.exports = Object; + } +}); + +// node_modules/es-errors/index.js +var require_es_errors = __commonJS({ + "node_modules/es-errors/index.js"(exports2, module2) { + "use strict"; + module2.exports = Error; + } +}); + +// node_modules/es-errors/eval.js +var require_eval = __commonJS({ + "node_modules/es-errors/eval.js"(exports2, module2) { + "use strict"; + module2.exports = EvalError; + } +}); + +// node_modules/es-errors/range.js +var require_range = __commonJS({ + "node_modules/es-errors/range.js"(exports2, module2) { + "use strict"; + module2.exports = RangeError; + } +}); + +// node_modules/es-errors/ref.js +var require_ref = __commonJS({ + "node_modules/es-errors/ref.js"(exports2, module2) { + "use strict"; + module2.exports = ReferenceError; + } +}); + +// node_modules/es-errors/syntax.js +var require_syntax = __commonJS({ + "node_modules/es-errors/syntax.js"(exports2, module2) { + "use strict"; + module2.exports = SyntaxError; + } +}); + +// node_modules/es-errors/type.js +var require_type = __commonJS({ + "node_modules/es-errors/type.js"(exports2, module2) { + "use strict"; + module2.exports = TypeError; + } +}); + +// node_modules/es-errors/uri.js +var require_uri = __commonJS({ + "node_modules/es-errors/uri.js"(exports2, module2) { + "use strict"; + module2.exports = URIError; + } +}); + +// node_modules/math-intrinsics/abs.js +var require_abs = __commonJS({ + "node_modules/math-intrinsics/abs.js"(exports2, module2) { + "use strict"; + module2.exports = Math.abs; + } +}); + +// node_modules/math-intrinsics/floor.js +var require_floor = __commonJS({ + "node_modules/math-intrinsics/floor.js"(exports2, module2) { + "use strict"; + module2.exports = Math.floor; + } +}); + +// node_modules/math-intrinsics/max.js +var require_max = __commonJS({ + "node_modules/math-intrinsics/max.js"(exports2, module2) { + "use strict"; + module2.exports = Math.max; + } +}); + +// node_modules/math-intrinsics/min.js +var require_min = __commonJS({ + "node_modules/math-intrinsics/min.js"(exports2, module2) { + "use strict"; + module2.exports = Math.min; + } +}); + +// node_modules/math-intrinsics/pow.js +var require_pow = __commonJS({ + "node_modules/math-intrinsics/pow.js"(exports2, module2) { + "use strict"; + module2.exports = Math.pow; + } +}); + +// node_modules/math-intrinsics/round.js +var require_round = __commonJS({ + "node_modules/math-intrinsics/round.js"(exports2, module2) { + "use strict"; + module2.exports = Math.round; + } +}); + +// node_modules/math-intrinsics/isNaN.js +var require_isNaN = __commonJS({ + "node_modules/math-intrinsics/isNaN.js"(exports2, module2) { + "use strict"; + module2.exports = Number.isNaN || function isNaN2(a) { + return a !== a; + }; + } +}); + +// node_modules/math-intrinsics/sign.js +var require_sign = __commonJS({ + "node_modules/math-intrinsics/sign.js"(exports2, module2) { + "use strict"; + var $isNaN = require_isNaN(); + module2.exports = function sign2(number) { + if ($isNaN(number) || number === 0) { + return number; + } + return number < 0 ? -1 : 1; + }; + } +}); + +// node_modules/gopd/gOPD.js +var require_gOPD = __commonJS({ + "node_modules/gopd/gOPD.js"(exports2, module2) { + "use strict"; + module2.exports = Object.getOwnPropertyDescriptor; + } +}); + +// node_modules/gopd/index.js +var require_gopd = __commonJS({ + "node_modules/gopd/index.js"(exports2, module2) { + "use strict"; + var $gOPD = require_gOPD(); + if ($gOPD) { + try { + $gOPD([], "length"); + } catch (e) { + $gOPD = null; + } + } + module2.exports = $gOPD; + } +}); + +// node_modules/es-define-property/index.js +var require_es_define_property = __commonJS({ + "node_modules/es-define-property/index.js"(exports2, module2) { + "use strict"; + var $defineProperty = Object.defineProperty || false; + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e) { + $defineProperty = false; + } + } + module2.exports = $defineProperty; + } +}); + +// node_modules/has-symbols/shams.js +var require_shams = __commonJS({ + "node_modules/has-symbols/shams.js"(exports2, module2) { + "use strict"; + module2.exports = function hasSymbols() { + if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { + return false; + } + if (typeof Symbol.iterator === "symbol") { + return true; + } + var obj = {}; + var sym = Symbol("test"); + var symObj = Object(sym); + if (typeof sym === "string") { + return false; + } + if (Object.prototype.toString.call(sym) !== "[object Symbol]") { + return false; + } + if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { + return false; + } + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { + return false; + } + if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { + return false; + } + if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { + return false; + } + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { + return false; + } + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { + return false; + } + if (typeof Object.getOwnPropertyDescriptor === "function") { + var descriptor = ( + /** @type {PropertyDescriptor} */ + Object.getOwnPropertyDescriptor(obj, sym) + ); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { + return false; + } + } + return true; + }; + } +}); + +// node_modules/has-symbols/index.js +var require_has_symbols = __commonJS({ + "node_modules/has-symbols/index.js"(exports2, module2) { + "use strict"; + var origSymbol = typeof Symbol !== "undefined" && Symbol; + var hasSymbolSham = require_shams(); + module2.exports = function hasNativeSymbols() { + if (typeof origSymbol !== "function") { + return false; + } + if (typeof Symbol !== "function") { + return false; + } + if (typeof origSymbol("foo") !== "symbol") { + return false; + } + if (typeof Symbol("bar") !== "symbol") { + return false; + } + return hasSymbolSham(); + }; + } +}); + +// node_modules/get-proto/Reflect.getPrototypeOf.js +var require_Reflect_getPrototypeOf = __commonJS({ + "node_modules/get-proto/Reflect.getPrototypeOf.js"(exports2, module2) { + "use strict"; + module2.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null; + } +}); + +// node_modules/get-proto/Object.getPrototypeOf.js +var require_Object_getPrototypeOf = __commonJS({ + "node_modules/get-proto/Object.getPrototypeOf.js"(exports2, module2) { + "use strict"; + var $Object = require_es_object_atoms(); + module2.exports = $Object.getPrototypeOf || null; + } +}); + +// node_modules/function-bind/implementation.js +var require_implementation = __commonJS({ + "node_modules/function-bind/implementation.js"(exports2, module2) { + "use strict"; + var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; + var toStr = Object.prototype.toString; + var max = Math.max; + var funcType = "[object Function]"; + var concatty = function concatty2(a, b2) { + var arr = []; + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j2 = 0; j2 < b2.length; j2 += 1) { + arr[j2 + a.length] = b2[j2]; + } + return arr; + }; + var slicy = function slicy2(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j2 = 0; i < arrLike.length; i += 1, j2 += 1) { + arr[j2] = arrLike[i]; + } + return arr; + }; + var joiny = function(arr, joiner) { + var str = ""; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; + }; + module2.exports = function bind2(that) { + var target = this; + if (typeof target !== "function" || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + var bound; + var binder = function() { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + }; + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = "$" + i; + } + bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); + if (target.prototype) { + var Empty = function Empty2() { + }; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; + }; + } +}); + +// node_modules/function-bind/index.js +var require_function_bind = __commonJS({ + "node_modules/function-bind/index.js"(exports2, module2) { + "use strict"; + var implementation = require_implementation(); + module2.exports = Function.prototype.bind || implementation; + } +}); + +// node_modules/call-bind-apply-helpers/functionCall.js +var require_functionCall = __commonJS({ + "node_modules/call-bind-apply-helpers/functionCall.js"(exports2, module2) { + "use strict"; + module2.exports = Function.prototype.call; + } +}); + +// node_modules/call-bind-apply-helpers/functionApply.js +var require_functionApply = __commonJS({ + "node_modules/call-bind-apply-helpers/functionApply.js"(exports2, module2) { + "use strict"; + module2.exports = Function.prototype.apply; + } +}); + +// node_modules/call-bind-apply-helpers/reflectApply.js +var require_reflectApply = __commonJS({ + "node_modules/call-bind-apply-helpers/reflectApply.js"(exports2, module2) { + "use strict"; + module2.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply; + } +}); + +// node_modules/call-bind-apply-helpers/actualApply.js +var require_actualApply = __commonJS({ + "node_modules/call-bind-apply-helpers/actualApply.js"(exports2, module2) { + "use strict"; + var bind2 = require_function_bind(); + var $apply = require_functionApply(); + var $call = require_functionCall(); + var $reflectApply = require_reflectApply(); + module2.exports = $reflectApply || bind2.call($call, $apply); + } +}); + +// node_modules/call-bind-apply-helpers/index.js +var require_call_bind_apply_helpers = __commonJS({ + "node_modules/call-bind-apply-helpers/index.js"(exports2, module2) { + "use strict"; + var bind2 = require_function_bind(); + var $TypeError = require_type(); + var $call = require_functionCall(); + var $actualApply = require_actualApply(); + module2.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== "function") { + throw new $TypeError("a function is required"); + } + return $actualApply(bind2, $call, args); + }; + } +}); + +// node_modules/dunder-proto/get.js +var require_get = __commonJS({ + "node_modules/dunder-proto/get.js"(exports2, module2) { + "use strict"; + var callBind = require_call_bind_apply_helpers(); + var gOPD = require_gopd(); + var hasProtoAccessor; + try { + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ + [].__proto__ === Array.prototype; + } catch (e) { + if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") { + throw e; + } + } + var desc = !!hasProtoAccessor && gOPD && gOPD( + Object.prototype, + /** @type {keyof typeof Object.prototype} */ + "__proto__" + ); + var $Object = Object; + var $getPrototypeOf = $Object.getPrototypeOf; + module2.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? ( + /** @type {import('./get')} */ + function getDunder(value) { + return $getPrototypeOf(value == null ? value : $Object(value)); + } + ) : false; + } +}); + +// node_modules/get-proto/index.js +var require_get_proto = __commonJS({ + "node_modules/get-proto/index.js"(exports2, module2) { + "use strict"; + var reflectGetProto = require_Reflect_getPrototypeOf(); + var originalGetProto = require_Object_getPrototypeOf(); + var getDunderProto = require_get(); + module2.exports = reflectGetProto ? function getProto(O) { + return reflectGetProto(O); + } : originalGetProto ? function getProto(O) { + if (!O || typeof O !== "object" && typeof O !== "function") { + throw new TypeError("getProto: not an object"); + } + return originalGetProto(O); + } : getDunderProto ? function getProto(O) { + return getDunderProto(O); + } : null; + } +}); + +// node_modules/hasown/index.js +var require_hasown = __commonJS({ + "node_modules/hasown/index.js"(exports2, module2) { + "use strict"; + var call2 = Function.prototype.call; + var $hasOwn = Object.prototype.hasOwnProperty; + var bind2 = require_function_bind(); + module2.exports = bind2.call(call2, $hasOwn); + } +}); + +// node_modules/get-intrinsic/index.js +var require_get_intrinsic = __commonJS({ + "node_modules/get-intrinsic/index.js"(exports2, module2) { + "use strict"; + var undefined2; + var $Object = require_es_object_atoms(); + var $Error = require_es_errors(); + var $EvalError = require_eval(); + var $RangeError = require_range(); + var $ReferenceError = require_ref(); + var $SyntaxError = require_syntax(); + var $TypeError = require_type(); + var $URIError = require_uri(); + var abs = require_abs(); + var floor = require_floor(); + var max = require_max(); + var min = require_min(); + var pow3 = require_pow(); + var round = require_round(); + var sign2 = require_sign(); + var $Function = Function; + var getEvalledConstructor = function(expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); + } catch (e) { + } + }; + var $gOPD = require_gopd(); + var $defineProperty = require_es_define_property(); + var throwTypeError = function() { + throw new $TypeError(); + }; + var ThrowTypeError = $gOPD ? function() { + try { + arguments.callee; + return throwTypeError; + } catch (calleeThrows) { + try { + return $gOPD(arguments, "callee").get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }() : throwTypeError; + var hasSymbols = require_has_symbols()(); + var getProto = require_get_proto(); + var $ObjectGPO = require_Object_getPrototypeOf(); + var $ReflectGPO = require_Reflect_getPrototypeOf(); + var $apply = require_functionApply(); + var $call = require_functionCall(); + var needsEval = {}; + var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array); + var INTRINSICS = { + __proto__: null, + "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError, + "%Array%": Array, + "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer, + "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, + "%AsyncFromSyncIteratorPrototype%": undefined2, + "%AsyncFunction%": needsEval, + "%AsyncGenerator%": needsEval, + "%AsyncGeneratorFunction%": needsEval, + "%AsyncIteratorPrototype%": needsEval, + "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics, + "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt, + "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array, + "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array, + "%Boolean%": Boolean, + "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView, + "%Date%": Date, + "%decodeURI%": decodeURI, + "%decodeURIComponent%": decodeURIComponent, + "%encodeURI%": encodeURI, + "%encodeURIComponent%": encodeURIComponent, + "%Error%": $Error, + "%eval%": eval, + // eslint-disable-line no-eval + "%EvalError%": $EvalError, + "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array, + "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array, + "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array, + "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry, + "%Function%": $Function, + "%GeneratorFunction%": needsEval, + "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array, + "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array, + "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array, + "%isFinite%": isFinite, + "%isNaN%": isNaN, + "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, + "%JSON%": typeof JSON === "object" ? JSON : undefined2, + "%Map%": typeof Map === "undefined" ? undefined2 : Map, + "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()), + "%Math%": Math, + "%Number%": Number, + "%Object%": $Object, + "%Object.getOwnPropertyDescriptor%": $gOPD, + "%parseFloat%": parseFloat, + "%parseInt%": parseInt, + "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise, + "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy, + "%RangeError%": $RangeError, + "%ReferenceError%": $ReferenceError, + "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect, + "%RegExp%": RegExp, + "%Set%": typeof Set === "undefined" ? undefined2 : Set, + "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()), + "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer, + "%String%": String, + "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, + "%Symbol%": hasSymbols ? Symbol : undefined2, + "%SyntaxError%": $SyntaxError, + "%ThrowTypeError%": ThrowTypeError, + "%TypedArray%": TypedArray, + "%TypeError%": $TypeError, + "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array, + "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray, + "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array, + "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array, + "%URIError%": $URIError, + "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap, + "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef, + "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet, + "%Function.prototype.call%": $call, + "%Function.prototype.apply%": $apply, + "%Object.defineProperty%": $defineProperty, + "%Object.getPrototypeOf%": $ObjectGPO, + "%Math.abs%": abs, + "%Math.floor%": floor, + "%Math.max%": max, + "%Math.min%": min, + "%Math.pow%": pow3, + "%Math.round%": round, + "%Math.sign%": sign2, + "%Reflect.getPrototypeOf%": $ReflectGPO + }; + if (getProto) { + try { + null.error; + } catch (e) { + errorProto = getProto(getProto(e)); + INTRINSICS["%Error.prototype%"] = errorProto; + } + } + var errorProto; + var doEval = function doEval2(name) { + var value; + if (name === "%AsyncFunction%") { + value = getEvalledConstructor("async function () {}"); + } else if (name === "%GeneratorFunction%") { + value = getEvalledConstructor("function* () {}"); + } else if (name === "%AsyncGeneratorFunction%") { + value = getEvalledConstructor("async function* () {}"); + } else if (name === "%AsyncGenerator%") { + var fn2 = doEval2("%AsyncGeneratorFunction%"); + if (fn2) { + value = fn2.prototype; + } + } else if (name === "%AsyncIteratorPrototype%") { + var gen3 = doEval2("%AsyncGenerator%"); + if (gen3 && getProto) { + value = getProto(gen3.prototype); + } + } + INTRINSICS[name] = value; + return value; + }; + var LEGACY_ALIASES = { + __proto__: null, + "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], + "%ArrayPrototype%": ["Array", "prototype"], + "%ArrayProto_entries%": ["Array", "prototype", "entries"], + "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], + "%ArrayProto_keys%": ["Array", "prototype", "keys"], + "%ArrayProto_values%": ["Array", "prototype", "values"], + "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], + "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], + "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], + "%BooleanPrototype%": ["Boolean", "prototype"], + "%DataViewPrototype%": ["DataView", "prototype"], + "%DatePrototype%": ["Date", "prototype"], + "%ErrorPrototype%": ["Error", "prototype"], + "%EvalErrorPrototype%": ["EvalError", "prototype"], + "%Float32ArrayPrototype%": ["Float32Array", "prototype"], + "%Float64ArrayPrototype%": ["Float64Array", "prototype"], + "%FunctionPrototype%": ["Function", "prototype"], + "%Generator%": ["GeneratorFunction", "prototype"], + "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], + "%Int8ArrayPrototype%": ["Int8Array", "prototype"], + "%Int16ArrayPrototype%": ["Int16Array", "prototype"], + "%Int32ArrayPrototype%": ["Int32Array", "prototype"], + "%JSONParse%": ["JSON", "parse"], + "%JSONStringify%": ["JSON", "stringify"], + "%MapPrototype%": ["Map", "prototype"], + "%NumberPrototype%": ["Number", "prototype"], + "%ObjectPrototype%": ["Object", "prototype"], + "%ObjProto_toString%": ["Object", "prototype", "toString"], + "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], + "%PromisePrototype%": ["Promise", "prototype"], + "%PromiseProto_then%": ["Promise", "prototype", "then"], + "%Promise_all%": ["Promise", "all"], + "%Promise_reject%": ["Promise", "reject"], + "%Promise_resolve%": ["Promise", "resolve"], + "%RangeErrorPrototype%": ["RangeError", "prototype"], + "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], + "%RegExpPrototype%": ["RegExp", "prototype"], + "%SetPrototype%": ["Set", "prototype"], + "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], + "%StringPrototype%": ["String", "prototype"], + "%SymbolPrototype%": ["Symbol", "prototype"], + "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], + "%TypedArrayPrototype%": ["TypedArray", "prototype"], + "%TypeErrorPrototype%": ["TypeError", "prototype"], + "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], + "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], + "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], + "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], + "%URIErrorPrototype%": ["URIError", "prototype"], + "%WeakMapPrototype%": ["WeakMap", "prototype"], + "%WeakSetPrototype%": ["WeakSet", "prototype"] + }; + var bind2 = require_function_bind(); + var hasOwn = require_hasown(); + var $concat = bind2.call($call, Array.prototype.concat); + var $spliceApply = bind2.call($apply, Array.prototype.splice); + var $replace = bind2.call($call, String.prototype.replace); + var $strSlice = bind2.call($call, String.prototype.slice); + var $exec = bind2.call($call, RegExp.prototype.exec); + var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; + var reEscapeChar = /\\(\\)?/g; + var stringToPath = function stringToPath2(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === "%" && last !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); + } else if (last === "%" && first !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); + } + var result = []; + $replace(string, rePropName, function(match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match; + }); + return result; + }; + var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = "%" + alias[0] + "%"; + } + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === "undefined" && !allowMissing) { + throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!"); + } + return { + alias, + name: intrinsicName, + value + }; + } + throw new $SyntaxError("intrinsic " + name + " does not exist!"); + }; + module2.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== "string" || name.length === 0) { + throw new $TypeError("intrinsic name must be a non-empty string"); + } + if (arguments.length > 1 && typeof allowMissing !== "boolean") { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; + var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { + throw new $SyntaxError("property names with quotes must have matching quotes"); + } + if (part === "constructor" || !isOwn) { + skipFurtherCaching = true; + } + intrinsicBaseName += "." + part; + intrinsicRealName = "%" + intrinsicBaseName + "%"; + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available."); + } + return void undefined2; + } + if ($gOPD && i + 1 >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + if (isOwn && "get" in desc && !("originalValue" in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; + }; + } +}); + +// node_modules/has-tostringtag/shams.js +var require_shams2 = __commonJS({ + "node_modules/has-tostringtag/shams.js"(exports2, module2) { + "use strict"; + var hasSymbols = require_shams(); + module2.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; + }; + } +}); + +// node_modules/es-set-tostringtag/index.js +var require_es_set_tostringtag = __commonJS({ + "node_modules/es-set-tostringtag/index.js"(exports2, module2) { + "use strict"; + var GetIntrinsic = require_get_intrinsic(); + var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); + var hasToStringTag = require_shams2()(); + var hasOwn = require_hasown(); + var $TypeError = require_type(); + var toStringTag2 = hasToStringTag ? Symbol.toStringTag : null; + module2.exports = function setToStringTag(object, value) { + var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; + var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; + if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") { + throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans"); + } + if (toStringTag2 && (overrideIfSet || !hasOwn(object, toStringTag2))) { + if ($defineProperty) { + $defineProperty(object, toStringTag2, { + configurable: !nonConfigurable, + enumerable: false, + value, + writable: false + }); + } else { + object[toStringTag2] = value; + } + } + }; + } +}); + +// node_modules/form-data/lib/populate.js +var require_populate = __commonJS({ + "node_modules/form-data/lib/populate.js"(exports2, module2) { + module2.exports = function(dst, src) { + Object.keys(src).forEach(function(prop) { + dst[prop] = dst[prop] || src[prop]; + }); + return dst; + }; + } +}); + +// node_modules/form-data/lib/form_data.js +var require_form_data = __commonJS({ + "node_modules/form-data/lib/form_data.js"(exports2, module2) { + var CombinedStream = require_combined_stream(); + var util3 = __require("util"); + var path = __require("path"); + var http3 = __require("http"); + var https2 = __require("https"); + var parseUrl = __require("url").parse; + var fs2 = __require("fs"); + var Stream = __require("stream").Stream; + var mime = require_mime_types(); + var asynckit = require_asynckit(); + var setToStringTag = require_es_set_tostringtag(); + var populate = require_populate(); + module2.exports = FormData3; + util3.inherits(FormData3, CombinedStream); + function FormData3(options) { + if (!(this instanceof FormData3)) { + return new FormData3(options); + } + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + CombinedStream.call(this); + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } + } + FormData3.LINE_BREAK = "\r\n"; + FormData3.DEFAULT_CONTENT_TYPE = "application/octet-stream"; + FormData3.prototype.append = function(field, value, options) { + options = options || {}; + if (typeof options == "string") { + options = { filename: options }; + } + var append2 = CombinedStream.prototype.append.bind(this); + if (typeof value == "number") { + value = "" + value; + } + if (Array.isArray(value)) { + this._error(new Error("Arrays are not supported.")); + return; + } + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + append2(header); + append2(value); + append2(footer); + this._trackLength(header, value, options); + }; + FormData3.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === "string") { + valueLength = Buffer.byteLength(value); + } + this._valueLength += valueLength; + this._overheadLength += Buffer.byteLength(header) + FormData3.LINE_BREAK.length; + if (!value || !value.path && !(value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) && !(value instanceof Stream)) { + return; + } + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } + }; + FormData3.prototype._lengthRetriever = function(value, callback) { + if (Object.prototype.hasOwnProperty.call(value, "fd")) { + if (value.end != void 0 && value.end != Infinity && value.start != void 0) { + callback(null, value.end + 1 - (value.start ? value.start : 0)); + } else { + fs2.stat(value.path, function(err, stat) { + var fileSize; + if (err) { + callback(err); + return; + } + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } + } else if (Object.prototype.hasOwnProperty.call(value, "httpVersion")) { + callback(null, +value.headers["content-length"]); + } else if (Object.prototype.hasOwnProperty.call(value, "httpModule")) { + value.on("response", function(response) { + value.pause(); + callback(null, +response.headers["content-length"]); + }); + value.resume(); + } else { + callback("Unknown stream"); + } + }; + FormData3.prototype._multiPartHeader = function(field, value, options) { + if (typeof options.header == "string") { + return options.header; + } + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + var contents = ""; + var headers = { + // add custom disposition as third element or keep it two elements if not + "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + "Content-Type": [].concat(contentType || []) + }; + if (typeof options.header == "object") { + populate(headers, options.header); + } + var header; + for (var prop in headers) { + if (Object.prototype.hasOwnProperty.call(headers, prop)) { + header = headers[prop]; + if (header == null) { + continue; + } + if (!Array.isArray(header)) { + header = [header]; + } + if (header.length) { + contents += prop + ": " + header.join("; ") + FormData3.LINE_BREAK; + } + } + } + return "--" + this.getBoundary() + FormData3.LINE_BREAK + contents + FormData3.LINE_BREAK; + }; + FormData3.prototype._getContentDisposition = function(value, options) { + var filename, contentDisposition; + if (typeof options.filepath === "string") { + filename = path.normalize(options.filepath).replace(/\\/g, "/"); + } else if (options.filename || value.name || value.path) { + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) { + filename = path.basename(value.client._httpMessage.path || ""); + } + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } + return contentDisposition; + }; + FormData3.prototype._getContentType = function(value, options) { + var contentType = options.contentType; + if (!contentType && value.name) { + contentType = mime.lookup(value.name); + } + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } + if (!contentType && value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) { + contentType = value.headers["content-type"]; + } + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } + if (!contentType && typeof value == "object") { + contentType = FormData3.DEFAULT_CONTENT_TYPE; + } + return contentType; + }; + FormData3.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData3.LINE_BREAK; + var lastPart = this._streams.length === 0; + if (lastPart) { + footer += this._lastBoundary(); + } + next(footer); + }.bind(this); + }; + FormData3.prototype._lastBoundary = function() { + return "--" + this.getBoundary() + "--" + FormData3.LINE_BREAK; + }; + FormData3.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + "content-type": "multipart/form-data; boundary=" + this.getBoundary() + }; + for (header in userHeaders) { + if (Object.prototype.hasOwnProperty.call(userHeaders, header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } + return formHeaders; + }; + FormData3.prototype.setBoundary = function(boundary) { + this._boundary = boundary; + }; + FormData3.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } + return this._boundary; + }; + FormData3.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc(0); + var boundary = this.getBoundary(); + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== "function") { + if (Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); + } else { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); + } + if (typeof this._streams[i] !== "string" || this._streams[i].substring(2, boundary.length + 2) !== boundary) { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData3.LINE_BREAK)]); + } + } + } + return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); + }; + FormData3.prototype._generateBoundary = function() { + var boundary = "--------------------------"; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } + this._boundary = boundary; + }; + FormData3.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + if (!this.hasKnownLength()) { + this._error(new Error("Cannot calculate proper length in synchronous way.")); + } + return knownLength; + }; + FormData3.prototype.hasKnownLength = function() { + var hasKnownLength = true; + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } + return hasKnownLength; + }; + FormData3.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } + values.forEach(function(length) { + knownLength += length; + }); + cb(null, knownLength); + }); + }; + FormData3.prototype.submit = function(params, cb) { + var request, options, defaults2 = { method: "post" }; + if (typeof params == "string") { + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults2); + } else { + options = populate(params, defaults2); + if (!options.port) { + options.port = options.protocol == "https:" ? 443 : 80; + } + } + options.headers = this.getHeaders(params.headers); + if (options.protocol == "https:") { + request = https2.request(options); + } else { + request = http3.request(options); + } + this.getLength(function(err, length) { + if (err && err !== "Unknown stream") { + this._error(err); + return; + } + if (length) { + request.setHeader("Content-Length", length); + } + this.pipe(request); + if (cb) { + var onResponse; + var callback = function(error, responce) { + request.removeListener("error", callback); + request.removeListener("response", onResponse); + return cb.call(this, error, responce); + }; + onResponse = callback.bind(this, null); + request.on("error", callback); + request.on("response", onResponse); + } + }.bind(this)); + return request; + }; + FormData3.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit("error", err); + } + }; + FormData3.prototype.toString = function() { + return "[object FormData]"; + }; + setToStringTag(FormData3, "FormData"); + } +}); + +// node_modules/proxy-from-env/index.js +var require_proxy_from_env = __commonJS({ + "node_modules/proxy-from-env/index.js"(exports2) { + "use strict"; + var parseUrl = __require("url").parse; + var DEFAULT_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 + }; + var stringEndsWith = String.prototype.endsWith || function(s) { + return s.length <= this.length && this.indexOf(s, this.length - s.length) !== -1; + }; + function getProxyForUrl(url2) { + var parsedUrl = typeof url2 === "string" ? parseUrl(url2) : url2 || {}; + var proto = parsedUrl.protocol; + var hostname = parsedUrl.host; + var port = parsedUrl.port; + if (typeof hostname !== "string" || !hostname || typeof proto !== "string") { + return ""; + } + proto = proto.split(":", 1)[0]; + hostname = hostname.replace(/:\d*$/, ""); + port = parseInt(port) || DEFAULT_PORTS[proto] || 0; + if (!shouldProxy(hostname, port)) { + return ""; + } + var proxy = getEnv("npm_config_" + proto + "_proxy") || getEnv(proto + "_proxy") || getEnv("npm_config_proxy") || getEnv("all_proxy"); + if (proxy && proxy.indexOf("://") === -1) { + proxy = proto + "://" + proxy; + } + return proxy; + } + function shouldProxy(hostname, port) { + var NO_PROXY = (getEnv("npm_config_no_proxy") || getEnv("no_proxy")).toLowerCase(); + if (!NO_PROXY) { + return true; + } + if (NO_PROXY === "*") { + return false; + } + return NO_PROXY.split(/[,\s]/).every(function(proxy) { + if (!proxy) { + return true; + } + var parsedProxy = proxy.match(/^(.+):(\d+)$/); + var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; + var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; + if (parsedProxyPort && parsedProxyPort !== port) { + return true; + } + if (!/^[.*]/.test(parsedProxyHostname)) { + return hostname !== parsedProxyHostname; + } + if (parsedProxyHostname.charAt(0) === "*") { + parsedProxyHostname = parsedProxyHostname.slice(1); + } + return !stringEndsWith.call(hostname, parsedProxyHostname); + }); + } + function getEnv(key) { + return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ""; + } + exports2.getProxyForUrl = getProxyForUrl; + } +}); + +// node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/ms/index.js"(exports2, module2) { + var s = 1e3; + var m2 = s * 60; + var h = m2 * 60; + var d = h * 24; + var w2 = d * 7; + var y2 = d * 365.25; + module2.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === "string" && val.length > 0) { + return parse(val); + } else if (type === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) + ); + }; + function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || "ms").toLowerCase(); + switch (type) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y2; + case "weeks": + case "week": + case "w": + return n * w2; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m2; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; + } + } + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m2) { + return Math.round(ms / m2) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; + } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); + } + if (msAbs >= m2) { + return plural(ms, msAbs, m2, "minute"); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } + } +}); + +// node_modules/debug/src/common.js +var require_common = __commonJS({ + "node_modules/debug/src/common.js"(exports2, module2) { + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash2 = 0; + for (let i = 0; i < namespace.length; i++) { + hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); + hash2 |= 0; + } + return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug(...args) { + if (!debug.enabled) { + return; + } + const self2 = debug; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index2 = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; + } + index2++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index2]; + match = formatter.call(self2, val); + args.splice(index2, 1); + index2--; + } + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend2; + debug.destroy = createDebug.destroy; + Object.defineProperty(debug, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug); + } + return debug; + } + function extend2(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split3 = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns2 of split3) { + if (ns2[0] === "-") { + createDebug.skips.push(ns2.slice(1)); + } else { + createDebug.names.push(ns2); + } + } + } + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; + } + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; + } + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + for (const skip2 of createDebug.skips) { + if (matchesTemplate(name, skip2)) { + return false; + } + } + for (const ns2 of createDebug.names) { + if (matchesTemplate(name, ns2)) { + return true; + } + } + return false; + } + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + module2.exports = setup; + } +}); + +// node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/debug/src/browser.js"(exports2, module2) { + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load; + exports2.useColors = useColors; + exports2.storage = localstorage(); + exports2.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports2.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m2; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m2 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m2[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index2 = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index2++; + if (match === "%c") { + lastC = index2; + } + }); + args.splice(lastC, 0, c); + } + exports2.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports2.storage.setItem("debug", namespaces); + } else { + exports2.storage.removeItem("debug"); + } + } catch (error) { + } + } + function load() { + let r; + try { + r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); + } catch (error) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error) { + } + } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error) { + return "[UnexpectedJSONParseError]: " + error.message; + } + }; + } +}); + +// node_modules/has-flag/index.js +var require_has_flag = __commonJS({ + "node_modules/has-flag/index.js"(exports2, module2) { + "use strict"; + module2.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; + } +}); + +// node_modules/supports-color/index.js +var require_supports_color = __commonJS({ + "node_modules/supports-color/index.js"(exports2, module2) { + "use strict"; + var os2 = __require("os"); + var tty = __require("tty"); + var hasFlag = require_has_flag(); + var { env } = process; + var forceColor; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { + forceColor = 0; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + forceColor = 1; + } + if ("FORCE_COLOR" in env) { + if (env.FORCE_COLOR === "true") { + forceColor = 1; + } else if (env.FORCE_COLOR === "false") { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } + } + function translateLevel(level) { + if (level === 0) { + return false; + } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; + } + if (hasFlag("color=256")) { + return 2; + } + if (haveStream && !streamIsTTY && forceColor === void 0) { + return 0; + } + const min = forceColor || 0; + if (env.TERM === "dumb") { + return min; + } + if (process.platform === "win32") { + const osRelease = os2.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign2) => sign2 in env) || env.CI_NAME === "codeship") { + return 1; + } + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if (env.COLORTERM === "truecolor") { + return 3; + } + if ("TERM_PROGRAM" in env) { + const version4 = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version4 >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; + } + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + return min; + } + function getSupportLevel(stream4) { + const level = supportsColor(stream4, stream4 && stream4.isTTY); + return translateLevel(level); + } + module2.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) + }; + } +}); + +// node_modules/debug/src/node.js +var require_node = __commonJS({ + "node_modules/debug/src/node.js"(exports2, module2) { + var tty = __require("tty"); + var util3 = __require("util"); + exports2.init = init; + exports2.log = log; + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load; + exports2.useColors = useColors; + exports2.destroy = util3.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports2.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = require_supports_color(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports2.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error) { + } + exports2.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k2) => { + return k2.toUpperCase(); + }); + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === "null") { + val = null; + } else { + val = Number(val); + } + obj[prop] = val; + return obj; + }, {}); + function useColors() { + return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + function formatArgs(args) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args[0] = prefix + args[0].split("\n").join("\n" + prefix); + args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + " " + args[0]; + } + } + function getDate() { + if (exports2.inspectOpts.hideDate) { + return ""; + } + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + function log(...args) { + return process.stderr.write(util3.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + } + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + function load() { + return process.env.DEBUG; + } + function init(debug) { + debug.inspectOpts = {}; + const keys = Object.keys(exports2.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + } + } + module2.exports = require_common()(exports2); + var { formatters } = module2.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util3.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util3.inspect(v, this.inspectOpts); + }; + } +}); + +// node_modules/debug/src/index.js +var require_src = __commonJS({ + "node_modules/debug/src/index.js"(exports2, module2) { + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + module2.exports = require_browser(); + } else { + module2.exports = require_node(); + } + } +}); + +// node_modules/follow-redirects/debug.js +var require_debug = __commonJS({ + "node_modules/follow-redirects/debug.js"(exports2, module2) { + var debug; + module2.exports = function() { + if (!debug) { + try { + debug = require_src()("follow-redirects"); + } catch (error) { + } + if (typeof debug !== "function") { + debug = function() { + }; + } + } + debug.apply(null, arguments); + }; + } +}); + +// node_modules/follow-redirects/index.js +var require_follow_redirects = __commonJS({ + "node_modules/follow-redirects/index.js"(exports2, module2) { + var url2 = __require("url"); + var URL2 = url2.URL; + var http3 = __require("http"); + var https2 = __require("https"); + var Writable = __require("stream").Writable; + var assert3 = __require("assert"); + var debug = require_debug(); + (function detectUnsupportedEnvironment() { + var looksLikeNode = typeof process !== "undefined"; + var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; + var looksLikeV8 = isFunction2(Error.captureStackTrace); + if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { + console.warn("The follow-redirects package should be excluded from browser builds."); + } + })(); + var useNativeURL = false; + try { + assert3(new URL2("")); + } catch (error) { + useNativeURL = error.code === "ERR_INVALID_URL"; + } + var preservedUrlFields = [ + "auth", + "host", + "hostname", + "href", + "path", + "pathname", + "port", + "protocol", + "query", + "search", + "hash" + ]; + var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; + var eventHandlers = /* @__PURE__ */ Object.create(null); + events.forEach(function(event) { + eventHandlers[event] = function(arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; + }); + var InvalidUrlError = createErrorType( + "ERR_INVALID_URL", + "Invalid URL", + TypeError + ); + var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "Redirected request failed" + ); + var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded", + RedirectionError + ); + var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" + ); + var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" + ); + var destroy = Writable.prototype.destroy || noop2; + function RedirectableRequest(options, responseCallback) { + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; + if (responseCallback) { + this.on("response", responseCallback); + } + var self2 = this; + this._onNativeResponse = function(response) { + try { + self2._processResponse(response); + } catch (cause) { + self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause })); + } + }; + this._performRequest(); + } + RedirectableRequest.prototype = Object.create(Writable.prototype); + RedirectableRequest.prototype.abort = function() { + destroyRequest(this._currentRequest); + this._currentRequest.abort(); + this.emit("abort"); + }; + RedirectableRequest.prototype.destroy = function(error) { + destroyRequest(this._currentRequest, error); + destroy.call(this, error); + return this; + }; + RedirectableRequest.prototype.write = function(data, encoding, callback) { + if (this._ending) { + throw new WriteAfterEndError(); + } + if (!isString2(data) && !isBuffer2(data)) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (isFunction2(encoding)) { + callback = encoding; + encoding = null; + } + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data, encoding }); + this._currentRequest.write(data, encoding, callback); + } else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } + }; + RedirectableRequest.prototype.end = function(data, encoding, callback) { + if (isFunction2(data)) { + callback = data; + data = encoding = null; + } else if (isFunction2(encoding)) { + callback = encoding; + encoding = null; + } + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } else { + var self2 = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function() { + self2._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; + } + }; + RedirectableRequest.prototype.setHeader = function(name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); + }; + RedirectableRequest.prototype.removeHeader = function(name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); + }; + RedirectableRequest.prototype.setTimeout = function(msecs, callback) { + var self2 = this; + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } + function startTimer(socket) { + if (self2._timeout) { + clearTimeout(self2._timeout); + } + self2._timeout = setTimeout(function() { + self2.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } + function clearTimer() { + if (self2._timeout) { + clearTimeout(self2._timeout); + self2._timeout = null; + } + self2.removeListener("abort", clearTimer); + self2.removeListener("error", clearTimer); + self2.removeListener("response", clearTimer); + self2.removeListener("close", clearTimer); + if (callback) { + self2.removeListener("timeout", callback); + } + if (!self2.socket) { + self2._currentRequest.removeListener("socket", startTimer); + } + } + if (callback) { + this.on("timeout", callback); + } + if (this.socket) { + startTimer(this.socket); + } else { + this._currentRequest.once("socket", startTimer); + } + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + this.on("close", clearTimer); + return this; + }; + [ + "flushHeaders", + "getHeader", + "setNoDelay", + "setSocketKeepAlive" + ].forEach(function(method) { + RedirectableRequest.prototype[method] = function(a, b2) { + return this._currentRequest[method](a, b2); + }; + }); + ["aborted", "connection", "socket"].forEach(function(property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function() { + return this._currentRequest[property]; + } + }); + }); + RedirectableRequest.prototype._sanitizeOptions = function(options) { + if (!options.headers) { + options.headers = {}; + } + if (options.host) { + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } + }; + RedirectableRequest.prototype._performRequest = function() { + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + throw new TypeError("Unsupported protocol " + protocol); + } + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } + var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse); + request._redirectable = this; + for (var event of events) { + request.on(event, eventHandlers[event]); + } + this._currentUrl = /^\//.test(this._options.path) ? url2.format(this._options) : ( + // When making a request to a proxy, […] + // a client MUST send the target URI in absolute-form […]. + this._options.path + ); + if (this._isRedirect) { + var i = 0; + var self2 = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + if (request === self2._currentRequest) { + if (error) { + self2.emit("error", error); + } else if (i < buffers.length) { + var buffer2 = buffers[i++]; + if (!request.finished) { + request.write(buffer2.data, buffer2.encoding, writeNext); + } + } else if (self2._ended) { + request.end(); + } + } + })(); + } + }; + RedirectableRequest.prototype._processResponse = function(response) { + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode + }); + } + var location = response.headers.location; + if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); + this._requestBodyBuffers = []; + return; + } + destroyRequest(this._currentRequest); + response.destroy(); + if (++this._redirectCount > this._options.maxRedirects) { + throw new TooManyRedirectsError(); + } + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + // The Host header was set by nativeProtocol.request + Host: response.req.getHeader("host") + }, this._options.headers); + } + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); + var currentUrlParts = parseUrl(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url2.format(Object.assign(currentUrlParts, { host: currentHost })); + var redirectUrl = resolveUrl(location, currentUrl); + debug("redirecting to", redirectUrl.href); + this._isRedirect = true; + spreadUrlObject(redirectUrl, this._options); + if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) { + removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); + } + if (isFunction2(beforeRedirect)) { + var responseDetails = { + headers: response.headers, + statusCode + }; + var requestDetails = { + url: currentUrl, + method, + headers: requestHeaders + }; + beforeRedirect(this._options, responseDetails, requestDetails); + this._sanitizeOptions(this._options); + } + this._performRequest(); + }; + function wrap(protocols) { + var exports3 = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024 + }; + var nativeProtocols = {}; + Object.keys(protocols).forEach(function(scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports3[scheme] = Object.create(nativeProtocol); + function request(input, options, callback) { + if (isURL(input)) { + input = spreadUrlObject(input); + } else if (isString2(input)) { + input = spreadUrlObject(parseUrl(input)); + } else { + callback = options; + options = validateUrl(input); + input = { protocol }; + } + if (isFunction2(options)) { + callback = options; + options = null; + } + options = Object.assign({ + maxRedirects: exports3.maxRedirects, + maxBodyLength: exports3.maxBodyLength + }, input, options); + options.nativeProtocols = nativeProtocols; + if (!isString2(options.host) && !isString2(options.hostname)) { + options.hostname = "::1"; + } + assert3.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true } + }); + }); + return exports3; + } + function noop2() { + } + function parseUrl(input) { + var parsed; + if (useNativeURL) { + parsed = new URL2(input); + } else { + parsed = validateUrl(url2.parse(input)); + if (!isString2(parsed.protocol)) { + throw new InvalidUrlError({ input }); + } + } + return parsed; + } + function resolveUrl(relative, base) { + return useNativeURL ? new URL2(relative, base) : parseUrl(url2.resolve(base, relative)); + } + function validateUrl(input) { + if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { + throw new InvalidUrlError({ input: input.href || input }); + } + if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { + throw new InvalidUrlError({ input: input.href || input }); + } + return input; + } + function spreadUrlObject(urlObject, target) { + var spread3 = target || {}; + for (var key of preservedUrlFields) { + spread3[key] = urlObject[key]; + } + if (spread3.hostname.startsWith("[")) { + spread3.hostname = spread3.hostname.slice(1, -1); + } + if (spread3.port !== "") { + spread3.port = Number(spread3.port); + } + spread3.path = spread3.search ? spread3.pathname + spread3.search : spread3.pathname; + return spread3; + } + function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } + } + return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim(); + } + function createErrorType(code, message, baseClass) { + function CustomError(properties) { + if (isFunction2(Error.captureStackTrace)) { + Error.captureStackTrace(this, this.constructor); + } + Object.assign(this, properties || {}); + this.code = code; + this.message = this.cause ? message + ": " + this.cause.message : message; + } + CustomError.prototype = new (baseClass || Error)(); + Object.defineProperties(CustomError.prototype, { + constructor: { + value: CustomError, + enumerable: false + }, + name: { + value: "Error [" + code + "]", + enumerable: false + } + }); + return CustomError; + } + function destroyRequest(request, error) { + for (var event of events) { + request.removeListener(event, eventHandlers[event]); + } + request.on("error", noop2); + request.destroy(error); + } + function isSubdomain(subdomain, domain) { + assert3(isString2(subdomain) && isString2(domain)); + var dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); + } + function isString2(value) { + return typeof value === "string" || value instanceof String; + } + function isFunction2(value) { + return typeof value === "function"; + } + function isBuffer2(value) { + return typeof value === "object" && "length" in value; + } + function isURL(value) { + return URL2 && value instanceof URL2; + } + module2.exports = wrap({ http: http3, https: https2 }); + module2.exports.wrap = wrap; + } +}); + +// node_modules/logform/format.js +var require_format = __commonJS({ + "node_modules/logform/format.js"(exports2, module2) { + "use strict"; + var InvalidFormatError = class _InvalidFormatError extends Error { + constructor(formatFn) { + super(`Format functions must be synchronous taking a two arguments: (info, opts) +Found: ${formatFn.toString().split("\n")[0]} +`); + Error.captureStackTrace(this, _InvalidFormatError); + } + }; + module2.exports = (formatFn) => { + if (formatFn.length > 2) { + throw new InvalidFormatError(formatFn); + } + function Format(options = {}) { + this.options = options; + } + Format.prototype.transform = formatFn; + function createFormatWrap(opts) { + return new Format(opts); + } + createFormatWrap.Format = Format; + return createFormatWrap; + }; + } +}); + +// node_modules/@colors/colors/lib/styles.js +var require_styles = __commonJS({ + "node_modules/@colors/colors/lib/styles.js"(exports2, module2) { + var styles = {}; + module2["exports"] = styles; + var codes = { + reset: [0, 0], + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 39], + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + bgGray: [100, 49], + bgGrey: [100, 49], + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 49], + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49] + }; + Object.keys(codes).forEach(function(key) { + var val = codes[key]; + var style = styles[key] = []; + style.open = "\x1B[" + val[0] + "m"; + style.close = "\x1B[" + val[1] + "m"; + }); + } +}); + +// node_modules/@colors/colors/lib/system/has-flag.js +var require_has_flag2 = __commonJS({ + "node_modules/@colors/colors/lib/system/has-flag.js"(exports2, module2) { + "use strict"; + module2.exports = function(flag, argv) { + argv = argv || process.argv || []; + var terminatorPos = argv.indexOf("--"); + var prefix = /^-{1,2}/.test(flag) ? "" : "--"; + var pos = argv.indexOf(prefix + flag); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + }; + } +}); + +// node_modules/@colors/colors/lib/system/supports-colors.js +var require_supports_colors = __commonJS({ + "node_modules/@colors/colors/lib/system/supports-colors.js"(exports2, module2) { + "use strict"; + var os2 = __require("os"); + var hasFlag = require_has_flag2(); + var env = process.env; + var forceColor = void 0; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false")) { + forceColor = false; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + forceColor = true; + } + if ("FORCE_COLOR" in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; + } + function translateLevel(level) { + if (level === 0) { + return false; + } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + function supportsColor(stream4) { + if (forceColor === false) { + return 0; + } + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; + } + if (hasFlag("color=256")) { + return 2; + } + if (stream4 && !stream4.isTTY && forceColor !== true) { + return 0; + } + var min = forceColor ? 1 : 0; + if (process.platform === "win32") { + var osRelease = os2.release().split("."); + if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign2) { + return sign2 in env; + }) || env.CI_NAME === "codeship") { + return 1; + } + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if ("TERM_PROGRAM" in env) { + var version4 = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version4 >= 3 ? 3 : 2; + case "Hyper": + return 3; + case "Apple_Terminal": + return 2; + } + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + if (env.TERM === "dumb") { + return min; + } + return min; + } + function getSupportLevel(stream4) { + var level = supportsColor(stream4); + return translateLevel(level); + } + module2.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) + }; + } +}); + +// node_modules/@colors/colors/lib/custom/trap.js +var require_trap = __commonJS({ + "node_modules/@colors/colors/lib/custom/trap.js"(exports2, module2) { + module2["exports"] = function runTheTrap(text, options) { + var result = ""; + text = text || "Run the trap, drop the bass"; + text = text.split(""); + var trap = { + a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"], + b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"], + c: ["\xA9", "\u023B", "\u03FE"], + d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"], + e: [ + "\xCB", + "\u0115", + "\u018E", + "\u0258", + "\u03A3", + "\u03BE", + "\u04BC", + "\u0A6C" + ], + f: ["\u04FA"], + g: ["\u0262"], + h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"], + i: ["\u0F0F"], + j: ["\u0134"], + k: ["\u0138", "\u04A0", "\u04C3", "\u051E"], + l: ["\u0139"], + m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"], + n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"], + o: [ + "\xD8", + "\xF5", + "\xF8", + "\u01FE", + "\u0298", + "\u047A", + "\u05DD", + "\u06DD", + "\u0E4F" + ], + p: ["\u01F7", "\u048E"], + q: ["\u09CD"], + r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"], + s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"], + t: ["\u0141", "\u0166", "\u0373"], + u: ["\u01B1", "\u054D"], + v: ["\u05D8"], + w: ["\u0428", "\u0460", "\u047C", "\u0D70"], + x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"], + y: ["\xA5", "\u04B0", "\u04CB"], + z: ["\u01B5", "\u0240"] + }; + text.forEach(function(c) { + c = c.toLowerCase(); + var chars = trap[c] || [" "]; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap[c] !== "undefined") { + result += trap[c][rand]; + } else { + result += c; + } + }); + return result; + }; + } +}); + +// node_modules/@colors/colors/lib/custom/zalgo.js +var require_zalgo = __commonJS({ + "node_modules/@colors/colors/lib/custom/zalgo.js"(exports2, module2) { + module2["exports"] = function zalgo(text, options) { + text = text || " he is here "; + var soul = { + "up": [ + "\u030D", + "\u030E", + "\u0304", + "\u0305", + "\u033F", + "\u0311", + "\u0306", + "\u0310", + "\u0352", + "\u0357", + "\u0351", + "\u0307", + "\u0308", + "\u030A", + "\u0342", + "\u0313", + "\u0308", + "\u034A", + "\u034B", + "\u034C", + "\u0303", + "\u0302", + "\u030C", + "\u0350", + "\u0300", + "\u0301", + "\u030B", + "\u030F", + "\u0312", + "\u0313", + "\u0314", + "\u033D", + "\u0309", + "\u0363", + "\u0364", + "\u0365", + "\u0366", + "\u0367", + "\u0368", + "\u0369", + "\u036A", + "\u036B", + "\u036C", + "\u036D", + "\u036E", + "\u036F", + "\u033E", + "\u035B", + "\u0346", + "\u031A" + ], + "down": [ + "\u0316", + "\u0317", + "\u0318", + "\u0319", + "\u031C", + "\u031D", + "\u031E", + "\u031F", + "\u0320", + "\u0324", + "\u0325", + "\u0326", + "\u0329", + "\u032A", + "\u032B", + "\u032C", + "\u032D", + "\u032E", + "\u032F", + "\u0330", + "\u0331", + "\u0332", + "\u0333", + "\u0339", + "\u033A", + "\u033B", + "\u033C", + "\u0345", + "\u0347", + "\u0348", + "\u0349", + "\u034D", + "\u034E", + "\u0353", + "\u0354", + "\u0355", + "\u0356", + "\u0359", + "\u035A", + "\u0323" + ], + "mid": [ + "\u0315", + "\u031B", + "\u0300", + "\u0301", + "\u0358", + "\u0321", + "\u0322", + "\u0327", + "\u0328", + "\u0334", + "\u0335", + "\u0336", + "\u035C", + "\u035D", + "\u035E", + "\u035F", + "\u0360", + "\u0362", + "\u0338", + "\u0337", + "\u0361", + " \u0489" + ] + }; + var all3 = [].concat(soul.up, soul.down, soul.mid); + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } + function isChar(character) { + var bool = false; + all3.filter(function(i) { + bool = i === character; + }); + return bool; + } + function heComes(text2, options2) { + var result = ""; + var counts; + var l; + options2 = options2 || {}; + options2["up"] = typeof options2["up"] !== "undefined" ? options2["up"] : true; + options2["mid"] = typeof options2["mid"] !== "undefined" ? options2["mid"] : true; + options2["down"] = typeof options2["down"] !== "undefined" ? options2["down"] : true; + options2["size"] = typeof options2["size"] !== "undefined" ? options2["size"] : "maxi"; + text2 = text2.split(""); + for (l in text2) { + if (isChar(l)) { + continue; + } + result = result + text2[l]; + counts = { "up": 0, "down": 0, "mid": 0 }; + switch (options2.size) { + case "mini": + counts.up = randomNumber(8); + counts.mid = randomNumber(2); + counts.down = randomNumber(8); + break; + case "maxi": + counts.up = randomNumber(16) + 3; + counts.mid = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } + var arr = ["up", "mid", "down"]; + for (var d in arr) { + var index2 = arr[d]; + for (var i = 0; i <= counts[index2]; i++) { + if (options2[index2]) { + result = result + soul[index2][randomNumber(soul[index2].length)]; + } + } + } + } + return result; + } + return heComes(text, options); + }; + } +}); + +// node_modules/@colors/colors/lib/maps/america.js +var require_america = __commonJS({ + "node_modules/@colors/colors/lib/maps/america.js"(exports2, module2) { + module2["exports"] = function(colors) { + return function(letter, i, exploded) { + if (letter === " ") return letter; + switch (i % 3) { + case 0: + return colors.red(letter); + case 1: + return colors.white(letter); + case 2: + return colors.blue(letter); + } + }; + }; + } +}); + +// node_modules/@colors/colors/lib/maps/zebra.js +var require_zebra = __commonJS({ + "node_modules/@colors/colors/lib/maps/zebra.js"(exports2, module2) { + module2["exports"] = function(colors) { + return function(letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); + }; + }; + } +}); + +// node_modules/@colors/colors/lib/maps/rainbow.js +var require_rainbow = __commonJS({ + "node_modules/@colors/colors/lib/maps/rainbow.js"(exports2, module2) { + module2["exports"] = function(colors) { + var rainbowColors = ["red", "yellow", "green", "blue", "magenta"]; + return function(letter, i, exploded) { + if (letter === " ") { + return letter; + } else { + return colors[rainbowColors[i++ % rainbowColors.length]](letter); + } + }; + }; + } +}); + +// node_modules/@colors/colors/lib/maps/random.js +var require_random = __commonJS({ + "node_modules/@colors/colors/lib/maps/random.js"(exports2, module2) { + module2["exports"] = function(colors) { + var available = [ + "underline", + "inverse", + "grey", + "yellow", + "red", + "green", + "blue", + "white", + "cyan", + "magenta", + "brightYellow", + "brightRed", + "brightGreen", + "brightBlue", + "brightWhite", + "brightCyan", + "brightMagenta" + ]; + return function(letter, i, exploded) { + return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 2))]](letter); + }; + }; + } +}); + +// node_modules/@colors/colors/lib/colors.js +var require_colors = __commonJS({ + "node_modules/@colors/colors/lib/colors.js"(exports2, module2) { + var colors = {}; + module2["exports"] = colors; + colors.themes = {}; + var util3 = __require("util"); + var ansiStyles = colors.styles = require_styles(); + var defineProps = Object.defineProperties; + var newLineRegex = new RegExp(/[\r\n]+/g); + colors.supportsColor = require_supports_colors().supportsColor; + if (typeof colors.enabled === "undefined") { + colors.enabled = colors.supportsColor() !== false; + } + colors.enable = function() { + colors.enabled = true; + }; + colors.disable = function() { + colors.enabled = false; + }; + colors.stripColors = colors.strip = function(str) { + return ("" + str).replace(/\x1B\[\d+m/g, ""); + }; + var stylize = colors.stylize = function stylize2(str, style) { + if (!colors.enabled) { + return str + ""; + } + var styleMap = ansiStyles[style]; + if (!styleMap && style in colors) { + return colors[style](str); + } + return styleMap.open + str + styleMap.close; + }; + var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + var escapeStringRegexp = function(str) { + if (typeof str !== "string") { + throw new TypeError("Expected a string"); + } + return str.replace(matchOperatorsRe, "\\$&"); + }; + function build(_styles) { + var builder = function builder2() { + return applyStyle.apply(builder2, arguments); + }; + builder._styles = _styles; + builder.__proto__ = proto; + return builder; + } + var styles = function() { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function(key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), "g"); + ret[key] = { + get: function() { + return build(this._styles.concat(key)); + } + }; + }); + return ret; + }(); + var proto = defineProps(function colors2() { + }, styles); + function applyStyle() { + var args = Array.prototype.slice.call(arguments); + var str = args.map(function(arg) { + if (arg != null && arg.constructor === String) { + return arg; + } else { + return util3.inspect(arg); + } + }).join(" "); + if (!colors.enabled || !str) { + return str; + } + var newLinesPresent = str.indexOf("\n") != -1; + var nestedStyles = this._styles; + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + if (newLinesPresent) { + str = str.replace(newLineRegex, function(match) { + return code.close + match + code.open; + }); + } + } + return str; + } + colors.setTheme = function(theme) { + if (typeof theme === "string") { + console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));"); + return; + } + for (var style in theme) { + (function(style2) { + colors[style2] = function(str) { + if (typeof theme[style2] === "object") { + var out = str; + for (var i in theme[style2]) { + out = colors[theme[style2][i]](out); + } + return out; + } + return colors[theme[style2]](str); + }; + })(style); + } + }; + function init() { + var ret = {}; + Object.keys(styles).forEach(function(name) { + ret[name] = { + get: function() { + return build([name]); + } + }; + }); + return ret; + } + var sequencer = function sequencer2(map2, str) { + var exploded = str.split(""); + exploded = exploded.map(map2); + return exploded.join(""); + }; + colors.trap = require_trap(); + colors.zalgo = require_zalgo(); + colors.maps = {}; + colors.maps.america = require_america()(colors); + colors.maps.zebra = require_zebra()(colors); + colors.maps.rainbow = require_rainbow()(colors); + colors.maps.random = require_random()(colors); + for (map in colors.maps) { + (function(map2) { + colors[map2] = function(str) { + return sequencer(colors.maps[map2], str); + }; + })(map); + } + var map; + defineProps(colors, init()); + } +}); + +// node_modules/@colors/colors/safe.js +var require_safe = __commonJS({ + "node_modules/@colors/colors/safe.js"(exports2, module2) { + var colors = require_colors(); + module2["exports"] = colors; + } +}); + +// node_modules/triple-beam/config/cli.js +var require_cli = __commonJS({ + "node_modules/triple-beam/config/cli.js"(exports2) { + "use strict"; + exports2.levels = { + error: 0, + warn: 1, + help: 2, + data: 3, + info: 4, + debug: 5, + prompt: 6, + verbose: 7, + input: 8, + silly: 9 + }; + exports2.colors = { + error: "red", + warn: "yellow", + help: "cyan", + data: "grey", + info: "green", + debug: "blue", + prompt: "grey", + verbose: "cyan", + input: "grey", + silly: "magenta" + }; + } +}); + +// node_modules/triple-beam/config/npm.js +var require_npm = __commonJS({ + "node_modules/triple-beam/config/npm.js"(exports2) { + "use strict"; + exports2.levels = { + error: 0, + warn: 1, + info: 2, + http: 3, + verbose: 4, + debug: 5, + silly: 6 + }; + exports2.colors = { + error: "red", + warn: "yellow", + info: "green", + http: "green", + verbose: "cyan", + debug: "blue", + silly: "magenta" + }; + } +}); + +// node_modules/triple-beam/config/syslog.js +var require_syslog = __commonJS({ + "node_modules/triple-beam/config/syslog.js"(exports2) { + "use strict"; + exports2.levels = { + emerg: 0, + alert: 1, + crit: 2, + error: 3, + warning: 4, + notice: 5, + info: 6, + debug: 7 + }; + exports2.colors = { + emerg: "red", + alert: "yellow", + crit: "red", + error: "red", + warning: "red", + notice: "yellow", + info: "green", + debug: "blue" + }; + } +}); + +// node_modules/triple-beam/config/index.js +var require_config = __commonJS({ + "node_modules/triple-beam/config/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "cli", { + value: require_cli() + }); + Object.defineProperty(exports2, "npm", { + value: require_npm() + }); + Object.defineProperty(exports2, "syslog", { + value: require_syslog() + }); + } +}); + +// node_modules/triple-beam/index.js +var require_triple_beam = __commonJS({ + "node_modules/triple-beam/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "LEVEL", { + value: Symbol.for("level") + }); + Object.defineProperty(exports2, "MESSAGE", { + value: Symbol.for("message") + }); + Object.defineProperty(exports2, "SPLAT", { + value: Symbol.for("splat") + }); + Object.defineProperty(exports2, "configs", { + value: require_config() + }); + } +}); + +// node_modules/logform/colorize.js +var require_colorize = __commonJS({ + "node_modules/logform/colorize.js"(exports2, module2) { + "use strict"; + var colors = require_safe(); + var { LEVEL, MESSAGE } = require_triple_beam(); + colors.enabled = true; + var hasSpace = /\s+/; + var Colorizer = class _Colorizer { + constructor(opts = {}) { + if (opts.colors) { + this.addColors(opts.colors); + } + this.options = opts; + } + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + static addColors(clrs) { + const nextColors = Object.keys(clrs).reduce((acc, level) => { + acc[level] = hasSpace.test(clrs[level]) ? clrs[level].split(hasSpace) : clrs[level]; + return acc; + }, {}); + _Colorizer.allColors = Object.assign({}, _Colorizer.allColors || {}, nextColors); + return _Colorizer.allColors; + } + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + addColors(clrs) { + return _Colorizer.addColors(clrs); + } + /* + * function colorize (lookup, level, message) + * Performs multi-step colorization using @colors/colors/safe + */ + colorize(lookup, level, message) { + if (typeof message === "undefined") { + message = level; + } + if (!Array.isArray(_Colorizer.allColors[lookup])) { + return colors[_Colorizer.allColors[lookup]](message); + } + for (let i = 0, len = _Colorizer.allColors[lookup].length; i < len; i++) { + message = colors[_Colorizer.allColors[lookup][i]](message); + } + return message; + } + /* + * function transform (info, opts) + * Attempts to colorize the { level, message } of the given + * `logform` info object. + */ + transform(info, opts) { + if (opts.all && typeof info[MESSAGE] === "string") { + info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]); + } + if (opts.level || opts.all || !opts.message) { + info.level = this.colorize(info[LEVEL], info.level); + } + if (opts.all || opts.message) { + info.message = this.colorize(info[LEVEL], info.level, info.message); + } + return info; + } + }; + module2.exports = (opts) => new Colorizer(opts); + module2.exports.Colorizer = module2.exports.Format = Colorizer; + } +}); + +// node_modules/logform/levels.js +var require_levels = __commonJS({ + "node_modules/logform/levels.js"(exports2, module2) { + "use strict"; + var { Colorizer } = require_colorize(); + module2.exports = (config3) => { + Colorizer.addColors(config3.colors || config3); + return config3; + }; + } +}); + +// node_modules/logform/align.js +var require_align = __commonJS({ + "node_modules/logform/align.js"(exports2, module2) { + "use strict"; + var format = require_format(); + module2.exports = format((info) => { + info.message = ` ${info.message}`; + return info; + }); + } +}); + +// node_modules/logform/errors.js +var require_errors = __commonJS({ + "node_modules/logform/errors.js"(exports2, module2) { + "use strict"; + var format = require_format(); + var { LEVEL, MESSAGE } = require_triple_beam(); + module2.exports = format((einfo, { stack, cause }) => { + if (einfo instanceof Error) { + const info = Object.assign({}, einfo, { + level: einfo.level, + [LEVEL]: einfo[LEVEL] || einfo.level, + message: einfo.message, + [MESSAGE]: einfo[MESSAGE] || einfo.message + }); + if (stack) info.stack = einfo.stack; + if (cause) info.cause = einfo.cause; + return info; + } + if (!(einfo.message instanceof Error)) return einfo; + const err = einfo.message; + Object.assign(einfo, err); + einfo.message = err.message; + einfo[MESSAGE] = err.message; + if (stack) einfo.stack = err.stack; + if (cause) einfo.cause = err.cause; + return einfo; + }); + } +}); + +// node_modules/logform/pad-levels.js +var require_pad_levels = __commonJS({ + "node_modules/logform/pad-levels.js"(exports2, module2) { + "use strict"; + var { configs, LEVEL, MESSAGE } = require_triple_beam(); + var Padder = class _Padder { + constructor(opts = { levels: configs.npm.levels }) { + this.paddings = _Padder.paddingForLevels(opts.levels, opts.filler); + this.options = opts; + } + /** + * Returns the maximum length of keys in the specified `levels` Object. + * @param {Object} levels Set of all levels to calculate longest level against. + * @returns {Number} Maximum length of the longest level string. + */ + static getLongestLevel(levels) { + const lvls = Object.keys(levels).map((level) => level.length); + return Math.max(...lvls); + } + /** + * Returns the padding for the specified `level` assuming that the + * maximum length of all levels it's associated with is `maxLength`. + * @param {String} level Level to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @param {Number} maxLength Length of the longest level + * @returns {String} Padding string for the `level` + */ + static paddingForLevel(level, filler, maxLength) { + const targetLen = maxLength + 1 - level.length; + const rep = Math.floor(targetLen / filler.length); + const padding = `${filler}${filler.repeat(rep)}`; + return padding.slice(0, targetLen); + } + /** + * Returns an object with the string paddings for the given `levels` + * using the specified `filler`. + * @param {Object} levels Set of all levels to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @returns {Object} Mapping of level to desired padding. + */ + static paddingForLevels(levels, filler = " ") { + const maxLength = _Padder.getLongestLevel(levels); + return Object.keys(levels).reduce((acc, level) => { + acc[level] = _Padder.paddingForLevel(level, filler, maxLength); + return acc; + }, {}); + } + /** + * Prepends the padding onto the `message` based on the `LEVEL` of + * the `info`. This is based on the behavior of `winston@2` which also + * prepended the level onto the message. + * + * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201 + * + * @param {Info} info Logform info object + * @param {Object} opts Options passed along to this instance. + * @returns {Info} Modified logform info object. + */ + transform(info, opts) { + info.message = `${this.paddings[info[LEVEL]]}${info.message}`; + if (info[MESSAGE]) { + info[MESSAGE] = `${this.paddings[info[LEVEL]]}${info[MESSAGE]}`; + } + return info; + } + }; + module2.exports = (opts) => new Padder(opts); + module2.exports.Padder = module2.exports.Format = Padder; + } +}); + +// node_modules/logform/cli.js +var require_cli2 = __commonJS({ + "node_modules/logform/cli.js"(exports2, module2) { + "use strict"; + var { Colorizer } = require_colorize(); + var { Padder } = require_pad_levels(); + var { configs, MESSAGE } = require_triple_beam(); + var CliFormat = class { + constructor(opts = {}) { + if (!opts.levels) { + opts.levels = configs.cli.levels; + } + this.colorizer = new Colorizer(opts); + this.padder = new Padder(opts); + this.options = opts; + } + /* + * function transform (info, opts) + * Attempts to both: + * 1. Pad the { level } + * 2. Colorize the { level, message } + * of the given `logform` info object depending on the `opts`. + */ + transform(info, opts) { + this.colorizer.transform( + this.padder.transform(info, opts), + opts + ); + info[MESSAGE] = `${info.level}:${info.message}`; + return info; + } + }; + module2.exports = (opts) => new CliFormat(opts); + module2.exports.Format = CliFormat; + } +}); + +// node_modules/logform/combine.js +var require_combine = __commonJS({ + "node_modules/logform/combine.js"(exports2, module2) { + "use strict"; + var format = require_format(); + function cascade(formats) { + if (!formats.every(isValidFormat)) { + return; + } + return (info) => { + let obj = info; + for (let i = 0; i < formats.length; i++) { + obj = formats[i].transform(obj, formats[i].options); + if (!obj) { + return false; + } + } + return obj; + }; + } + function isValidFormat(fmt) { + if (typeof fmt.transform !== "function") { + throw new Error([ + "No transform function found on format. Did you create a format instance?", + "const myFormat = format(formatFn);", + "const instance = myFormat();" + ].join("\n")); + } + return true; + } + module2.exports = (...formats) => { + const combinedFormat = format(cascade(formats)); + const instance = combinedFormat(); + instance.Format = combinedFormat.Format; + return instance; + }; + module2.exports.cascade = cascade; + } +}); + +// node_modules/safe-stable-stringify/index.js +var require_safe_stable_stringify = __commonJS({ + "node_modules/safe-stable-stringify/index.js"(exports2, module2) { + "use strict"; + var { hasOwnProperty: hasOwnProperty2 } = Object.prototype; + var stringify3 = configure(); + stringify3.configure = configure; + stringify3.stringify = stringify3; + stringify3.default = stringify3; + exports2.stringify = stringify3; + exports2.configure = configure; + module2.exports = stringify3; + var strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/; + function strEscape(str) { + if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) { + return `"${str}"`; + } + return JSON.stringify(str); + } + function sort(array, comparator) { + if (array.length > 200 || comparator) { + return array.sort(comparator); + } + for (let i = 1; i < array.length; i++) { + const currentValue = array[i]; + let position = i; + while (position !== 0 && array[position - 1] > currentValue) { + array[position] = array[position - 1]; + position--; + } + array[position] = currentValue; + } + return array; + } + var typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor( + Object.getPrototypeOf( + Object.getPrototypeOf( + new Int8Array() + ) + ), + Symbol.toStringTag + ).get; + function isTypedArrayWithEntries(value) { + return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0; + } + function stringifyTypedArray(array, separator, maximumBreadth) { + if (array.length < maximumBreadth) { + maximumBreadth = array.length; + } + const whitespace = separator === "," ? "" : " "; + let res = `"0":${whitespace}${array[0]}`; + for (let i = 1; i < maximumBreadth; i++) { + res += `${separator}"${i}":${whitespace}${array[i]}`; + } + return res; + } + function getCircularValueOption(options) { + if (hasOwnProperty2.call(options, "circularValue")) { + const circularValue = options.circularValue; + if (typeof circularValue === "string") { + return `"${circularValue}"`; + } + if (circularValue == null) { + return circularValue; + } + if (circularValue === Error || circularValue === TypeError) { + return { + toString() { + throw new TypeError("Converting circular structure to JSON"); + } + }; + } + throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined'); + } + return '"[Circular]"'; + } + function getDeterministicOption(options) { + let value; + if (hasOwnProperty2.call(options, "deterministic")) { + value = options.deterministic; + if (typeof value !== "boolean" && typeof value !== "function") { + throw new TypeError('The "deterministic" argument must be of type boolean or comparator function'); + } + } + return value === void 0 ? true : value; + } + function getBooleanOption(options, key) { + let value; + if (hasOwnProperty2.call(options, key)) { + value = options[key]; + if (typeof value !== "boolean") { + throw new TypeError(`The "${key}" argument must be of type boolean`); + } + } + return value === void 0 ? true : value; + } + function getPositiveIntegerOption(options, key) { + let value; + if (hasOwnProperty2.call(options, key)) { + value = options[key]; + if (typeof value !== "number") { + throw new TypeError(`The "${key}" argument must be of type number`); + } + if (!Number.isInteger(value)) { + throw new TypeError(`The "${key}" argument must be an integer`); + } + if (value < 1) { + throw new RangeError(`The "${key}" argument must be >= 1`); + } + } + return value === void 0 ? Infinity : value; + } + function getItemCount(number) { + if (number === 1) { + return "1 item"; + } + return `${number} items`; + } + function getUniqueReplacerSet(replacerArray) { + const replacerSet = /* @__PURE__ */ new Set(); + for (const value of replacerArray) { + if (typeof value === "string" || typeof value === "number") { + replacerSet.add(String(value)); + } + } + return replacerSet; + } + function getStrictOption(options) { + if (hasOwnProperty2.call(options, "strict")) { + const value = options.strict; + if (typeof value !== "boolean") { + throw new TypeError('The "strict" argument must be of type boolean'); + } + if (value) { + return (value2) => { + let message = `Object can not safely be stringified. Received type ${typeof value2}`; + if (typeof value2 !== "function") message += ` (${value2.toString()})`; + throw new Error(message); + }; + } + } + } + function configure(options) { + options = { ...options }; + const fail = getStrictOption(options); + if (fail) { + if (options.bigint === void 0) { + options.bigint = false; + } + if (!("circularValue" in options)) { + options.circularValue = Error; + } + } + const circularValue = getCircularValueOption(options); + const bigint = getBooleanOption(options, "bigint"); + const deterministic = getDeterministicOption(options); + const comparator = typeof deterministic === "function" ? deterministic : void 0; + const maximumDepth = getPositiveIntegerOption(options, "maximumDepth"); + const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth"); + function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) { + let value = parent[key]; + if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { + value = value.toJSON(key); + } + value = replacer.call(parent, key, value); + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + let res = ""; + let join2 = ","; + const originalIndentation = indentation; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + if (spacer !== "") { + indentation += spacer; + res += ` +${indentation}`; + join2 = `, +${indentation}`; + } + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += join2; + } + const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; + } + if (spacer !== "") { + res += ` +${originalIndentation}`; + } + stack.pop(); + return `[${res}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + let whitespace = ""; + let separator = ""; + if (spacer !== "") { + indentation += spacer; + join2 = `, +${indentation}`; + whitespace = " "; + } + const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (deterministic && !isTypedArrayWithEntries(value)) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key2 = keys[i]; + const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; + separator = join2; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`; + separator = join2; + } + if (spacer !== "" && separator.length > 1) { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) { + if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { + value = value.toJSON(key); + } + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + const originalIndentation = indentation; + let res = ""; + let join2 = ","; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + if (spacer !== "") { + indentation += spacer; + res += ` +${indentation}`; + join2 = `, +${indentation}`; + } + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += join2; + } + const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; + } + if (spacer !== "") { + res += ` +${originalIndentation}`; + } + stack.pop(); + return `[${res}]`; + } + stack.push(value); + let whitespace = ""; + if (spacer !== "") { + indentation += spacer; + join2 = `, +${indentation}`; + whitespace = " "; + } + let separator = ""; + for (const key2 of replacer) { + const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; + separator = join2; + } + } + if (spacer !== "" && separator.length > 1) { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringifyIndent(key, value, stack, spacer, indentation) { + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (typeof value.toJSON === "function") { + value = value.toJSON(key); + if (typeof value !== "object") { + return stringifyIndent(key, value, stack, spacer, indentation); + } + if (value === null) { + return "null"; + } + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + const originalIndentation = indentation; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + indentation += spacer; + let res2 = ` +${indentation}`; + const join3 = `, +${indentation}`; + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation); + res2 += tmp2 !== void 0 ? tmp2 : "null"; + res2 += join3; + } + const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation); + res2 += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res2 += `${join3}"... ${getItemCount(removedKeys)} not stringified"`; + } + res2 += ` +${originalIndentation}`; + stack.pop(); + return `[${res2}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + indentation += spacer; + const join2 = `, +${indentation}`; + let res = ""; + let separator = ""; + let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (isTypedArrayWithEntries(value)) { + res += stringifyTypedArray(value, join2, maximumBreadth); + keys = keys.slice(value.length); + maximumPropertiesToStringify -= value.length; + separator = join2; + } + if (deterministic) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key2 = keys[i]; + const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}: ${tmp}`; + separator = join2; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`; + separator = join2; + } + if (separator !== "") { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringifySimple(key, value, stack) { + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (typeof value.toJSON === "function") { + value = value.toJSON(key); + if (typeof value !== "object") { + return stringifySimple(key, value, stack); + } + if (value === null) { + return "null"; + } + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + let res = ""; + const hasLength = value.length !== void 0; + if (hasLength && Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifySimple(String(i), value[i], stack); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += ","; + } + const tmp = stringifySimple(String(i), value[i], stack); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `,"... ${getItemCount(removedKeys)} not stringified"`; + } + stack.pop(); + return `[${res}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + let separator = ""; + let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (hasLength && isTypedArrayWithEntries(value)) { + res += stringifyTypedArray(value, ",", maximumBreadth); + keys = keys.slice(value.length); + maximumPropertiesToStringify -= value.length; + separator = ","; + } + if (deterministic) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key2 = keys[i]; + const tmp = stringifySimple(key2, value[key2], stack); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${tmp}`; + separator = ","; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringify4(value, replacer, space) { + if (arguments.length > 1) { + let spacer = ""; + if (typeof space === "number") { + spacer = " ".repeat(Math.min(space, 10)); + } else if (typeof space === "string") { + spacer = space.slice(0, 10); + } + if (replacer != null) { + if (typeof replacer === "function") { + return stringifyFnReplacer("", { "": value }, [], replacer, spacer, ""); + } + if (Array.isArray(replacer)) { + return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, ""); + } + } + if (spacer.length !== 0) { + return stringifyIndent("", value, [], spacer, ""); + } + } + return stringifySimple("", value, []); + } + return stringify4; + } + } +}); + +// node_modules/logform/json.js +var require_json = __commonJS({ + "node_modules/logform/json.js"(exports2, module2) { + "use strict"; + var format = require_format(); + var { MESSAGE } = require_triple_beam(); + var stringify3 = require_safe_stable_stringify(); + function replacer(key, value) { + if (typeof value === "bigint") + return value.toString(); + return value; + } + module2.exports = format((info, opts) => { + const jsonStringify = stringify3.configure(opts); + info[MESSAGE] = jsonStringify(info, opts.replacer || replacer, opts.space); + return info; + }); + } +}); + +// node_modules/logform/label.js +var require_label = __commonJS({ + "node_modules/logform/label.js"(exports2, module2) { + "use strict"; + var format = require_format(); + module2.exports = format((info, opts) => { + if (opts.message) { + info.message = `[${opts.label}] ${info.message}`; + return info; + } + info.label = opts.label; + return info; + }); + } +}); + +// node_modules/logform/logstash.js +var require_logstash = __commonJS({ + "node_modules/logform/logstash.js"(exports2, module2) { + "use strict"; + var format = require_format(); + var { MESSAGE } = require_triple_beam(); + var jsonStringify = require_safe_stable_stringify(); + module2.exports = format((info) => { + const logstash = {}; + if (info.message) { + logstash["@message"] = info.message; + delete info.message; + } + if (info.timestamp) { + logstash["@timestamp"] = info.timestamp; + delete info.timestamp; + } + logstash["@fields"] = info; + info[MESSAGE] = jsonStringify(logstash); + return info; + }); + } +}); + +// node_modules/logform/metadata.js +var require_metadata = __commonJS({ + "node_modules/logform/metadata.js"(exports2, module2) { + "use strict"; + var format = require_format(); + function fillExcept(info, fillExceptKeys, metadataKey) { + const savedKeys = fillExceptKeys.reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + const metadata = Object.keys(info).reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + Object.assign(info, savedKeys, { + [metadataKey]: metadata + }); + return info; + } + function fillWith(info, fillWithKeys, metadataKey) { + info[metadataKey] = fillWithKeys.reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + return info; + } + module2.exports = format((info, opts = {}) => { + let metadataKey = "metadata"; + if (opts.key) { + metadataKey = opts.key; + } + let fillExceptKeys = []; + if (!opts.fillExcept && !opts.fillWith) { + fillExceptKeys.push("level"); + fillExceptKeys.push("message"); + } + if (opts.fillExcept) { + fillExceptKeys = opts.fillExcept; + } + if (fillExceptKeys.length > 0) { + return fillExcept(info, fillExceptKeys, metadataKey); + } + if (opts.fillWith) { + return fillWith(info, opts.fillWith, metadataKey); + } + return info; + }); + } +}); + +// node_modules/logform/ms.js +var require_ms2 = __commonJS({ + "node_modules/logform/ms.js"(exports2, module2) { + "use strict"; + var format = require_format(); + var ms = require_ms(); + module2.exports = format((info) => { + const curr = +/* @__PURE__ */ new Date(); + exports2.diff = curr - (exports2.prevTime || curr); + exports2.prevTime = curr; + info.ms = `+${ms(exports2.diff)}`; + return info; + }); + } +}); + +// node_modules/logform/pretty-print.js +var require_pretty_print = __commonJS({ + "node_modules/logform/pretty-print.js"(exports2, module2) { + "use strict"; + var inspect = __require("util").inspect; + var format = require_format(); + var { LEVEL, MESSAGE, SPLAT } = require_triple_beam(); + module2.exports = format((info, opts = {}) => { + const stripped = Object.assign({}, info); + delete stripped[LEVEL]; + delete stripped[MESSAGE]; + delete stripped[SPLAT]; + info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize); + return info; + }); + } +}); + +// node_modules/logform/printf.js +var require_printf = __commonJS({ + "node_modules/logform/printf.js"(exports2, module2) { + "use strict"; + var { MESSAGE } = require_triple_beam(); + var Printf = class { + constructor(templateFn) { + this.template = templateFn; + } + transform(info) { + info[MESSAGE] = this.template(info); + return info; + } + }; + module2.exports = (opts) => new Printf(opts); + module2.exports.Printf = module2.exports.Format = Printf; + } +}); + +// node_modules/logform/simple.js +var require_simple = __commonJS({ + "node_modules/logform/simple.js"(exports2, module2) { + "use strict"; + var format = require_format(); + var { MESSAGE } = require_triple_beam(); + var jsonStringify = require_safe_stable_stringify(); + module2.exports = format((info) => { + const stringifiedRest = jsonStringify(Object.assign({}, info, { + level: void 0, + message: void 0, + splat: void 0 + })); + const padding = info.padding && info.padding[info.level] || ""; + if (stringifiedRest !== "{}") { + info[MESSAGE] = `${info.level}:${padding} ${info.message} ${stringifiedRest}`; + } else { + info[MESSAGE] = `${info.level}:${padding} ${info.message}`; + } + return info; + }); + } +}); + +// node_modules/logform/splat.js +var require_splat = __commonJS({ + "node_modules/logform/splat.js"(exports2, module2) { + "use strict"; + var util3 = __require("util"); + var { SPLAT } = require_triple_beam(); + var formatRegExp = /%[scdjifoO%]/g; + var escapedPercent = /%%/g; + var Splatter = class { + constructor(opts) { + this.options = opts; + } + /** + * Check to see if tokens <= splat.length, assign { splat, meta } into the + * `info` accordingly, and write to this instance. + * + * @param {Info} info Logform info message. + * @param {String[]} tokens Set of string interpolation tokens. + * @returns {Info} Modified info message + * @private + */ + _splat(info, tokens) { + const msg = info.message; + const splat = info[SPLAT] || info.splat || []; + const percents = msg.match(escapedPercent); + const escapes = percents && percents.length || 0; + const expectedSplat = tokens.length - escapes; + const extraSplat = expectedSplat - splat.length; + const metas = extraSplat < 0 ? splat.splice(extraSplat, -1 * extraSplat) : []; + const metalen = metas.length; + if (metalen) { + for (let i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + info.message = util3.format(msg, ...splat); + return info; + } + /** + * Transforms the `info` message by using `util.format` to complete + * any `info.message` provided it has string interpolation tokens. + * If no tokens exist then `info` is immutable. + * + * @param {Info} info Logform info message. + * @param {Object} opts Options for this instance. + * @returns {Info} Modified info message + */ + transform(info) { + const msg = info.message; + const splat = info[SPLAT] || info.splat; + if (!splat || !splat.length) { + return info; + } + const tokens = msg && msg.match && msg.match(formatRegExp); + if (!tokens && (splat || splat.length)) { + const metas = splat.length > 1 ? splat.splice(0) : splat; + const metalen = metas.length; + if (metalen) { + for (let i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + return info; + } + if (tokens) { + return this._splat(info, tokens); + } + return info; + } + }; + module2.exports = (opts) => new Splatter(opts); + } +}); + +// node_modules/fecha/lib/fecha.umd.js +var require_fecha_umd = __commonJS({ + "node_modules/fecha/lib/fecha.umd.js"(exports2, module2) { + (function(global2, factory) { + typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : factory(global2.fecha = {}); + })(exports2, function(exports3) { + "use strict"; + var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; + var twoDigitsOptional = "\\d\\d?"; + var twoDigits = "\\d\\d"; + var threeDigits = "\\d{3}"; + var fourDigits = "\\d{4}"; + var word = "[^\\s]+"; + var literal = /\[([^]*?)\]/gm; + function shorten2(arr, sLen) { + var newArr = []; + for (var i = 0, len = arr.length; i < len; i++) { + newArr.push(arr[i].substr(0, sLen)); + } + return newArr; + } + var monthUpdate = function(arrName) { + return function(v, i18n) { + var lowerCaseArr = i18n[arrName].map(function(v2) { + return v2.toLowerCase(); + }); + var index2 = lowerCaseArr.indexOf(v.toLowerCase()); + if (index2 > -1) { + return index2; + } + return null; + }; + }; + function assign(origObj) { + var args = []; + for (var _i2 = 1; _i2 < arguments.length; _i2++) { + args[_i2 - 1] = arguments[_i2]; + } + for (var _a2 = 0, args_1 = args; _a2 < args_1.length; _a2++) { + var obj = args_1[_a2]; + for (var key in obj) { + origObj[key] = obj[key]; + } + } + return origObj; + } + var dayNames = [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ]; + var monthNames = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ]; + var monthNamesShort = shorten2(monthNames, 3); + var dayNamesShort = shorten2(dayNames, 3); + var defaultI18n = { + dayNamesShort, + dayNames, + monthNamesShort, + monthNames, + amPm: ["am", "pm"], + DoFn: function(dayOfMonth) { + return dayOfMonth + ["th", "st", "nd", "rd"][dayOfMonth % 10 > 3 ? 0 : (dayOfMonth - dayOfMonth % 10 !== 10 ? 1 : 0) * dayOfMonth % 10]; + } + }; + var globalI18n = assign({}, defaultI18n); + var setGlobalDateI18n = function(i18n) { + return globalI18n = assign(globalI18n, i18n); + }; + var regexEscape = function(str) { + return str.replace(/[|\\{()[^$+*?.-]/g, "\\$&"); + }; + var pad4 = function(val, len) { + if (len === void 0) { + len = 2; + } + val = String(val); + while (val.length < len) { + val = "0" + val; + } + return val; + }; + var formatFlags = { + D: function(dateObj) { + return String(dateObj.getDate()); + }, + DD: function(dateObj) { + return pad4(dateObj.getDate()); + }, + Do: function(dateObj, i18n) { + return i18n.DoFn(dateObj.getDate()); + }, + d: function(dateObj) { + return String(dateObj.getDay()); + }, + dd: function(dateObj) { + return pad4(dateObj.getDay()); + }, + ddd: function(dateObj, i18n) { + return i18n.dayNamesShort[dateObj.getDay()]; + }, + dddd: function(dateObj, i18n) { + return i18n.dayNames[dateObj.getDay()]; + }, + M: function(dateObj) { + return String(dateObj.getMonth() + 1); + }, + MM: function(dateObj) { + return pad4(dateObj.getMonth() + 1); + }, + MMM: function(dateObj, i18n) { + return i18n.monthNamesShort[dateObj.getMonth()]; + }, + MMMM: function(dateObj, i18n) { + return i18n.monthNames[dateObj.getMonth()]; + }, + YY: function(dateObj) { + return pad4(String(dateObj.getFullYear()), 4).substr(2); + }, + YYYY: function(dateObj) { + return pad4(dateObj.getFullYear(), 4); + }, + h: function(dateObj) { + return String(dateObj.getHours() % 12 || 12); + }, + hh: function(dateObj) { + return pad4(dateObj.getHours() % 12 || 12); + }, + H: function(dateObj) { + return String(dateObj.getHours()); + }, + HH: function(dateObj) { + return pad4(dateObj.getHours()); + }, + m: function(dateObj) { + return String(dateObj.getMinutes()); + }, + mm: function(dateObj) { + return pad4(dateObj.getMinutes()); + }, + s: function(dateObj) { + return String(dateObj.getSeconds()); + }, + ss: function(dateObj) { + return pad4(dateObj.getSeconds()); + }, + S: function(dateObj) { + return String(Math.round(dateObj.getMilliseconds() / 100)); + }, + SS: function(dateObj) { + return pad4(Math.round(dateObj.getMilliseconds() / 10), 2); + }, + SSS: function(dateObj) { + return pad4(dateObj.getMilliseconds(), 3); + }, + a: function(dateObj, i18n) { + return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1]; + }, + A: function(dateObj, i18n) { + return dateObj.getHours() < 12 ? i18n.amPm[0].toUpperCase() : i18n.amPm[1].toUpperCase(); + }, + ZZ: function(dateObj) { + var offset = dateObj.getTimezoneOffset(); + return (offset > 0 ? "-" : "+") + pad4(Math.floor(Math.abs(offset) / 60) * 100 + Math.abs(offset) % 60, 4); + }, + Z: function(dateObj) { + var offset = dateObj.getTimezoneOffset(); + return (offset > 0 ? "-" : "+") + pad4(Math.floor(Math.abs(offset) / 60), 2) + ":" + pad4(Math.abs(offset) % 60, 2); + } + }; + var monthParse = function(v) { + return +v - 1; + }; + var emptyDigits = [null, twoDigitsOptional]; + var emptyWord = [null, word]; + var amPm = [ + "isPm", + word, + function(v, i18n) { + var val = v.toLowerCase(); + if (val === i18n.amPm[0]) { + return 0; + } else if (val === i18n.amPm[1]) { + return 1; + } + return null; + } + ]; + var timezoneOffset = [ + "timezoneOffset", + "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?", + function(v) { + var parts = (v + "").match(/([+-]|\d\d)/gi); + if (parts) { + var minutes = +parts[1] * 60 + parseInt(parts[2], 10); + return parts[0] === "+" ? minutes : -minutes; + } + return 0; + } + ]; + var parseFlags = { + D: ["day", twoDigitsOptional], + DD: ["day", twoDigits], + Do: ["day", twoDigitsOptional + word, function(v) { + return parseInt(v, 10); + }], + M: ["month", twoDigitsOptional, monthParse], + MM: ["month", twoDigits, monthParse], + YY: [ + "year", + twoDigits, + function(v) { + var now = /* @__PURE__ */ new Date(); + var cent = +("" + now.getFullYear()).substr(0, 2); + return +("" + (+v > 68 ? cent - 1 : cent) + v); + } + ], + h: ["hour", twoDigitsOptional, void 0, "isPm"], + hh: ["hour", twoDigits, void 0, "isPm"], + H: ["hour", twoDigitsOptional], + HH: ["hour", twoDigits], + m: ["minute", twoDigitsOptional], + mm: ["minute", twoDigits], + s: ["second", twoDigitsOptional], + ss: ["second", twoDigits], + YYYY: ["year", fourDigits], + S: ["millisecond", "\\d", function(v) { + return +v * 100; + }], + SS: ["millisecond", twoDigits, function(v) { + return +v * 10; + }], + SSS: ["millisecond", threeDigits], + d: emptyDigits, + dd: emptyDigits, + ddd: emptyWord, + dddd: emptyWord, + MMM: ["month", word, monthUpdate("monthNamesShort")], + MMMM: ["month", word, monthUpdate("monthNames")], + a: amPm, + A: amPm, + ZZ: timezoneOffset, + Z: timezoneOffset + }; + var globalMasks = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + isoDate: "YYYY-MM-DD", + isoDateTime: "YYYY-MM-DDTHH:mm:ssZ", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" + }; + var setGlobalDateMasks = function(masks) { + return assign(globalMasks, masks); + }; + var format = function(dateObj, mask, i18n) { + if (mask === void 0) { + mask = globalMasks["default"]; + } + if (i18n === void 0) { + i18n = {}; + } + if (typeof dateObj === "number") { + dateObj = new Date(dateObj); + } + if (Object.prototype.toString.call(dateObj) !== "[object Date]" || isNaN(dateObj.getTime())) { + throw new Error("Invalid Date pass to format"); + } + mask = globalMasks[mask] || mask; + var literals = []; + mask = mask.replace(literal, function($0, $1) { + literals.push($1); + return "@@@"; + }); + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + mask = mask.replace(token, function($0) { + return formatFlags[$0](dateObj, combinedI18nSettings); + }); + return mask.replace(/@@@/g, function() { + return literals.shift(); + }); + }; + function parse(dateStr, format2, i18n) { + if (i18n === void 0) { + i18n = {}; + } + if (typeof format2 !== "string") { + throw new Error("Invalid format in fecha parse"); + } + format2 = globalMasks[format2] || format2; + if (dateStr.length > 1e3) { + return null; + } + var today = /* @__PURE__ */ new Date(); + var dateInfo = { + year: today.getFullYear(), + month: 0, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + isPm: null, + timezoneOffset: null + }; + var parseInfo = []; + var literals = []; + var newFormat = format2.replace(literal, function($0, $1) { + literals.push(regexEscape($1)); + return "@@@"; + }); + var specifiedFields = {}; + var requiredFields = {}; + newFormat = regexEscape(newFormat).replace(token, function($0) { + var info = parseFlags[$0]; + var field2 = info[0], regex = info[1], requiredField = info[3]; + if (specifiedFields[field2]) { + throw new Error("Invalid format. " + field2 + " specified twice in format"); + } + specifiedFields[field2] = true; + if (requiredField) { + requiredFields[requiredField] = true; + } + parseInfo.push(info); + return "(" + regex + ")"; + }); + Object.keys(requiredFields).forEach(function(field2) { + if (!specifiedFields[field2]) { + throw new Error("Invalid format. " + field2 + " is required in specified format"); + } + }); + newFormat = newFormat.replace(/@@@/g, function() { + return literals.shift(); + }); + var matches = dateStr.match(new RegExp(newFormat, "i")); + if (!matches) { + return null; + } + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + for (var i = 1; i < matches.length; i++) { + var _a2 = parseInfo[i - 1], field = _a2[0], parser = _a2[2]; + var value = parser ? parser(matches[i], combinedI18nSettings) : +matches[i]; + if (value == null) { + return null; + } + dateInfo[field] = value; + } + if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) { + dateInfo.hour = +dateInfo.hour + 12; + } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) { + dateInfo.hour = 0; + } + var dateTZ; + if (dateInfo.timezoneOffset == null) { + dateTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond); + var validateFields = [ + ["month", "getMonth"], + ["day", "getDate"], + ["hour", "getHours"], + ["minute", "getMinutes"], + ["second", "getSeconds"] + ]; + for (var i = 0, len = validateFields.length; i < len; i++) { + if (specifiedFields[validateFields[i][0]] && dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]()) { + return null; + } + } + } else { + dateTZ = new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond)); + if (dateInfo.month > 11 || dateInfo.month < 0 || dateInfo.day > 31 || dateInfo.day < 1 || dateInfo.hour > 23 || dateInfo.hour < 0 || dateInfo.minute > 59 || dateInfo.minute < 0 || dateInfo.second > 59 || dateInfo.second < 0) { + return null; + } + } + return dateTZ; + } + var fecha = { + format, + parse, + defaultI18n, + setGlobalDateI18n, + setGlobalDateMasks + }; + exports3.assign = assign; + exports3.default = fecha; + exports3.format = format; + exports3.parse = parse; + exports3.defaultI18n = defaultI18n; + exports3.setGlobalDateI18n = setGlobalDateI18n; + exports3.setGlobalDateMasks = setGlobalDateMasks; + Object.defineProperty(exports3, "__esModule", { value: true }); + }); + } +}); + +// node_modules/logform/timestamp.js +var require_timestamp = __commonJS({ + "node_modules/logform/timestamp.js"(exports2, module2) { + "use strict"; + var fecha = require_fecha_umd(); + var format = require_format(); + module2.exports = format((info, opts = {}) => { + if (opts.format) { + info.timestamp = typeof opts.format === "function" ? opts.format() : fecha.format(/* @__PURE__ */ new Date(), opts.format); + } + if (!info.timestamp) { + info.timestamp = (/* @__PURE__ */ new Date()).toISOString(); + } + if (opts.alias) { + info[opts.alias] = info.timestamp; + } + return info; + }); + } +}); + +// node_modules/logform/uncolorize.js +var require_uncolorize = __commonJS({ + "node_modules/logform/uncolorize.js"(exports2, module2) { + "use strict"; + var colors = require_safe(); + var format = require_format(); + var { MESSAGE } = require_triple_beam(); + module2.exports = format((info, opts) => { + if (opts.level !== false) { + info.level = colors.strip(info.level); + } + if (opts.message !== false) { + info.message = colors.strip(String(info.message)); + } + if (opts.raw !== false && info[MESSAGE]) { + info[MESSAGE] = colors.strip(String(info[MESSAGE])); + } + return info; + }); + } +}); + +// node_modules/logform/index.js +var require_logform = __commonJS({ + "node_modules/logform/index.js"(exports2) { + "use strict"; + var format = exports2.format = require_format(); + exports2.levels = require_levels(); + function exposeFormat(name, requireFormat) { + Object.defineProperty(format, name, { + get() { + return requireFormat(); + }, + configurable: true + }); + } + exposeFormat("align", function() { + return require_align(); + }); + exposeFormat("errors", function() { + return require_errors(); + }); + exposeFormat("cli", function() { + return require_cli2(); + }); + exposeFormat("combine", function() { + return require_combine(); + }); + exposeFormat("colorize", function() { + return require_colorize(); + }); + exposeFormat("json", function() { + return require_json(); + }); + exposeFormat("label", function() { + return require_label(); + }); + exposeFormat("logstash", function() { + return require_logstash(); + }); + exposeFormat("metadata", function() { + return require_metadata(); + }); + exposeFormat("ms", function() { + return require_ms2(); + }); + exposeFormat("padLevels", function() { + return require_pad_levels(); + }); + exposeFormat("prettyPrint", function() { + return require_pretty_print(); + }); + exposeFormat("printf", function() { + return require_printf(); + }); + exposeFormat("simple", function() { + return require_simple(); + }); + exposeFormat("splat", function() { + return require_splat(); + }); + exposeFormat("timestamp", function() { + return require_timestamp(); + }); + exposeFormat("uncolorize", function() { + return require_uncolorize(); + }); + } +}); + +// node_modules/winston/lib/winston/common.js +var require_common2 = __commonJS({ + "node_modules/winston/lib/winston/common.js"(exports2) { + "use strict"; + var { format } = __require("util"); + exports2.warn = { + deprecated(prop) { + return () => { + throw new Error(format("{ %s } was removed in winston@3.0.0.", prop)); + }; + }, + useFormat(prop) { + return () => { + throw new Error([ + format("{ %s } was removed in winston@3.0.0.", prop), + "Use a custom winston.format = winston.format(function) instead." + ].join("\n")); + }; + }, + forFunctions(obj, type, props) { + props.forEach((prop) => { + obj[prop] = exports2.warn[type](prop); + }); + }, + forProperties(obj, type, props) { + props.forEach((prop) => { + const notice = exports2.warn[type](prop); + Object.defineProperty(obj, prop, { + get: notice, + set: notice + }); + }); + } + }; + } +}); + +// node_modules/winston/package.json +var require_package2 = __commonJS({ + "node_modules/winston/package.json"(exports2, module2) { + module2.exports = { + name: "winston", + description: "A logger for just about everything.", + version: "3.17.0", + author: "Charlie Robbins ", + maintainers: [ + "David Hyde " + ], + repository: { + type: "git", + url: "https://github.com/winstonjs/winston.git" + }, + keywords: [ + "winston", + "logger", + "logging", + "logs", + "sysadmin", + "bunyan", + "pino", + "loglevel", + "tools", + "json", + "stream" + ], + dependencies: { + "@dabh/diagnostics": "^2.0.2", + "@colors/colors": "^1.6.0", + async: "^3.2.3", + "is-stream": "^2.0.0", + logform: "^2.7.0", + "one-time": "^1.0.0", + "readable-stream": "^3.4.0", + "safe-stable-stringify": "^2.3.1", + "stack-trace": "0.0.x", + "triple-beam": "^1.3.0", + "winston-transport": "^4.9.0" + }, + devDependencies: { + "@babel/cli": "^7.23.9", + "@babel/core": "^7.24.0", + "@babel/preset-env": "^7.24.0", + "@dabh/eslint-config-populist": "^4.4.0", + "@types/node": "^20.11.24", + "abstract-winston-transport": "^0.5.1", + assume: "^2.2.0", + "cross-spawn-async": "^2.2.5", + eslint: "^8.57.0", + hock: "^1.4.1", + mocha: "^10.3.0", + nyc: "^17.1.0", + rimraf: "5.0.1", + split2: "^4.1.0", + "std-mocks": "^2.0.0", + through2: "^4.0.2", + "winston-compat": "^0.1.5" + }, + main: "./lib/winston.js", + browser: "./dist/winston", + types: "./index.d.ts", + scripts: { + lint: "eslint lib/*.js lib/winston/*.js lib/winston/**/*.js --resolve-plugins-relative-to ./node_modules/@dabh/eslint-config-populist", + test: "rimraf test/fixtures/logs/* && mocha", + "test:coverage": "nyc npm run test:unit", + "test:unit": "mocha test/unit", + "test:integration": "mocha test/integration", + build: "rimraf dist && babel lib -d dist", + prepublishOnly: "npm run build" + }, + engines: { + node: ">= 12.0.0" + }, + license: "MIT" + }; + } +}); + +// node_modules/util-deprecate/node.js +var require_node2 = __commonJS({ + "node_modules/util-deprecate/node.js"(exports2, module2) { + module2.exports = __require("util").deprecate; + } +}); + +// node_modules/readable-stream/lib/internal/streams/stream.js +var require_stream = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/stream.js"(exports2, module2) { + module2.exports = __require("stream"); + } +}); + +// node_modules/readable-stream/lib/internal/streams/destroy.js +var require_destroy = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports2, module2) { + "use strict"; + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + if (this._readableState) { + this._readableState.destroyed = true; + } + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function(err2) { + if (!cb && err2) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err2); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; + } + function emitErrorAndCloseNT(self2, err) { + emitErrorNT(self2, err); + emitCloseNT(self2); + } + function emitCloseNT(self2) { + if (self2._writableState && !self2._writableState.emitClose) return; + if (self2._readableState && !self2._readableState.emitClose) return; + self2.emit("close"); + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + function emitErrorNT(self2, err) { + self2.emit("error", err); + } + function errorOrDestroy(stream4, err) { + var rState = stream4._readableState; + var wState = stream4._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream4.destroy(err); + else stream4.emit("error", err); + } + module2.exports = { + destroy, + undestroy, + errorOrDestroy + }; + } +}); + +// node_modules/readable-stream/errors.js +var require_errors2 = __commonJS({ + "node_modules/readable-stream/errors.js"(exports2, module2) { + "use strict"; + var codes = {}; + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + function getMessage(arg1, arg2, arg3) { + if (typeof message === "string") { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + class NodeError extends Base { + constructor(arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; + } + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(", ")}, or ` + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } + } + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } + function endsWith2(str, search, this_len) { + if (this_len === void 0 || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + function includes(str, search, start) { + if (typeof start !== "number") { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + createErrorType("ERR_INVALID_OPT_VALUE", function(name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { + let determiner; + if (typeof expected === "string" && startsWith(expected, "not ")) { + determiner = "must not be"; + expected = expected.replace(/^not /, ""); + } else { + determiner = "must be"; + } + let msg; + if (endsWith2(name, " argument")) { + msg = `The ${name} ${determiner} ${oneOf(expected, "type")}`; + } else { + const type = includes(name, ".") ? "property" : "argument"; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, "type")}`; + } + msg += `. Received type ${typeof actual}`; + return msg; + }, TypeError); + createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); + createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name) { + return "The " + name + " method is not implemented"; + }); + createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); + createErrorType("ERR_STREAM_DESTROYED", function(name) { + return "Cannot call " + name + " after a stream was destroyed"; + }); + createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); + createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); + createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { + return "Unknown encoding: " + arg; + }, TypeError); + createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); + module2.exports.codes = codes; + } +}); + +// node_modules/readable-stream/lib/internal/streams/state.js +var require_state2 = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { + "use strict"; + var ERR_INVALID_OPT_VALUE = require_errors2().codes.ERR_INVALID_OPT_VALUE; + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } + function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : "highWaterMark"; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + return state.objectMode ? 16 : 16 * 1024; + } + module2.exports = { + getHighWaterMark + }; + } +}); + +// node_modules/inherits/inherits_browser.js +var require_inherits_browser = __commonJS({ + "node_modules/inherits/inherits_browser.js"(exports2, module2) { + if (typeof Object.create === "function") { + module2.exports = function inherits2(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + module2.exports = function inherits2(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; + } + } +}); + +// node_modules/inherits/inherits.js +var require_inherits = __commonJS({ + "node_modules/inherits/inherits.js"(exports2, module2) { + try { + util3 = __require("util"); + if (typeof util3.inherits !== "function") throw ""; + module2.exports = util3.inherits; + } catch (e) { + module2.exports = require_inherits_browser(); + } + var util3; + } +}); + +// node_modules/readable-stream/lib/internal/streams/buffer_list.js +var require_buffer_list = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports2, module2) { + "use strict"; + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; + } + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; + } + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var _require = __require("buffer"); + var Buffer2 = _require.Buffer; + var _require2 = __require("util"); + var inspect = _require2.inspect; + var custom = inspect && inspect.custom || "inspect"; + function copyBuffer(src, target, offset) { + Buffer2.prototype.copy.call(src, target, offset); + } + module2.exports = /* @__PURE__ */ function() { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join2(s) { + if (this.length === 0) return ""; + var p = this.head; + var ret = "" + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat3(n) { + if (this.length === 0) return Buffer2.alloc(0); + var ret = Buffer2.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + ret = this.shift(); + } else { + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str; + else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer2.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; + }(); + } +}); + +// node_modules/safe-buffer/index.js +var require_safe_buffer = __commonJS({ + "node_modules/safe-buffer/index.js"(exports2, module2) { + var buffer2 = __require("buffer"); + var Buffer2 = buffer2.Buffer; + function copyProps(src, dst) { + for (var key in src) { + dst[key] = src[key]; + } + } + if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + module2.exports = buffer2; + } else { + copyProps(buffer2, exports2); + exports2.Buffer = SafeBuffer; + } + function SafeBuffer(arg, encodingOrOffset, length) { + return Buffer2(arg, encodingOrOffset, length); + } + SafeBuffer.prototype = Object.create(Buffer2.prototype); + copyProps(Buffer2, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + throw new TypeError("Argument must not be a number"); + } + return Buffer2(arg, encodingOrOffset, length); + }; + SafeBuffer.alloc = function(size5, fill, encoding) { + if (typeof size5 !== "number") { + throw new TypeError("Argument must be a number"); + } + var buf = Buffer2(size5); + if (fill !== void 0) { + if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf; + }; + SafeBuffer.allocUnsafe = function(size5) { + if (typeof size5 !== "number") { + throw new TypeError("Argument must be a number"); + } + return Buffer2(size5); + }; + SafeBuffer.allocUnsafeSlow = function(size5) { + if (typeof size5 !== "number") { + throw new TypeError("Argument must be a number"); + } + return buffer2.SlowBuffer(size5); + }; + } +}); + +// node_modules/string_decoder/lib/string_decoder.js +var require_string_decoder = __commonJS({ + "node_modules/string_decoder/lib/string_decoder.js"(exports2) { + "use strict"; + var Buffer2 = require_safe_buffer().Buffer; + var isEncoding = Buffer2.isEncoding || function(encoding) { + encoding = "" + encoding; + switch (encoding && encoding.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; + function _normalizeEncoding(enc) { + if (!enc) return "utf8"; + var retried; + while (true) { + switch (enc) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return enc; + default: + if (retried) return; + enc = ("" + enc).toLowerCase(); + retried = true; + } + } + } + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc); + return nenc || enc; + } + exports2.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case "utf16le": + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case "utf8": + this.fillLast = utf8FillLast; + nb = 4; + break; + case "base64": + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer2.allocUnsafe(nb); + } + StringDecoder.prototype.write = function(buf) { + if (buf.length === 0) return ""; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === void 0) return ""; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ""; + }; + StringDecoder.prototype.end = utf8End; + StringDecoder.prototype.text = utf8Text; + StringDecoder.prototype.fillLast = function(buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; + }; + function utf8CheckByte(byte) { + if (byte <= 127) return 0; + else if (byte >> 5 === 6) return 2; + else if (byte >> 4 === 14) return 3; + else if (byte >> 3 === 30) return 4; + return byte >> 6 === 2 ? -1 : -2; + } + function utf8CheckIncomplete(self2, buf, i) { + var j2 = buf.length - 1; + if (j2 < i) return 0; + var nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 1; + return nb; + } + if (--j2 < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 2; + return nb; + } + if (--j2 < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0; + else self2.lastNeed = nb - 3; + } + return nb; + } + return 0; + } + function utf8CheckExtraBytes(self2, buf, p) { + if ((buf[0] & 192) !== 128) { + self2.lastNeed = 0; + return "\uFFFD"; + } + if (self2.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 192) !== 128) { + self2.lastNeed = 1; + return "\uFFFD"; + } + if (self2.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 192) !== 128) { + self2.lastNeed = 2; + return "\uFFFD"; + } + } + } + } + function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== void 0) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; + } + function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString("utf8", i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString("utf8", i, end); + } + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) return r + "\uFFFD"; + return r; + } + function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString("utf16le", i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 55296 && c <= 56319) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString("utf16le", i, buf.length - 1); + } + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString("utf16le", 0, end); + } + return r; + } + function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString("base64", i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString("base64", i, buf.length - n); + } + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); + return r; + } + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ""; + } + } +}); + +// node_modules/readable-stream/lib/internal/streams/end-of-stream.js +var require_end_of_stream = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports2, module2) { + "use strict"; + var ERR_STREAM_PREMATURE_CLOSE = require_errors2().codes.ERR_STREAM_PREMATURE_CLOSE; + function once(callback) { + var called = false; + return function() { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; + } + function noop2() { + } + function isRequest2(stream4) { + return stream4.setHeader && typeof stream4.abort === "function"; + } + function eos(stream4, opts, callback) { + if (typeof opts === "function") return eos(stream4, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop2); + var readable = opts.readable || opts.readable !== false && stream4.readable; + var writable = opts.writable || opts.writable !== false && stream4.writable; + var onlegacyfinish = function onlegacyfinish2() { + if (!stream4.writable) onfinish(); + }; + var writableEnded = stream4._writableState && stream4._writableState.finished; + var onfinish = function onfinish2() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream4); + }; + var readableEnded = stream4._readableState && stream4._readableState.endEmitted; + var onend = function onend2() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream4); + }; + var onerror = function onerror2(err) { + callback.call(stream4, err); + }; + var onclose = function onclose2() { + var err; + if (readable && !readableEnded) { + if (!stream4._readableState || !stream4._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream4, err); + } + if (writable && !writableEnded) { + if (!stream4._writableState || !stream4._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream4, err); + } + }; + var onrequest = function onrequest2() { + stream4.req.on("finish", onfinish); + }; + if (isRequest2(stream4)) { + stream4.on("complete", onfinish); + stream4.on("abort", onclose); + if (stream4.req) onrequest(); + else stream4.on("request", onrequest); + } else if (writable && !stream4._writableState) { + stream4.on("end", onlegacyfinish); + stream4.on("close", onlegacyfinish); + } + stream4.on("end", onend); + stream4.on("finish", onfinish); + if (opts.error !== false) stream4.on("error", onerror); + stream4.on("close", onclose); + return function() { + stream4.removeListener("complete", onfinish); + stream4.removeListener("abort", onclose); + stream4.removeListener("request", onrequest); + if (stream4.req) stream4.req.removeListener("finish", onfinish); + stream4.removeListener("end", onlegacyfinish); + stream4.removeListener("close", onlegacyfinish); + stream4.removeListener("finish", onfinish); + stream4.removeListener("end", onend); + stream4.removeListener("error", onerror); + stream4.removeListener("close", onclose); + }; + } + module2.exports = eos; + } +}); + +// node_modules/readable-stream/lib/internal/streams/async_iterator.js +var require_async_iterator = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/async_iterator.js"(exports2, module2) { + "use strict"; + var _Object$setPrototypeO; + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var finished = require_end_of_stream(); + var kLastResolve = Symbol("lastResolve"); + var kLastReject = Symbol("lastReject"); + var kError = Symbol("error"); + var kEnded = Symbol("ended"); + var kLastPromise = Symbol("lastPromise"); + var kHandlePromise = Symbol("handlePromise"); + var kStream = Symbol("stream"); + function createIterResult(value, done) { + return { + value, + done + }; + } + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } + } + function onReadable(iter) { + process.nextTick(readAndResolve, iter); + } + function wrapForNext(lastPromise, iter) { + return function(resolve, reject) { + lastPromise.then(function() { + if (iter[kEnded]) { + resolve(createIterResult(void 0, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + var AsyncIteratorPrototype = Object.getPrototypeOf(function() { + }); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(void 0, true)); + } + if (this[kStream].destroyed) { + return new Promise(function(resolve, reject) { + process.nextTick(function() { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(void 0, true)); + } + }); + }); + } + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + return new Promise(function(resolve, reject) { + _this2[kStream].destroy(null, function(err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(void 0, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream4) { + var _Object$create; + var iterator2 = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream4, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream4._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator2[kStream].read(); + if (data) { + iterator2[kLastPromise] = null; + iterator2[kLastResolve] = null; + iterator2[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator2[kLastResolve] = resolve; + iterator2[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator2[kLastPromise] = null; + finished(stream4, function(err) { + if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + var reject = iterator2[kLastReject]; + if (reject !== null) { + iterator2[kLastPromise] = null; + iterator2[kLastResolve] = null; + iterator2[kLastReject] = null; + reject(err); + } + iterator2[kError] = err; + return; + } + var resolve = iterator2[kLastResolve]; + if (resolve !== null) { + iterator2[kLastPromise] = null; + iterator2[kLastResolve] = null; + iterator2[kLastReject] = null; + resolve(createIterResult(void 0, true)); + } + iterator2[kEnded] = true; + }); + stream4.on("readable", onReadable.bind(null, iterator2)); + return iterator2; + }; + module2.exports = createReadableStreamAsyncIterator; + } +}); + +// node_modules/readable-stream/lib/internal/streams/from.js +var require_from = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/from.js"(exports2, module2) { + "use strict"; + function asyncGeneratorStep(gen3, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen3[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + function _asyncToGenerator(fn2) { + return function() { + var self2 = this, args = arguments; + return new Promise(function(resolve, reject) { + var gen3 = fn2.apply(self2, args); + function _next(value) { + asyncGeneratorStep(gen3, resolve, reject, _next, _throw, "next", value); + } + function _throw(err) { + asyncGeneratorStep(gen3, resolve, reject, _next, _throw, "throw", err); + } + _next(void 0); + }); + }; + } + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; + } + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; + } + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var ERR_INVALID_ARG_TYPE = require_errors2().codes.ERR_INVALID_ARG_TYPE; + function from5(Readable2, iterable, opts) { + var iterator2; + if (iterable && typeof iterable.next === "function") { + iterator2 = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator2 = iterable[Symbol.asyncIterator](); + else if (iterable && iterable[Symbol.iterator]) iterator2 = iterable[Symbol.iterator](); + else throw new ERR_INVALID_ARG_TYPE("iterable", ["Iterable"], iterable); + var readable = new Readable2(_objectSpread({ + objectMode: true + }, opts)); + var reading = false; + readable._read = function() { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator2.next(), value = _yield$iterator$next.value, done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; + } + module2.exports = from5; + } +}); + +// node_modules/readable-stream/lib/_stream_readable.js +var require_stream_readable = __commonJS({ + "node_modules/readable-stream/lib/_stream_readable.js"(exports2, module2) { + "use strict"; + module2.exports = Readable2; + var Duplex; + Readable2.ReadableState = ReadableState; + var EE = __require("events").EventEmitter; + var EElistenerCount = function EElistenerCount2(emitter, type) { + return emitter.listeners(type).length; + }; + var Stream = require_stream(); + var Buffer2 = __require("buffer").Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var debugUtil = __require("util"); + var debug; + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog("stream"); + } else { + debug = function debug2() { + }; + } + var BufferList = require_buffer_list(); + var destroyImpl = require_destroy(); + var _require = require_state2(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors2().codes; + var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; + var ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + var StringDecoder; + var createReadableStreamAsyncIterator; + var from5; + require_inherits()(Readable2, Stream); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + function prependListener(emitter, event, fn2) { + if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn2); + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn2); + else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn2); + else emitter._events[event] = [fn2, emitter._events[event]]; + } + function ReadableState(options, stream4, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream4 instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + this.sync = true; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + this.emitClose = options.emitClose !== false; + this.autoDestroy = !!options.autoDestroy; + this.destroyed = false; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.awaitDrain = 0; + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable2(options) { + Duplex = Duplex || require_stream_duplex(); + if (!(this instanceof Readable2)) return new Readable2(options); + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + this.readable = true; + if (options) { + if (typeof options.read === "function") this._read = options.read; + if (typeof options.destroy === "function") this._destroy = options.destroy; + } + Stream.call(this); + } + Object.defineProperty(Readable2.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === void 0) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; + } + }); + Readable2.prototype.destroy = destroyImpl.destroy; + Readable2.prototype._undestroy = destroyImpl.undestroy; + Readable2.prototype._destroy = function(err, cb) { + cb(err); + }; + Readable2.prototype.push = function(chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === "string") { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer2.from(chunk, encoding); + encoding = ""; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; + Readable2.prototype.unshift = function(chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream4, chunk, encoding, addToFront, skipChunkCheck) { + debug("readableAddChunk", chunk); + var state = stream4._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream4, state); + } else { + var er2; + if (!skipChunkCheck) er2 = chunkInvalid(state, chunk); + if (er2) { + errorOrDestroy(stream4, er2); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream4, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else addChunk(stream4, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream4, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream4, state, chunk, false); + else maybeReadMore(stream4, state); + } else { + addChunk(stream4, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream4, state); + } + } + return !state.ended && (state.length < state.highWaterMark || state.length === 0); + } + function addChunk(stream4, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream4.emit("data", chunk); + } else { + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk); + else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream4); + } + maybeReadMore(stream4, state); + } + function chunkInvalid(state, chunk) { + var er2; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { + er2 = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + return er2; + } + Readable2.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Readable2.prototype.setEncoding = function(enc) { + if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + this._readableState.encoding = this._readableState.decoder.encoding; + var p = this._readableState.buffer.head; + var content = ""; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== "") this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; + var MAX_HWM = 1073741824; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + if (state.flowing && state.length) return state.buffer.head.data.length; + else return state.length; + } + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + Readable2.prototype.read = function(n) { + debug("read", n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug("read: emitReadable", state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this); + else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + var doRead = state.needReadable; + debug("need readable", doRead); + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug("length less than watermark", doRead); + } + if (state.ended || state.reading) { + doRead = false; + debug("reading or ended", doRead); + } else if (doRead) { + debug("do read"); + state.reading = true; + state.sync = true; + if (state.length === 0) state.needReadable = true; + this._read(state.highWaterMark); + state.sync = false; + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state); + else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + if (!state.ended) state.needReadable = true; + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit("data", ret); + return ret; + }; + function onEofChunk(stream4, state) { + debug("onEofChunk"); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + emitReadable(stream4); + } else { + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream4); + } + } + } + function emitReadable(stream4) { + var state = stream4._readableState; + debug("emitReadable", state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug("emitReadable", state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream4); + } + } + function emitReadable_(stream4) { + var state = stream4._readableState; + debug("emitReadable_", state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream4.emit("readable"); + state.emittedReadable = false; + } + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream4); + } + function maybeReadMore(stream4, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream4, state); + } + } + function maybeReadMore_(stream4, state) { + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug("maybeReadMore read 0"); + stream4.read(0); + if (len === state.length) + break; + } + state.readingMore = false; + } + Readable2.prototype._read = function(n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); + }; + Readable2.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn); + else src.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable, unpipeInfo) { + debug("onunpipe"); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug("onend"); + dest.end(); + } + var ondrain = pipeOnDrain(src); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src.removeListener("end", onend); + src.removeListener("end", unpipe); + src.removeListener("data", ondata); + cleanedUp = true; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on("data", ondata); + function ondata(chunk) { + debug("ondata"); + var ret = dest.write(chunk); + debug("dest.write", ret); + if (ret === false) { + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug("false write response, pause", state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + function onerror(er2) { + debug("onerror", er2); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er2); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug("unpipe"); + src.unpipe(dest); + } + dest.emit("pipe", src); + if (!state.flowing) { + debug("pipe resume"); + src.resume(); + } + return dest; + }; + function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug("pipeOnDrain", state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, "data")) { + state.flowing = true; + flow(src); + } + }; + } + Readable2.prototype.unpipe = function(dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + if (state.pipesCount === 0) return this; + if (state.pipesCount === 1) { + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit("unpipe", this, unpipeInfo); + return this; + } + if (!dest) { + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit("unpipe", this, { + hasUnpiped: false + }); + return this; + } + var index2 = indexOf(state.pipes, dest); + if (index2 === -1) return this; + state.pipes.splice(index2, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable2.prototype.on = function(ev, fn2) { + var res = Stream.prototype.on.call(this, ev, fn2); + var state = this._readableState; + if (ev === "data") { + state.readableListening = this.listenerCount("readable") > 0; + if (state.flowing !== false) this.resume(); + } else if (ev === "readable") { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug("on readable", state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; + }; + Readable2.prototype.addListener = Readable2.prototype.on; + Readable2.prototype.removeListener = function(ev, fn2) { + var res = Stream.prototype.removeListener.call(this, ev, fn2); + if (ev === "readable") { + process.nextTick(updateReadableListening, this); + } + return res; + }; + Readable2.prototype.removeAllListeners = function(ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === "readable" || ev === void 0) { + process.nextTick(updateReadableListening, this); + } + return res; + }; + function updateReadableListening(self2) { + var state = self2._readableState; + state.readableListening = self2.listenerCount("readable") > 0; + if (state.resumeScheduled && !state.paused) { + state.flowing = true; + } else if (self2.listenerCount("data") > 0) { + self2.resume(); + } + } + function nReadingNextTick(self2) { + debug("readable nexttick read 0"); + self2.read(0); + } + Readable2.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug("resume"); + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; + }; + function resume(stream4, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream4, state); + } + } + function resume_(stream4, state) { + debug("resume", state.reading); + if (!state.reading) { + stream4.read(0); + } + state.resumeScheduled = false; + stream4.emit("resume"); + flow(stream4); + if (state.flowing && !state.reading) stream4.read(0); + } + Readable2.prototype.pause = function() { + debug("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + this._readableState.paused = true; + return this; + }; + function flow(stream4) { + var state = stream4._readableState; + debug("flow", state.flowing); + while (state.flowing && stream4.read() !== null) ; + } + Readable2.prototype.wrap = function(stream4) { + var _this = this; + var state = this._readableState; + var paused = false; + stream4.on("end", function() { + debug("wrapped end"); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream4.on("data", function(chunk) { + debug("wrapped data"); + if (state.decoder) chunk = state.decoder.write(chunk); + if (state.objectMode && (chunk === null || chunk === void 0)) return; + else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream4.pause(); + } + }); + for (var i in stream4) { + if (this[i] === void 0 && typeof stream4[i] === "function") { + this[i] = /* @__PURE__ */ function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream4[method].apply(stream4, arguments); + }; + }(i); + } + } + for (var n = 0; n < kProxyEvents.length; n++) { + stream4.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + this._read = function(n2) { + debug("wrapped _read", n2); + if (paused) { + paused = false; + stream4.resume(); + } + }; + return this; + }; + if (typeof Symbol === "function") { + Readable2.prototype[Symbol.asyncIterator] = function() { + if (createReadableStreamAsyncIterator === void 0) { + createReadableStreamAsyncIterator = require_async_iterator(); + } + return createReadableStreamAsyncIterator(this); + }; + } + Object.defineProperty(Readable2.prototype, "readableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable2.prototype, "readableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable2.prototype, "readableFlowing", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }); + Readable2._fromList = fromList; + Object.defineProperty(Readable2.prototype, "readableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } + }); + function fromList(n, state) { + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift(); + else if (!n || n >= state.length) { + if (state.decoder) ret = state.buffer.join(""); + else if (state.buffer.length === 1) ret = state.buffer.first(); + else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + ret = state.buffer.consume(n, state.decoder); + } + return ret; + } + function endReadable(stream4) { + var state = stream4._readableState; + debug("endReadable", state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream4); + } + } + function endReadableNT(state, stream4) { + debug("endReadableNT", state.endEmitted, state.length); + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream4.readable = false; + stream4.emit("end"); + if (state.autoDestroy) { + var wState = stream4._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream4.destroy(); + } + } + } + } + if (typeof Symbol === "function") { + Readable2.from = function(iterable, opts) { + if (from5 === void 0) { + from5 = require_from(); + } + return from5(Readable2, iterable, opts); + }; + } + function indexOf(xs2, x2) { + for (var i = 0, l = xs2.length; i < l; i++) { + if (xs2[i] === x2) return i; + } + return -1; + } + } +}); + +// node_modules/readable-stream/lib/_stream_duplex.js +var require_stream_duplex = __commonJS({ + "node_modules/readable-stream/lib/_stream_duplex.js"(exports2, module2) { + "use strict"; + var objectKeys = Object.keys || function(obj) { + var keys2 = []; + for (var key in obj) keys2.push(key); + return keys2; + }; + module2.exports = Duplex; + var Readable2 = require_stream_readable(); + var Writable = require_stream_writable(); + require_inherits()(Duplex, Readable2); + { + keys = objectKeys(Writable.prototype); + for (v = 0; v < keys.length; v++) { + method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + var keys; + var method; + var v; + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable2.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once("end", onend); + } + } + } + Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + function onend() { + if (this._writableState.ended) return; + process.nextTick(onEndNT, this); + } + function onEndNT(self2) { + self2.end(); + } + Object.defineProperty(Duplex.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === void 0 || this._writableState === void 0) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + if (this._readableState === void 0 || this._writableState === void 0) { + return; + } + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + } +}); + +// node_modules/readable-stream/lib/_stream_writable.js +var require_stream_writable = __commonJS({ + "node_modules/readable-stream/lib/_stream_writable.js"(exports2, module2) { + "use strict"; + module2.exports = Writable; + function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state); + }; + } + var Duplex; + Writable.WritableState = WritableState; + var internalUtil = { + deprecate: require_node2() + }; + var Stream = require_stream(); + var Buffer2 = __require("buffer").Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = require_destroy(); + var _require = require_state2(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors2().codes; + var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; + var ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + var ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES; + var ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END; + var ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + var errorOrDestroy = destroyImpl.errorOrDestroy; + require_inherits()(Writable, Stream); + function nop() { + } + function WritableState(options, stream4, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream4 instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = function(er2) { + onwrite(stream4, er2); + }; + this.writecb = null; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + this.pendingcb = 0; + this.prefinished = false; + this.errorEmitted = false; + this.emitClose = options.emitClose !== false; + this.autoDestroy = !!options.autoDestroy; + this.bufferedRequestCount = 0; + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") + }); + } catch (_) { + } + })(); + var realHasInstance; + if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance2(object) { + return object instanceof this; + }; + } + function Writable(options) { + Duplex = Duplex || require_stream_duplex(); + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + this.writable = true; + if (options) { + if (typeof options.write === "function") this._write = options.write; + if (typeof options.writev === "function") this._writev = options.writev; + if (typeof options.destroy === "function") this._destroy = options.destroy; + if (typeof options.final === "function") this._final = options.final; + } + Stream.call(this); + } + Writable.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function writeAfterEnd(stream4, cb) { + var er2 = new ERR_STREAM_WRITE_AFTER_END(); + errorOrDestroy(stream4, er2); + process.nextTick(cb, er2); + } + function validChunk(stream4, state, chunk, cb) { + var er2; + if (chunk === null) { + er2 = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== "string" && !state.objectMode) { + er2 = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); + } + if (er2) { + errorOrDestroy(stream4, er2); + process.nextTick(cb, er2); + return false; + } + return true; + } + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer2.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = "buffer"; + else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== "function") cb = nop; + if (state.ending) writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + Writable.prototype.cork = function() { + this._writableState.corked++; + }; + Writable.prototype.uncork = function() { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + if (typeof encoding === "string") encoding = encoding.toLowerCase(); + if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + Object.defineProperty(Writable.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") { + chunk = Buffer2.from(chunk, encoding); + } + return chunk; + } + Object.defineProperty(Writable.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + function writeOrBuffer(stream4, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = "buffer"; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk, + encoding, + isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream4, state, false, len, chunk, encoding, cb); + } + return ret; + } + function doWrite(stream4, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED("write")); + else if (writev) stream4._writev(chunk, state.onwrite); + else stream4._write(chunk, encoding, state.onwrite); + state.sync = false; + } + function onwriteError(stream4, state, sync, er2, cb) { + --state.pendingcb; + if (sync) { + process.nextTick(cb, er2); + process.nextTick(finishMaybe, stream4, state); + stream4._writableState.errorEmitted = true; + errorOrDestroy(stream4, er2); + } else { + cb(er2); + stream4._writableState.errorEmitted = true; + errorOrDestroy(stream4, er2); + finishMaybe(stream4, state); + } + } + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + function onwrite(stream4, er2) { + var state = stream4._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er2) onwriteError(stream4, state, sync, er2, cb); + else { + var finished = needFinish(state) || stream4.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream4, state); + } + if (sync) { + process.nextTick(afterWrite, stream4, state, finished, cb); + } else { + afterWrite(stream4, state, finished, cb); + } + } + } + function afterWrite(stream4, state, finished, cb) { + if (!finished) onwriteDrain(stream4, state); + state.pendingcb--; + cb(); + finishMaybe(stream4, state); + } + function onwriteDrain(stream4, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream4.emit("drain"); + } + } + function clearBuffer(stream4, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream4._writev && entry && entry.next) { + var l = state.bufferedRequestCount; + var buffer2 = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer2[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer2.allBuffers = allBuffers; + doWrite(stream4, state, true, state.length, buffer2, "", holder.finish); + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream4, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); + }; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== void 0) this.write(chunk, encoding); + if (state.corked) { + state.corked = 1; + this.uncork(); + } + if (!state.ending) endWritable(this, state, cb); + return this; + }; + Object.defineProperty(Writable.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + function callFinal(stream4, state) { + stream4._final(function(err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream4, err); + } + state.prefinished = true; + stream4.emit("prefinish"); + finishMaybe(stream4, state); + }); + } + function prefinish(stream4, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream4._final === "function" && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream4, state); + } else { + state.prefinished = true; + stream4.emit("prefinish"); + } + } + } + function finishMaybe(stream4, state) { + var need = needFinish(state); + if (need) { + prefinish(stream4, state); + if (state.pendingcb === 0) { + state.finished = true; + stream4.emit("finish"); + if (state.autoDestroy) { + var rState = stream4._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream4.destroy(); + } + } + } + } + return need; + } + function endWritable(stream4, state, cb) { + state.ending = true; + finishMaybe(stream4, state); + if (cb) { + if (state.finished) process.nextTick(cb); + else stream4.once("finish", cb); + } + state.ended = true; + stream4.writable = false; + } + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + state.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === void 0) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + if (!this._writableState) { + return; + } + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + cb(err); + }; + } +}); + +// node_modules/winston-transport/modern.js +var require_modern = __commonJS({ + "node_modules/winston-transport/modern.js"(exports2, module2) { + "use strict"; + var util3 = __require("util"); + var Writable = require_stream_writable(); + var { LEVEL } = require_triple_beam(); + var TransportStream = module2.exports = function TransportStream2(options = {}) { + Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); + this.format = options.format; + this.level = options.level; + this.handleExceptions = options.handleExceptions; + this.handleRejections = options.handleRejections; + this.silent = options.silent; + if (options.log) this.log = options.log; + if (options.logv) this.logv = options.logv; + if (options.close) this.close = options.close; + this.once("pipe", (logger) => { + this.levels = logger.levels; + this.parent = logger; + }); + this.once("unpipe", (src) => { + if (src === this.parent) { + this.parent = null; + if (this.close) { + this.close(); + } + } + }); + }; + util3.inherits(TransportStream, Writable); + TransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || info.exception === true && !this.handleExceptions) { + return callback(null); + } + const level = this.level || this.parent && this.parent.level; + if (!level || this.levels[level] >= this.levels[info[LEVEL]]) { + if (info && !this.format) { + return this.log(info, callback); + } + let errState; + let transformed; + try { + transformed = this.format.transform(Object.assign({}, info), this.format.options); + } catch (err) { + errState = err; + } + if (errState || !transformed) { + callback(); + if (errState) throw errState; + return; + } + return this.log(transformed, callback); + } + this._writableState.sync = false; + return callback(null); + }; + TransportStream.prototype._writev = function _writev(chunks, callback) { + if (this.logv) { + const infos = chunks.filter(this._accept, this); + if (!infos.length) { + return callback(null); + } + return this.logv(infos, callback); + } + for (let i = 0; i < chunks.length; i++) { + if (!this._accept(chunks[i])) continue; + if (chunks[i].chunk && !this.format) { + this.log(chunks[i].chunk, chunks[i].callback); + continue; + } + let errState; + let transformed; + try { + transformed = this.format.transform( + Object.assign({}, chunks[i].chunk), + this.format.options + ); + } catch (err) { + errState = err; + } + if (errState || !transformed) { + chunks[i].callback(); + if (errState) { + callback(null); + throw errState; + } + } else { + this.log(transformed, chunks[i].callback); + } + } + return callback(null); + }; + TransportStream.prototype._accept = function _accept(write) { + const info = write.chunk; + if (this.silent) { + return false; + } + const level = this.level || this.parent && this.parent.level; + if (info.exception === true || !level || this.levels[level] >= this.levels[info[LEVEL]]) { + if (this.handleExceptions || info.exception !== true) { + return true; + } + } + return false; + }; + TransportStream.prototype._nop = function _nop() { + return void 0; + }; + } +}); + +// node_modules/winston-transport/legacy.js +var require_legacy = __commonJS({ + "node_modules/winston-transport/legacy.js"(exports2, module2) { + "use strict"; + var util3 = __require("util"); + var { LEVEL } = require_triple_beam(); + var TransportStream = require_modern(); + var LegacyTransportStream = module2.exports = function LegacyTransportStream2(options = {}) { + TransportStream.call(this, options); + if (!options.transport || typeof options.transport.log !== "function") { + throw new Error("Invalid transport, must be an object with a log method."); + } + this.transport = options.transport; + this.level = this.level || options.transport.level; + this.handleExceptions = this.handleExceptions || options.transport.handleExceptions; + this._deprecated(); + function transportError(err) { + this.emit("error", err, this.transport); + } + if (!this.transport.__winstonError) { + this.transport.__winstonError = transportError.bind(this); + this.transport.on("error", this.transport.__winstonError); + } + }; + util3.inherits(LegacyTransportStream, TransportStream); + LegacyTransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || info.exception === true && !this.handleExceptions) { + return callback(null); + } + if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) { + this.transport.log(info[LEVEL], info.message, info, this._nop); + } + callback(null); + }; + LegacyTransportStream.prototype._writev = function _writev(chunks, callback) { + for (let i = 0; i < chunks.length; i++) { + if (this._accept(chunks[i])) { + this.transport.log( + chunks[i].chunk[LEVEL], + chunks[i].chunk.message, + chunks[i].chunk, + this._nop + ); + chunks[i].callback(); + } + } + return callback(null); + }; + LegacyTransportStream.prototype._deprecated = function _deprecated() { + console.error([ + `${this.transport.name} is a legacy winston transport. Consider upgrading: `, + "- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md" + ].join("\n")); + }; + LegacyTransportStream.prototype.close = function close() { + if (this.transport.close) { + this.transport.close(); + } + if (this.transport.__winstonError) { + this.transport.removeListener("error", this.transport.__winstonError); + this.transport.__winstonError = null; + } + }; + } +}); + +// node_modules/winston-transport/index.js +var require_winston_transport = __commonJS({ + "node_modules/winston-transport/index.js"(exports2, module2) { + "use strict"; + module2.exports = require_modern(); + module2.exports.LegacyTransportStream = require_legacy(); + } +}); + +// node_modules/winston/lib/winston/transports/console.js +var require_console = __commonJS({ + "node_modules/winston/lib/winston/transports/console.js"(exports2, module2) { + "use strict"; + var os2 = __require("os"); + var { LEVEL, MESSAGE } = require_triple_beam(); + var TransportStream = require_winston_transport(); + module2.exports = class Console extends TransportStream { + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + constructor(options = {}) { + super(options); + this.name = options.name || "console"; + this.stderrLevels = this._stringArrayToSet(options.stderrLevels); + this.consoleWarnLevels = this._stringArrayToSet(options.consoleWarnLevels); + this.eol = typeof options.eol === "string" ? options.eol : os2.EOL; + this.forceConsole = options.forceConsole || false; + this._consoleLog = console.log.bind(console); + this._consoleWarn = console.warn.bind(console); + this._consoleError = console.error.bind(console); + this.setMaxListeners(30); + } + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + setImmediate(() => this.emit("logged", info)); + if (this.stderrLevels[info[LEVEL]]) { + if (console._stderr && !this.forceConsole) { + console._stderr.write(`${info[MESSAGE]}${this.eol}`); + } else { + this._consoleError(info[MESSAGE]); + } + if (callback) { + callback(); + } + return; + } else if (this.consoleWarnLevels[info[LEVEL]]) { + if (console._stderr && !this.forceConsole) { + console._stderr.write(`${info[MESSAGE]}${this.eol}`); + } else { + this._consoleWarn(info[MESSAGE]); + } + if (callback) { + callback(); + } + return; + } + if (console._stdout && !this.forceConsole) { + console._stdout.write(`${info[MESSAGE]}${this.eol}`); + } else { + this._consoleLog(info[MESSAGE]); + } + if (callback) { + callback(); + } + } + /** + * Returns a Set-like object with strArray's elements as keys (each with the + * value true). + * @param {Array} strArray - Array of Set-elements as strings. + * @param {?string} [errMsg] - Custom error message thrown on invalid input. + * @returns {Object} - TODO: add return description. + * @private + */ + _stringArrayToSet(strArray, errMsg) { + if (!strArray) return {}; + errMsg = errMsg || "Cannot make set from type other than Array of string elements"; + if (!Array.isArray(strArray)) { + throw new Error(errMsg); + } + return strArray.reduce((set, el2) => { + if (typeof el2 !== "string") { + throw new Error(errMsg); + } + set[el2] = true; + return set; + }, {}); + } + }; + } +}); + +// node_modules/async/internal/isArrayLike.js +var require_isArrayLike = __commonJS({ + "node_modules/async/internal/isArrayLike.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = isArrayLike; + function isArrayLike(value) { + return value && typeof value.length === "number" && value.length >= 0 && value.length % 1 === 0; + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/initialParams.js +var require_initialParams = __commonJS({ + "node_modules/async/internal/initialParams.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = function(fn2) { + return function(...args) { + var callback = args.pop(); + return fn2.call(this, args, callback); + }; + }; + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/setImmediate.js +var require_setImmediate = __commonJS({ + "node_modules/async/internal/setImmediate.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.fallback = fallback2; + exports2.wrap = wrap; + var hasQueueMicrotask = exports2.hasQueueMicrotask = typeof queueMicrotask === "function" && queueMicrotask; + var hasSetImmediate = exports2.hasSetImmediate = typeof setImmediate === "function" && setImmediate; + var hasNextTick = exports2.hasNextTick = typeof process === "object" && typeof process.nextTick === "function"; + function fallback2(fn2) { + setTimeout(fn2, 0); + } + function wrap(defer) { + return (fn2, ...args) => defer(() => fn2(...args)); + } + var _defer; + if (hasQueueMicrotask) { + _defer = queueMicrotask; + } else if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } else { + _defer = fallback2; + } + exports2.default = wrap(_defer); + } +}); + +// node_modules/async/asyncify.js +var require_asyncify = __commonJS({ + "node_modules/async/asyncify.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = asyncify; + var _initialParams = require_initialParams(); + var _initialParams2 = _interopRequireDefault(_initialParams); + var _setImmediate2 = require_setImmediate(); + var _setImmediate22 = _interopRequireDefault(_setImmediate2); + var _wrapAsync = require_wrapAsync(); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function asyncify(func) { + if ((0, _wrapAsync.isAsync)(func)) { + return function(...args) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback); + }; + } + return (0, _initialParams2.default)(function(args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + if (result && typeof result.then === "function") { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); + } + function handlePromise(promise, callback) { + return promise.then((value) => { + invokeCallback(callback, null, value); + }, (err) => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); + } + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + (0, _setImmediate22.default)((e) => { + throw e; + }, err); + } + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/wrapAsync.js +var require_wrapAsync = __commonJS({ + "node_modules/async/internal/wrapAsync.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.isAsyncIterable = exports2.isAsyncGenerator = exports2.isAsync = void 0; + var _asyncify = require_asyncify(); + var _asyncify2 = _interopRequireDefault(_asyncify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function isAsync(fn2) { + return fn2[Symbol.toStringTag] === "AsyncFunction"; + } + function isAsyncGenerator(fn2) { + return fn2[Symbol.toStringTag] === "AsyncGenerator"; + } + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === "function"; + } + function wrapAsync2(asyncFn) { + if (typeof asyncFn !== "function") throw new Error("expected a function"); + return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; + } + exports2.default = wrapAsync2; + exports2.isAsync = isAsync; + exports2.isAsyncGenerator = isAsyncGenerator; + exports2.isAsyncIterable = isAsyncIterable; + } +}); + +// node_modules/async/internal/awaitify.js +var require_awaitify = __commonJS({ + "node_modules/async/internal/awaitify.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = awaitify; + function awaitify(asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error("arity is undefined"); + function awaitable(...args) { + if (typeof args[arity - 1] === "function") { + return asyncFn.apply(this, args); + } + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err); + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }); + } + return awaitable; + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/parallel.js +var require_parallel2 = __commonJS({ + "node_modules/async/internal/parallel.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _isArrayLike = require_isArrayLike(); + var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + var _wrapAsync = require_wrapAsync(); + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + var _awaitify = require_awaitify(); + var _awaitify2 = _interopRequireDefault(_awaitify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + exports2.default = (0, _awaitify2.default)((eachfn, tasks, callback) => { + var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; + eachfn(tasks, (task, key, taskCb) => { + (0, _wrapAsync2.default)(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, (err) => callback(err, results)); + }, 3); + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/once.js +var require_once = __commonJS({ + "node_modules/async/internal/once.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = once; + function once(fn2) { + function wrapper(...args) { + if (fn2 === null) return; + var callFn = fn2; + fn2 = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn2); + return wrapper; + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/getIterator.js +var require_getIterator = __commonJS({ + "node_modules/async/internal/getIterator.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = function(coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + }; + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/iterator.js +var require_iterator = __commonJS({ + "node_modules/async/internal/iterator.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = createIterator; + var _isArrayLike = require_isArrayLike(); + var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + var _getIterator = require_getIterator(); + var _getIterator2 = _interopRequireDefault(_getIterator); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? { value: coll[i], key: i } : null; + }; + } + function createES2015Iterator(iterator2) { + var i = -1; + return function next() { + var item = iterator2.next(); + if (item.done) return null; + i++; + return { value: item.value, key: i }; + }; + } + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === "__proto__") { + return next(); + } + return i < len ? { value: obj[key], key } : null; + }; + } + function createIterator(coll) { + if ((0, _isArrayLike2.default)(coll)) { + return createArrayIterator(coll); + } + var iterator2 = (0, _getIterator2.default)(coll); + return iterator2 ? createES2015Iterator(iterator2) : createObjectIterator(coll); + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/onlyOnce.js +var require_onlyOnce = __commonJS({ + "node_modules/async/internal/onlyOnce.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = onlyOnce; + function onlyOnce(fn2) { + return function(...args) { + if (fn2 === null) throw new Error("Callback was already called."); + var callFn = fn2; + fn2 = null; + callFn.apply(this, args); + }; + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/breakLoop.js +var require_breakLoop = __commonJS({ + "node_modules/async/internal/breakLoop.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var breakLoop = {}; + exports2.default = breakLoop; + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/asyncEachOfLimit.js +var require_asyncEachOfLimit = __commonJS({ + "node_modules/async/internal/asyncEachOfLimit.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = asyncEachOfLimit; + var _breakLoop = require_breakLoop(); + var _breakLoop2 = _interopRequireDefault(_breakLoop); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + function replenish() { + if (running >= limit || awaiting || done) return; + awaiting = true; + generator.next().then(({ value, done: iterDone }) => { + if (canceled || done) return; + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + function iterateeCallback(err, result) { + running -= 1; + if (canceled) return; + if (err) return handleError(err); + if (err === false) { + done = true; + canceled = true; + return; + } + if (result === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); + } + replenish(); + } + function handleError(err) { + if (canceled) return; + awaiting = false; + done = true; + callback(err); + } + replenish(); + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/eachOfLimit.js +var require_eachOfLimit = __commonJS({ + "node_modules/async/internal/eachOfLimit.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _once = require_once(); + var _once2 = _interopRequireDefault(_once); + var _iterator = require_iterator(); + var _iterator2 = _interopRequireDefault(_iterator); + var _onlyOnce = require_onlyOnce(); + var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + var _wrapAsync = require_wrapAsync(); + var _asyncEachOfLimit = require_asyncEachOfLimit(); + var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit); + var _breakLoop = require_breakLoop(); + var _breakLoop2 = _interopRequireDefault(_breakLoop); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + exports2.default = (limit) => { + return (obj, iteratee, callback) => { + callback = (0, _once2.default)(callback); + if (limit <= 0) { + throw new RangeError("concurrency limit cannot be less than 1"); + } + if (!obj) { + return callback(null); + } + if ((0, _wrapAsync.isAsyncGenerator)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback); + } + if ((0, _wrapAsync.isAsyncIterable)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback); + } + var nextElem = (0, _iterator2.default)(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + function iterateeCallback(err, value) { + if (canceled) return; + running -= 1; + if (err) { + done = true; + callback(err); + } else if (err === false) { + done = true; + canceled = true; + } else if (value === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); + } else if (!looping) { + replenish(); + } + } + function replenish() { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); + } + looping = false; + } + replenish(); + }; + }; + module2.exports = exports2.default; + } +}); + +// node_modules/async/eachOfLimit.js +var require_eachOfLimit2 = __commonJS({ + "node_modules/async/eachOfLimit.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _eachOfLimit2 = require_eachOfLimit(); + var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + var _wrapAsync = require_wrapAsync(); + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + var _awaitify = require_awaitify(); + var _awaitify2 = _interopRequireDefault(_awaitify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function eachOfLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); + } + exports2.default = (0, _awaitify2.default)(eachOfLimit, 4); + module2.exports = exports2.default; + } +}); + +// node_modules/async/eachOfSeries.js +var require_eachOfSeries = __commonJS({ + "node_modules/async/eachOfSeries.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _eachOfLimit = require_eachOfLimit2(); + var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + var _awaitify = require_awaitify(); + var _awaitify2 = _interopRequireDefault(_awaitify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function eachOfSeries(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); + } + exports2.default = (0, _awaitify2.default)(eachOfSeries, 3); + module2.exports = exports2.default; + } +}); + +// node_modules/async/series.js +var require_series = __commonJS({ + "node_modules/async/series.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = series; + var _parallel2 = require_parallel2(); + var _parallel3 = _interopRequireDefault(_parallel2); + var _eachOfSeries = require_eachOfSeries(); + var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function series(tasks, callback) { + return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback); + } + module2.exports = exports2.default; + } +}); + +// node_modules/readable-stream/lib/_stream_transform.js +var require_stream_transform = __commonJS({ + "node_modules/readable-stream/lib/_stream_transform.js"(exports2, module2) { + "use strict"; + module2.exports = Transform; + var _require$codes = require_errors2().codes; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; + var ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING; + var ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + var Duplex = require_stream_duplex(); + require_inherits()(Transform, Duplex); + function afterTransform(er2, data) { + var ts2 = this._transformState; + ts2.transforming = false; + var cb = ts2.writecb; + if (cb === null) { + return this.emit("error", new ERR_MULTIPLE_CALLBACK()); + } + ts2.writechunk = null; + ts2.writecb = null; + if (data != null) + this.push(data); + cb(er2); + var rs2 = this._readableState; + rs2.reading = false; + if (rs2.needReadable || rs2.length < rs2.highWaterMark) { + this._read(rs2.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + this._readableState.needReadable = true; + this._readableState.sync = false; + if (options) { + if (typeof options.transform === "function") this._transform = options.transform; + if (typeof options.flush === "function") this._flush = options.flush; + } + this.on("prefinish", prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === "function" && !this._readableState.destroyed) { + this._flush(function(er2, data) { + done(_this, er2, data); + }); + } else { + done(this, null, null); + } + } + Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + Transform.prototype._transform = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); + }; + Transform.prototype._write = function(chunk, encoding, cb) { + var ts2 = this._transformState; + ts2.writecb = cb; + ts2.writechunk = chunk; + ts2.writeencoding = encoding; + if (!ts2.transforming) { + var rs2 = this._readableState; + if (ts2.needTransform || rs2.needReadable || rs2.length < rs2.highWaterMark) this._read(rs2.highWaterMark); + } + }; + Transform.prototype._read = function(n) { + var ts2 = this._transformState; + if (ts2.writechunk !== null && !ts2.transforming) { + ts2.transforming = true; + this._transform(ts2.writechunk, ts2.writeencoding, ts2.afterTransform); + } else { + ts2.needTransform = true; + } + }; + Transform.prototype._destroy = function(err, cb) { + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + }); + }; + function done(stream4, er2, data) { + if (er2) return stream4.emit("error", er2); + if (data != null) + stream4.push(data); + if (stream4._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream4._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream4.push(null); + } + } +}); + +// node_modules/readable-stream/lib/_stream_passthrough.js +var require_stream_passthrough = __commonJS({ + "node_modules/readable-stream/lib/_stream_passthrough.js"(exports2, module2) { + "use strict"; + module2.exports = PassThrough; + var Transform = require_stream_transform(); + require_inherits()(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); + } + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); + }; + } +}); + +// node_modules/readable-stream/lib/internal/streams/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports2, module2) { + "use strict"; + var eos; + function once(callback) { + var called = false; + return function() { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + var _require$codes = require_errors2().codes; + var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function noop2(err) { + if (err) throw err; + } + function isRequest2(stream4) { + return stream4.setHeader && typeof stream4.abort === "function"; + } + function destroyer(stream4, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream4.on("close", function() { + closed = true; + }); + if (eos === void 0) eos = require_end_of_stream(); + eos(stream4, { + readable: reading, + writable: writing + }, function(err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function(err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + if (isRequest2(stream4)) return stream4.abort(); + if (typeof stream4.destroy === "function") return stream4.destroy(); + callback(err || new ERR_STREAM_DESTROYED("pipe")); + }; + } + function call2(fn2) { + fn2(); + } + function pipe(from5, to2) { + return from5.pipe(to2); + } + function popCallback(streams) { + if (!streams.length) return noop2; + if (typeof streams[streams.length - 1] !== "function") return noop2; + return streams.pop(); + } + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS("streams"); + } + var error; + var destroys = streams.map(function(stream4, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream4, reading, writing, function(err) { + if (!error) error = err; + if (err) destroys.forEach(call2); + if (reading) return; + destroys.forEach(call2); + callback(error); + }); + }); + return streams.reduce(pipe); + } + module2.exports = pipeline; + } +}); + +// node_modules/readable-stream/readable.js +var require_readable = __commonJS({ + "node_modules/readable-stream/readable.js"(exports2, module2) { + var Stream = __require("stream"); + if (process.env.READABLE_STREAM === "disable" && Stream) { + module2.exports = Stream.Readable; + Object.assign(module2.exports, Stream); + module2.exports.Stream = Stream; + } else { + exports2 = module2.exports = require_stream_readable(); + exports2.Stream = Stream || exports2; + exports2.Readable = exports2; + exports2.Writable = require_stream_writable(); + exports2.Duplex = require_stream_duplex(); + exports2.Transform = require_stream_transform(); + exports2.PassThrough = require_stream_passthrough(); + exports2.finished = require_end_of_stream(); + exports2.pipeline = require_pipeline(); + } + } +}); + +// node_modules/@dabh/diagnostics/diagnostics.js +var require_diagnostics = __commonJS({ + "node_modules/@dabh/diagnostics/diagnostics.js"(exports2, module2) { + var adapters = []; + var modifiers2 = []; + var logger = function devnull() { + }; + function use(adapter) { + if (~adapters.indexOf(adapter)) return false; + adapters.push(adapter); + return true; + } + function set(custom) { + logger = custom; + } + function enabled(namespace) { + var async = []; + for (var i = 0; i < adapters.length; i++) { + if (adapters[i].async) { + async.push(adapters[i]); + continue; + } + if (adapters[i](namespace)) return true; + } + if (!async.length) return false; + return new Promise(function pinky(resolve) { + Promise.all( + async.map(function prebind(fn2) { + return fn2(namespace); + }) + ).then(function resolved(values) { + resolve(values.some(Boolean)); + }); + }); + } + function modify(fn2) { + if (~modifiers2.indexOf(fn2)) return false; + modifiers2.push(fn2); + return true; + } + function write() { + logger.apply(logger, arguments); + } + function process4(message) { + for (var i = 0; i < modifiers2.length; i++) { + message = modifiers2[i].apply(modifiers2[i], arguments); + } + return message; + } + function introduce(fn2, options) { + var has = Object.prototype.hasOwnProperty; + for (var key in options) { + if (has.call(options, key)) { + fn2[key] = options[key]; + } + } + return fn2; + } + function nope(options) { + options.enabled = false; + options.modify = modify; + options.set = set; + options.use = use; + return introduce(function diagnopes() { + return false; + }, options); + } + function yep(options) { + function diagnostics() { + var args = Array.prototype.slice.call(arguments, 0); + write.call(write, options, process4(args, options)); + return true; + } + options.enabled = true; + options.modify = modify; + options.set = set; + options.use = use; + return introduce(diagnostics, options); + } + module2.exports = function create(diagnostics) { + diagnostics.introduce = introduce; + diagnostics.enabled = enabled; + diagnostics.process = process4; + diagnostics.modify = modify; + diagnostics.write = write; + diagnostics.nope = nope; + diagnostics.yep = yep; + diagnostics.set = set; + diagnostics.use = use; + return diagnostics; + }; + } +}); + +// node_modules/@dabh/diagnostics/node/production.js +var require_production = __commonJS({ + "node_modules/@dabh/diagnostics/node/production.js"(exports2, module2) { + var create = require_diagnostics(); + var diagnostics = create(function prod(namespace, options) { + options = options || {}; + options.namespace = namespace; + options.prod = true; + options.dev = false; + if (!(options.force || prod.force)) return prod.nope(options); + return prod.yep(options); + }); + module2.exports = diagnostics; + } +}); + +// node_modules/color-name/index.js +var require_color_name = __commonJS({ + "node_modules/color-name/index.js"(exports2, module2) { + "use strict"; + module2.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + } +}); + +// node_modules/simple-swizzle/node_modules/is-arrayish/index.js +var require_is_arrayish = __commonJS({ + "node_modules/simple-swizzle/node_modules/is-arrayish/index.js"(exports2, module2) { + module2.exports = function isArrayish(obj) { + if (!obj || typeof obj === "string") { + return false; + } + return obj instanceof Array || Array.isArray(obj) || obj.length >= 0 && (obj.splice instanceof Function || Object.getOwnPropertyDescriptor(obj, obj.length - 1) && obj.constructor.name !== "String"); + }; + } +}); + +// node_modules/simple-swizzle/index.js +var require_simple_swizzle = __commonJS({ + "node_modules/simple-swizzle/index.js"(exports2, module2) { + "use strict"; + var isArrayish = require_is_arrayish(); + var concat3 = Array.prototype.concat; + var slice3 = Array.prototype.slice; + var swizzle = module2.exports = function swizzle2(args) { + var results = []; + for (var i = 0, len = args.length; i < len; i++) { + var arg = args[i]; + if (isArrayish(arg)) { + results = concat3.call(results, slice3.call(arg)); + } else { + results.push(arg); + } + } + return results; + }; + swizzle.wrap = function(fn2) { + return function() { + return fn2(swizzle(arguments)); + }; + }; + } +}); + +// node_modules/color-string/index.js +var require_color_string = __commonJS({ + "node_modules/color-string/index.js"(exports2, module2) { + var colorNames = require_color_name(); + var swizzle = require_simple_swizzle(); + var hasOwnProperty2 = Object.hasOwnProperty; + var reverseNames = /* @__PURE__ */ Object.create(null); + for (name in colorNames) { + if (hasOwnProperty2.call(colorNames, name)) { + reverseNames[colorNames[name]] = name; + } + } + var name; + var cs = module2.exports = { + to: {}, + get: {} + }; + cs.get = function(string) { + var prefix = string.substring(0, 3).toLowerCase(); + var val; + var model; + switch (prefix) { + case "hsl": + val = cs.get.hsl(string); + model = "hsl"; + break; + case "hwb": + val = cs.get.hwb(string); + model = "hwb"; + break; + default: + val = cs.get.rgb(string); + model = "rgb"; + break; + } + if (!val) { + return null; + } + return { model, value: val }; + }; + cs.get.rgb = function(string) { + if (!string) { + return null; + } + var abbr = /^#([a-f0-9]{3,4})$/i; + var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i; + var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; + var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; + var keyword = /^(\w+)$/; + var rgb = [0, 0, 0, 1]; + var match; + var i; + var hexAlpha; + if (match = string.match(hex)) { + hexAlpha = match[2]; + match = match[1]; + for (i = 0; i < 3; i++) { + var i2 = i * 2; + rgb[i] = parseInt(match.slice(i2, i2 + 2), 16); + } + if (hexAlpha) { + rgb[3] = parseInt(hexAlpha, 16) / 255; + } + } else if (match = string.match(abbr)) { + match = match[1]; + hexAlpha = match[3]; + for (i = 0; i < 3; i++) { + rgb[i] = parseInt(match[i] + match[i], 16); + } + if (hexAlpha) { + rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255; + } + } else if (match = string.match(rgba)) { + for (i = 0; i < 3; i++) { + rgb[i] = parseInt(match[i + 1], 0); + } + if (match[4]) { + if (match[5]) { + rgb[3] = parseFloat(match[4]) * 0.01; + } else { + rgb[3] = parseFloat(match[4]); + } + } + } else if (match = string.match(per)) { + for (i = 0; i < 3; i++) { + rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); + } + if (match[4]) { + if (match[5]) { + rgb[3] = parseFloat(match[4]) * 0.01; + } else { + rgb[3] = parseFloat(match[4]); + } + } + } else if (match = string.match(keyword)) { + if (match[1] === "transparent") { + return [0, 0, 0, 0]; + } + if (!hasOwnProperty2.call(colorNames, match[1])) { + return null; + } + rgb = colorNames[match[1]]; + rgb[3] = 1; + return rgb; + } else { + return null; + } + for (i = 0; i < 3; i++) { + rgb[i] = clamp(rgb[i], 0, 255); + } + rgb[3] = clamp(rgb[3], 0, 1); + return rgb; + }; + cs.get.hsl = function(string) { + if (!string) { + return null; + } + var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; + var match = string.match(hsl); + if (match) { + var alpha = parseFloat(match[4]); + var h = (parseFloat(match[1]) % 360 + 360) % 360; + var s = clamp(parseFloat(match[2]), 0, 100); + var l = clamp(parseFloat(match[3]), 0, 100); + var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, s, l, a]; + } + return null; + }; + cs.get.hwb = function(string) { + if (!string) { + return null; + } + var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; + var match = string.match(hwb); + if (match) { + var alpha = parseFloat(match[4]); + var h = (parseFloat(match[1]) % 360 + 360) % 360; + var w2 = clamp(parseFloat(match[2]), 0, 100); + var b2 = clamp(parseFloat(match[3]), 0, 100); + var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, w2, b2, a]; + } + return null; + }; + cs.to.hex = function() { + var rgba = swizzle(arguments); + return "#" + hexDouble(rgba[0]) + hexDouble(rgba[1]) + hexDouble(rgba[2]) + (rgba[3] < 1 ? hexDouble(Math.round(rgba[3] * 255)) : ""); + }; + cs.to.rgb = function() { + var rgba = swizzle(arguments); + return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ")" : "rgba(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ", " + rgba[3] + ")"; + }; + cs.to.rgb.percent = function() { + var rgba = swizzle(arguments); + var r = Math.round(rgba[0] / 255 * 100); + var g = Math.round(rgba[1] / 255 * 100); + var b2 = Math.round(rgba[2] / 255 * 100); + return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + r + "%, " + g + "%, " + b2 + "%)" : "rgba(" + r + "%, " + g + "%, " + b2 + "%, " + rgba[3] + ")"; + }; + cs.to.hsl = function() { + var hsla = swizzle(arguments); + return hsla.length < 4 || hsla[3] === 1 ? "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)" : "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + hsla[3] + ")"; + }; + cs.to.hwb = function() { + var hwba = swizzle(arguments); + var a = ""; + if (hwba.length >= 4 && hwba[3] !== 1) { + a = ", " + hwba[3]; + } + return "hwb(" + hwba[0] + ", " + hwba[1] + "%, " + hwba[2] + "%" + a + ")"; + }; + cs.to.keyword = function(rgb) { + return reverseNames[rgb.slice(0, 3)]; + }; + function clamp(num2, min, max) { + return Math.min(Math.max(min, num2), max); + } + function hexDouble(num2) { + var str = Math.round(num2).toString(16).toUpperCase(); + return str.length < 2 ? "0" + str : str; + } + } +}); + +// node_modules/color/node_modules/color-convert/node_modules/color-name/index.js +var require_color_name2 = __commonJS({ + "node_modules/color/node_modules/color-convert/node_modules/color-name/index.js"(exports2, module2) { + "use strict"; + module2.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + } +}); + +// node_modules/color/node_modules/color-convert/conversions.js +var require_conversions = __commonJS({ + "node_modules/color/node_modules/color-convert/conversions.js"(exports2, module2) { + var cssKeywords = require_color_name2(); + var reverseKeywords = {}; + for (key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } + } + var key; + var convert = module2.exports = { + rgb: { channels: 3, labels: "rgb" }, + hsl: { channels: 3, labels: "hsl" }, + hsv: { channels: 3, labels: "hsv" }, + hwb: { channels: 3, labels: "hwb" }, + cmyk: { channels: 4, labels: "cmyk" }, + xyz: { channels: 3, labels: "xyz" }, + lab: { channels: 3, labels: "lab" }, + lch: { channels: 3, labels: "lch" }, + hex: { channels: 1, labels: ["hex"] }, + keyword: { channels: 1, labels: ["keyword"] }, + ansi16: { channels: 1, labels: ["ansi16"] }, + ansi256: { channels: 1, labels: ["ansi256"] }, + hcg: { channels: 3, labels: ["h", "c", "g"] }, + apple: { channels: 3, labels: ["r16", "g16", "b16"] }, + gray: { channels: 1, labels: ["gray"] } + }; + for (model in convert) { + if (convert.hasOwnProperty(model)) { + if (!("channels" in convert[model])) { + throw new Error("missing channels property: " + model); + } + if (!("labels" in convert[model])) { + throw new Error("missing channel labels property: " + model); + } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error("channel and label counts mismatch: " + model); + } + channels = convert[model].channels; + labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], "channels", { value: channels }); + Object.defineProperty(convert[model], "labels", { value: labels }); + } + } + var channels; + var labels; + var model; + convert.rgb.hsl = function(rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b2 = rgb[2] / 255; + var min = Math.min(r, g, b2); + var max = Math.max(r, g, b2); + var delta = max - min; + var h; + var s; + var l; + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b2) / delta; + } else if (g === max) { + h = 2 + (b2 - r) / delta; + } else if (b2 === max) { + h = 4 + (r - g) / delta; + } + h = Math.min(h * 60, 360); + if (h < 0) { + h += 360; + } + l = (min + max) / 2; + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + return [h, s * 100, l * 100]; + }; + convert.rgb.hsv = function(rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b2 = rgb[2] / 255; + var v = Math.max(r, g, b2); + var diff = v - Math.min(r, g, b2); + var diffc = function(c) { + return (v - c) / 6 / diff + 1 / 2; + }; + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b2); + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = 1 / 3 + rdif - bdif; + } else if (b2 === v) { + h = 2 / 3 + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + return [ + h * 360, + s * 100, + v * 100 + ]; + }; + convert.rgb.hwb = function(rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b2 = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w2 = 1 / 255 * Math.min(r, Math.min(g, b2)); + b2 = 1 - 1 / 255 * Math.max(r, Math.max(g, b2)); + return [h, w2 * 100, b2 * 100]; + }; + convert.rgb.cmyk = function(rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b2 = rgb[2] / 255; + var c; + var m2; + var y2; + var k2; + k2 = Math.min(1 - r, 1 - g, 1 - b2); + c = (1 - r - k2) / (1 - k2) || 0; + m2 = (1 - g - k2) / (1 - k2) || 0; + y2 = (1 - b2 - k2) / (1 - k2) || 0; + return [c * 100, m2 * 100, y2 * 100, k2 * 100]; + }; + function comparativeDistance(x2, y2) { + return Math.pow(x2[0] - y2[0], 2) + Math.pow(x2[1] - y2[1], 2) + Math.pow(x2[2] - y2[2], 2); + } + convert.rgb.keyword = function(rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + var currentClosestDistance = Infinity; + var currentClosestKeyword; + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + var distance = comparativeDistance(rgb, value); + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + return currentClosestKeyword; + }; + convert.keyword.rgb = function(keyword) { + return cssKeywords[keyword]; + }; + convert.rgb.xyz = function(rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b2 = rgb[2] / 255; + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b2 = b2 > 0.04045 ? Math.pow((b2 + 0.055) / 1.055, 2.4) : b2 / 12.92; + var x2 = r * 0.4124 + g * 0.3576 + b2 * 0.1805; + var y2 = r * 0.2126 + g * 0.7152 + b2 * 0.0722; + var z = r * 0.0193 + g * 0.1192 + b2 * 0.9505; + return [x2 * 100, y2 * 100, z * 100]; + }; + convert.rgb.lab = function(rgb) { + var xyz = convert.rgb.xyz(rgb); + var x2 = xyz[0]; + var y2 = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b2; + x2 /= 95.047; + y2 /= 100; + z /= 108.883; + x2 = x2 > 8856e-6 ? Math.pow(x2, 1 / 3) : 7.787 * x2 + 16 / 116; + y2 = y2 > 8856e-6 ? Math.pow(y2, 1 / 3) : 7.787 * y2 + 16 / 116; + z = z > 8856e-6 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y2 - 16; + a = 500 * (x2 - y2); + b2 = 200 * (y2 - z); + return [l, a, b2]; + }; + convert.hsl.rgb = function(hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + t1 = 2 * l - t2; + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + rgb[i] = val * 255; + } + return rgb; + }; + convert.hsl.hsv = function(hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; + }; + convert.hsv.rgb = function(hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi2 = Math.floor(h) % 6; + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q2 = 255 * v * (1 - s * f); + var t = 255 * v * (1 - s * (1 - f)); + v *= 255; + switch (hi2) { + case 0: + return [v, t, p]; + case 1: + return [q2, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q2, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q2]; + } + }; + convert.hsv.hsl = function(hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl2; + var l; + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl2 = s * vmin; + sl2 /= lmin <= 1 ? lmin : 2 - lmin; + sl2 = sl2 || 0; + l /= 2; + return [h, sl2 * 100, l * 100]; + }; + convert.hwb.rgb = function(hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl2 = hwb[2] / 100; + var ratio = wh + bl2; + var i; + var v; + var f; + var n; + if (ratio > 1) { + wh /= ratio; + bl2 /= ratio; + } + i = Math.floor(6 * h); + v = 1 - bl2; + f = 6 * h - i; + if ((i & 1) !== 0) { + f = 1 - f; + } + n = wh + f * (v - wh); + var r; + var g; + var b2; + switch (i) { + default: + case 6: + case 0: + r = v; + g = n; + b2 = wh; + break; + case 1: + r = n; + g = v; + b2 = wh; + break; + case 2: + r = wh; + g = v; + b2 = n; + break; + case 3: + r = wh; + g = n; + b2 = v; + break; + case 4: + r = n; + g = wh; + b2 = v; + break; + case 5: + r = v; + g = wh; + b2 = n; + break; + } + return [r * 255, g * 255, b2 * 255]; + }; + convert.cmyk.rgb = function(cmyk) { + var c = cmyk[0] / 100; + var m2 = cmyk[1] / 100; + var y2 = cmyk[2] / 100; + var k2 = cmyk[3] / 100; + var r; + var g; + var b2; + r = 1 - Math.min(1, c * (1 - k2) + k2); + g = 1 - Math.min(1, m2 * (1 - k2) + k2); + b2 = 1 - Math.min(1, y2 * (1 - k2) + k2); + return [r * 255, g * 255, b2 * 255]; + }; + convert.xyz.rgb = function(xyz) { + var x2 = xyz[0] / 100; + var y2 = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b2; + r = x2 * 3.2406 + y2 * -1.5372 + z * -0.4986; + g = x2 * -0.9689 + y2 * 1.8758 + z * 0.0415; + b2 = x2 * 0.0557 + y2 * -0.204 + z * 1.057; + r = r > 31308e-7 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : r * 12.92; + g = g > 31308e-7 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : g * 12.92; + b2 = b2 > 31308e-7 ? 1.055 * Math.pow(b2, 1 / 2.4) - 0.055 : b2 * 12.92; + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b2 = Math.min(Math.max(0, b2), 1); + return [r * 255, g * 255, b2 * 255]; + }; + convert.xyz.lab = function(xyz) { + var x2 = xyz[0]; + var y2 = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b2; + x2 /= 95.047; + y2 /= 100; + z /= 108.883; + x2 = x2 > 8856e-6 ? Math.pow(x2, 1 / 3) : 7.787 * x2 + 16 / 116; + y2 = y2 > 8856e-6 ? Math.pow(y2, 1 / 3) : 7.787 * y2 + 16 / 116; + z = z > 8856e-6 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y2 - 16; + a = 500 * (x2 - y2); + b2 = 200 * (y2 - z); + return [l, a, b2]; + }; + convert.lab.xyz = function(lab) { + var l = lab[0]; + var a = lab[1]; + var b2 = lab[2]; + var x2; + var y2; + var z; + y2 = (l + 16) / 116; + x2 = a / 500 + y2; + z = y2 - b2 / 200; + var y22 = Math.pow(y2, 3); + var x22 = Math.pow(x2, 3); + var z2 = Math.pow(z, 3); + y2 = y22 > 8856e-6 ? y22 : (y2 - 16 / 116) / 7.787; + x2 = x22 > 8856e-6 ? x22 : (x2 - 16 / 116) / 7.787; + z = z2 > 8856e-6 ? z2 : (z - 16 / 116) / 7.787; + x2 *= 95.047; + y2 *= 100; + z *= 108.883; + return [x2, y2, z]; + }; + convert.lab.lch = function(lab) { + var l = lab[0]; + var a = lab[1]; + var b2 = lab[2]; + var hr2; + var h; + var c; + hr2 = Math.atan2(b2, a); + h = hr2 * 360 / 2 / Math.PI; + if (h < 0) { + h += 360; + } + c = Math.sqrt(a * a + b2 * b2); + return [l, c, h]; + }; + convert.lch.lab = function(lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b2; + var hr2; + hr2 = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr2); + b2 = c * Math.sin(hr2); + return [l, a, b2]; + }; + convert.rgb.ansi16 = function(args) { + var r = args[0]; + var g = args[1]; + var b2 = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; + value = Math.round(value / 50); + if (value === 0) { + return 30; + } + var ansi = 30 + (Math.round(b2 / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); + if (value === 2) { + ansi += 60; + } + return ansi; + }; + convert.hsv.ansi16 = function(args) { + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + convert.rgb.ansi256 = function(args) { + var r = args[0]; + var g = args[1]; + var b2 = args[2]; + if (r === g && g === b2) { + if (r < 8) { + return 16; + } + if (r > 248) { + return 231; + } + return Math.round((r - 8) / 247 * 24) + 232; + } + var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b2 / 255 * 5); + return ansi; + }; + convert.ansi16.rgb = function(args) { + var color = args % 10; + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + color = color / 10.5 * 255; + return [color, color, color]; + } + var mult = (~~(args > 50) + 1) * 0.5; + var r = (color & 1) * mult * 255; + var g = (color >> 1 & 1) * mult * 255; + var b2 = (color >> 2 & 1) * mult * 255; + return [r, g, b2]; + }; + convert.ansi256.rgb = function(args) { + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + args -= 16; + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b2 = rem % 6 / 5 * 255; + return [r, g, b2]; + }; + convert.rgb.hex = function(args) { + var integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255); + var string = integer.toString(16).toUpperCase(); + return "000000".substring(string.length) + string; + }; + convert.hex.rgb = function(args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + var colorString = match[0]; + if (match[0].length === 3) { + colorString = colorString.split("").map(function(char) { + return char + char; + }).join(""); + } + var integer = parseInt(colorString, 16); + var r = integer >> 16 & 255; + var g = integer >> 8 & 255; + var b2 = integer & 255; + return [r, g, b2]; + }; + convert.rgb.hcg = function(rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b2 = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b2); + var min = Math.min(Math.min(r, g), b2); + var chroma = max - min; + var grayscale; + var hue; + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + if (chroma <= 0) { + hue = 0; + } else if (max === r) { + hue = (g - b2) / chroma % 6; + } else if (max === g) { + hue = 2 + (b2 - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; + }; + convert.hsl.hcg = function(hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + if (l < 0.5) { + c = 2 * s * l; + } else { + c = 2 * s * (1 - l); + } + if (c < 1) { + f = (l - 0.5 * c) / (1 - c); + } + return [hsl[0], c * 100, f * 100]; + }; + convert.hsv.hcg = function(hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var c = s * v; + var f = 0; + if (c < 1) { + f = (v - c) / (1 - c); + } + return [hsv[0], c * 100, f * 100]; + }; + convert.hcg.rgb = function(hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + if (c === 0) { + return [g * 255, g * 255, g * 255]; + } + var pure = [0, 0, 0]; + var hi2 = h % 1 * 6; + var v = hi2 % 1; + var w2 = 1 - v; + var mg = 0; + switch (Math.floor(hi2)) { + case 0: + pure[0] = 1; + pure[1] = v; + pure[2] = 0; + break; + case 1: + pure[0] = w2; + pure[1] = 1; + pure[2] = 0; + break; + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v; + break; + case 3: + pure[0] = 0; + pure[1] = w2; + pure[2] = 1; + break; + case 4: + pure[0] = v; + pure[1] = 0; + pure[2] = 1; + break; + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w2; + } + mg = (1 - c) * g; + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; + }; + convert.hcg.hsv = function(hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1 - c); + var f = 0; + if (v > 0) { + f = c / v; + } + return [hcg[0], f * 100, v * 100]; + }; + convert.hcg.hsl = function(hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var l = g * (1 - c) + 0.5 * c; + var s = 0; + if (l > 0 && l < 0.5) { + s = c / (2 * l); + } else if (l >= 0.5 && l < 1) { + s = c / (2 * (1 - l)); + } + return [hcg[0], s * 100, l * 100]; + }; + convert.hcg.hwb = function(hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + convert.hwb.hcg = function(hwb) { + var w2 = hwb[1] / 100; + var b2 = hwb[2] / 100; + var v = 1 - b2; + var c = v - w2; + var g = 0; + if (c < 1) { + g = (v - c) / (1 - c); + } + return [hwb[0], c * 100, g * 100]; + }; + convert.apple.rgb = function(apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; + }; + convert.rgb.apple = function(rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; + }; + convert.gray.rgb = function(args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + convert.gray.hsl = convert.gray.hsv = function(args) { + return [0, 0, args[0]]; + }; + convert.gray.hwb = function(gray) { + return [0, 100, gray[0]]; + }; + convert.gray.cmyk = function(gray) { + return [0, 0, 0, gray[0]]; + }; + convert.gray.lab = function(gray) { + return [gray[0], 0, 0]; + }; + convert.gray.hex = function(gray) { + var val = Math.round(gray[0] / 100 * 255) & 255; + var integer = (val << 16) + (val << 8) + val; + var string = integer.toString(16).toUpperCase(); + return "000000".substring(string.length) + string; + }; + convert.rgb.gray = function(rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + } +}); + +// node_modules/color/node_modules/color-convert/route.js +var require_route = __commonJS({ + "node_modules/color/node_modules/color-convert/route.js"(exports2, module2) { + var conversions = require_conversions(); + function buildGraph() { + var graph = {}; + var models = Object.keys(conversions); + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + return graph; + } + function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; + graph[fromModel].distance = 0; + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + return graph; + } + function link(from5, to2) { + return function(args) { + return to2(from5(args)); + }; + } + function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn2 = conversions[graph[toModel].parent][toModel]; + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn2 = link(conversions[graph[cur].parent][cur], fn2); + cur = graph[cur].parent; + } + fn2.conversion = path; + return fn2; + } + module2.exports = function(fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + if (node.parent === null) { + continue; + } + conversion[toModel] = wrapConversion(toModel, graph); + } + return conversion; + }; + } +}); + +// node_modules/color/node_modules/color-convert/index.js +var require_color_convert = __commonJS({ + "node_modules/color/node_modules/color-convert/index.js"(exports2, module2) { + var conversions = require_conversions(); + var route = require_route(); + var convert = {}; + var models = Object.keys(conversions); + function wrapRaw(fn2) { + var wrappedFn = function(args) { + if (args === void 0 || args === null) { + return args; + } + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + return fn2(args); + }; + if ("conversion" in fn2) { + wrappedFn.conversion = fn2.conversion; + } + return wrappedFn; + } + function wrapRounded(fn2) { + var wrappedFn = function(args) { + if (args === void 0 || args === null) { + return args; + } + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + var result = fn2(args); + if (typeof result === "object") { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + return result; + }; + if ("conversion" in fn2) { + wrappedFn.conversion = fn2.conversion; + } + return wrappedFn; + } + models.forEach(function(fromModel) { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], "channels", { value: conversions[fromModel].channels }); + Object.defineProperty(convert[fromModel], "labels", { value: conversions[fromModel].labels }); + var routes = route(fromModel); + var routeModels = Object.keys(routes); + routeModels.forEach(function(toModel) { + var fn2 = routes[toModel]; + convert[fromModel][toModel] = wrapRounded(fn2); + convert[fromModel][toModel].raw = wrapRaw(fn2); + }); + }); + module2.exports = convert; + } +}); + +// node_modules/color/index.js +var require_color = __commonJS({ + "node_modules/color/index.js"(exports2, module2) { + "use strict"; + var colorString = require_color_string(); + var convert = require_color_convert(); + var _slice = [].slice; + var skippedModels = [ + // to be honest, I don't really feel like keyword belongs in color convert, but eh. + "keyword", + // gray conflicts with some method names, and has its own method defined. + "gray", + // shouldn't really be in color-convert either... + "hex" + ]; + var hashedModelKeys = {}; + Object.keys(convert).forEach(function(model) { + hashedModelKeys[_slice.call(convert[model].labels).sort().join("")] = model; + }); + var limiters = {}; + function Color(obj, model) { + if (!(this instanceof Color)) { + return new Color(obj, model); + } + if (model && model in skippedModels) { + model = null; + } + if (model && !(model in convert)) { + throw new Error("Unknown model: " + model); + } + var i; + var channels; + if (obj == null) { + this.model = "rgb"; + this.color = [0, 0, 0]; + this.valpha = 1; + } else if (obj instanceof Color) { + this.model = obj.model; + this.color = obj.color.slice(); + this.valpha = obj.valpha; + } else if (typeof obj === "string") { + var result = colorString.get(obj); + if (result === null) { + throw new Error("Unable to parse color from string: " + obj); + } + this.model = result.model; + channels = convert[this.model].channels; + this.color = result.value.slice(0, channels); + this.valpha = typeof result.value[channels] === "number" ? result.value[channels] : 1; + } else if (obj.length) { + this.model = model || "rgb"; + channels = convert[this.model].channels; + var newArr = _slice.call(obj, 0, channels); + this.color = zeroArray(newArr, channels); + this.valpha = typeof obj[channels] === "number" ? obj[channels] : 1; + } else if (typeof obj === "number") { + obj &= 16777215; + this.model = "rgb"; + this.color = [ + obj >> 16 & 255, + obj >> 8 & 255, + obj & 255 + ]; + this.valpha = 1; + } else { + this.valpha = 1; + var keys = Object.keys(obj); + if ("alpha" in obj) { + keys.splice(keys.indexOf("alpha"), 1); + this.valpha = typeof obj.alpha === "number" ? obj.alpha : 0; + } + var hashedKeys = keys.sort().join(""); + if (!(hashedKeys in hashedModelKeys)) { + throw new Error("Unable to parse color from object: " + JSON.stringify(obj)); + } + this.model = hashedModelKeys[hashedKeys]; + var labels = convert[this.model].labels; + var color = []; + for (i = 0; i < labels.length; i++) { + color.push(obj[labels[i]]); + } + this.color = zeroArray(color); + } + if (limiters[this.model]) { + channels = convert[this.model].channels; + for (i = 0; i < channels; i++) { + var limit = limiters[this.model][i]; + if (limit) { + this.color[i] = limit(this.color[i]); + } + } + } + this.valpha = Math.max(0, Math.min(1, this.valpha)); + if (Object.freeze) { + Object.freeze(this); + } + } + Color.prototype = { + toString: function() { + return this.string(); + }, + toJSON: function() { + return this[this.model](); + }, + string: function(places) { + var self2 = this.model in colorString.to ? this : this.rgb(); + self2 = self2.round(typeof places === "number" ? places : 1); + var args = self2.valpha === 1 ? self2.color : self2.color.concat(this.valpha); + return colorString.to[self2.model](args); + }, + percentString: function(places) { + var self2 = this.rgb().round(typeof places === "number" ? places : 1); + var args = self2.valpha === 1 ? self2.color : self2.color.concat(this.valpha); + return colorString.to.rgb.percent(args); + }, + array: function() { + return this.valpha === 1 ? this.color.slice() : this.color.concat(this.valpha); + }, + object: function() { + var result = {}; + var channels = convert[this.model].channels; + var labels = convert[this.model].labels; + for (var i = 0; i < channels; i++) { + result[labels[i]] = this.color[i]; + } + if (this.valpha !== 1) { + result.alpha = this.valpha; + } + return result; + }, + unitArray: function() { + var rgb = this.rgb().color; + rgb[0] /= 255; + rgb[1] /= 255; + rgb[2] /= 255; + if (this.valpha !== 1) { + rgb.push(this.valpha); + } + return rgb; + }, + unitObject: function() { + var rgb = this.rgb().object(); + rgb.r /= 255; + rgb.g /= 255; + rgb.b /= 255; + if (this.valpha !== 1) { + rgb.alpha = this.valpha; + } + return rgb; + }, + round: function(places) { + places = Math.max(places || 0, 0); + return new Color(this.color.map(roundToPlace(places)).concat(this.valpha), this.model); + }, + alpha: function(val) { + if (arguments.length) { + return new Color(this.color.concat(Math.max(0, Math.min(1, val))), this.model); + } + return this.valpha; + }, + // rgb + red: getset("rgb", 0, maxfn(255)), + green: getset("rgb", 1, maxfn(255)), + blue: getset("rgb", 2, maxfn(255)), + hue: getset(["hsl", "hsv", "hsl", "hwb", "hcg"], 0, function(val) { + return (val % 360 + 360) % 360; + }), + // eslint-disable-line brace-style + saturationl: getset("hsl", 1, maxfn(100)), + lightness: getset("hsl", 2, maxfn(100)), + saturationv: getset("hsv", 1, maxfn(100)), + value: getset("hsv", 2, maxfn(100)), + chroma: getset("hcg", 1, maxfn(100)), + gray: getset("hcg", 2, maxfn(100)), + white: getset("hwb", 1, maxfn(100)), + wblack: getset("hwb", 2, maxfn(100)), + cyan: getset("cmyk", 0, maxfn(100)), + magenta: getset("cmyk", 1, maxfn(100)), + yellow: getset("cmyk", 2, maxfn(100)), + black: getset("cmyk", 3, maxfn(100)), + x: getset("xyz", 0, maxfn(100)), + y: getset("xyz", 1, maxfn(100)), + z: getset("xyz", 2, maxfn(100)), + l: getset("lab", 0, maxfn(100)), + a: getset("lab", 1), + b: getset("lab", 2), + keyword: function(val) { + if (arguments.length) { + return new Color(val); + } + return convert[this.model].keyword(this.color); + }, + hex: function(val) { + if (arguments.length) { + return new Color(val); + } + return colorString.to.hex(this.rgb().round().color); + }, + rgbNumber: function() { + var rgb = this.rgb().color; + return (rgb[0] & 255) << 16 | (rgb[1] & 255) << 8 | rgb[2] & 255; + }, + luminosity: function() { + var rgb = this.rgb().color; + var lum = []; + for (var i = 0; i < rgb.length; i++) { + var chan = rgb[i] / 255; + lum[i] = chan <= 0.03928 ? chan / 12.92 : Math.pow((chan + 0.055) / 1.055, 2.4); + } + return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; + }, + contrast: function(color2) { + var lum1 = this.luminosity(); + var lum2 = color2.luminosity(); + if (lum1 > lum2) { + return (lum1 + 0.05) / (lum2 + 0.05); + } + return (lum2 + 0.05) / (lum1 + 0.05); + }, + level: function(color2) { + var contrastRatio = this.contrast(color2); + if (contrastRatio >= 7.1) { + return "AAA"; + } + return contrastRatio >= 4.5 ? "AA" : ""; + }, + isDark: function() { + var rgb = this.rgb().color; + var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1e3; + return yiq < 128; + }, + isLight: function() { + return !this.isDark(); + }, + negate: function() { + var rgb = this.rgb(); + for (var i = 0; i < 3; i++) { + rgb.color[i] = 255 - rgb.color[i]; + } + return rgb; + }, + lighten: function(ratio) { + var hsl = this.hsl(); + hsl.color[2] += hsl.color[2] * ratio; + return hsl; + }, + darken: function(ratio) { + var hsl = this.hsl(); + hsl.color[2] -= hsl.color[2] * ratio; + return hsl; + }, + saturate: function(ratio) { + var hsl = this.hsl(); + hsl.color[1] += hsl.color[1] * ratio; + return hsl; + }, + desaturate: function(ratio) { + var hsl = this.hsl(); + hsl.color[1] -= hsl.color[1] * ratio; + return hsl; + }, + whiten: function(ratio) { + var hwb = this.hwb(); + hwb.color[1] += hwb.color[1] * ratio; + return hwb; + }, + blacken: function(ratio) { + var hwb = this.hwb(); + hwb.color[2] += hwb.color[2] * ratio; + return hwb; + }, + grayscale: function() { + var rgb = this.rgb().color; + var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; + return Color.rgb(val, val, val); + }, + fade: function(ratio) { + return this.alpha(this.valpha - this.valpha * ratio); + }, + opaquer: function(ratio) { + return this.alpha(this.valpha + this.valpha * ratio); + }, + rotate: function(degrees) { + var hsl = this.hsl(); + var hue = hsl.color[0]; + hue = (hue + degrees) % 360; + hue = hue < 0 ? 360 + hue : hue; + hsl.color[0] = hue; + return hsl; + }, + mix: function(mixinColor, weight) { + if (!mixinColor || !mixinColor.rgb) { + throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor); + } + var color1 = mixinColor.rgb(); + var color2 = this.rgb(); + var p = weight === void 0 ? 0.5 : weight; + var w2 = 2 * p - 1; + var a = color1.alpha() - color2.alpha(); + var w1 = ((w2 * a === -1 ? w2 : (w2 + a) / (1 + w2 * a)) + 1) / 2; + var w22 = 1 - w1; + return Color.rgb( + w1 * color1.red() + w22 * color2.red(), + w1 * color1.green() + w22 * color2.green(), + w1 * color1.blue() + w22 * color2.blue(), + color1.alpha() * p + color2.alpha() * (1 - p) + ); + } + }; + Object.keys(convert).forEach(function(model) { + if (skippedModels.indexOf(model) !== -1) { + return; + } + var channels = convert[model].channels; + Color.prototype[model] = function() { + if (this.model === model) { + return new Color(this); + } + if (arguments.length) { + return new Color(arguments, model); + } + var newAlpha = typeof arguments[channels] === "number" ? channels : this.valpha; + return new Color(assertArray(convert[this.model][model].raw(this.color)).concat(newAlpha), model); + }; + Color[model] = function(color) { + if (typeof color === "number") { + color = zeroArray(_slice.call(arguments), channels); + } + return new Color(color, model); + }; + }); + function roundTo(num2, places) { + return Number(num2.toFixed(places)); + } + function roundToPlace(places) { + return function(num2) { + return roundTo(num2, places); + }; + } + function getset(model, channel, modifier) { + model = Array.isArray(model) ? model : [model]; + model.forEach(function(m2) { + (limiters[m2] || (limiters[m2] = []))[channel] = modifier; + }); + model = model[0]; + return function(val) { + var result; + if (arguments.length) { + if (modifier) { + val = modifier(val); + } + result = this[model](); + result.color[channel] = val; + return result; + } + result = this[model]().color[channel]; + if (modifier) { + result = modifier(result); + } + return result; + }; + } + function maxfn(max) { + return function(v) { + return Math.max(0, Math.min(max, v)); + }; + } + function assertArray(val) { + return Array.isArray(val) ? val : [val]; + } + function zeroArray(arr, length) { + for (var i = 0; i < length; i++) { + if (typeof arr[i] !== "number") { + arr[i] = 0; + } + } + return arr; + } + module2.exports = Color; + } +}); + +// node_modules/text-hex/index.js +var require_text_hex = __commonJS({ + "node_modules/text-hex/index.js"(exports2, module2) { + "use strict"; + module2.exports = function hex(str) { + for (var i = 0, hash2 = 0; i < str.length; hash2 = str.charCodeAt(i++) + ((hash2 << 5) - hash2)) ; + var color = Math.floor( + Math.abs( + Math.sin(hash2) * 1e4 % 1 * 16777216 + ) + ).toString(16); + return "#" + Array(6 - color.length + 1).join("0") + color; + }; + } +}); + +// node_modules/colorspace/index.js +var require_colorspace = __commonJS({ + "node_modules/colorspace/index.js"(exports2, module2) { + "use strict"; + var color = require_color(); + var hex = require_text_hex(); + module2.exports = function colorspace(namespace, delimiter) { + var split3 = namespace.split(delimiter || ":"); + var base = hex(split3[0]); + if (!split3.length) return base; + for (var i = 0, l = split3.length - 1; i < l; i++) { + base = color(base).mix(color(hex(split3[i + 1]))).saturate(1).hex(); + } + return base; + }; + } +}); + +// node_modules/kuler/index.js +var require_kuler = __commonJS({ + "node_modules/kuler/index.js"(exports2, module2) { + "use strict"; + function Kuler(text, color) { + if (color) return new Kuler(text).style(color); + if (!(this instanceof Kuler)) return new Kuler(text); + this.text = text; + } + Kuler.prototype.prefix = "\x1B["; + Kuler.prototype.suffix = "m"; + Kuler.prototype.hex = function hex(color) { + color = color[0] === "#" ? color.substring(1) : color; + if (color.length === 3) { + color = color.split(""); + color[5] = color[2]; + color[4] = color[2]; + color[3] = color[1]; + color[2] = color[1]; + color[1] = color[0]; + color = color.join(""); + } + var r = color.substring(0, 2), g = color.substring(2, 4), b2 = color.substring(4, 6); + return [parseInt(r, 16), parseInt(g, 16), parseInt(b2, 16)]; + }; + Kuler.prototype.rgb = function rgb(r, g, b2) { + var red = r / 255 * 5, green = g / 255 * 5, blue = b2 / 255 * 5; + return this.ansi(red, green, blue); + }; + Kuler.prototype.ansi = function ansi(r, g, b2) { + var red = Math.round(r), green = Math.round(g), blue = Math.round(b2); + return 16 + red * 36 + green * 6 + blue; + }; + Kuler.prototype.reset = function reset() { + return this.prefix + "39;49" + this.suffix; + }; + Kuler.prototype.style = function style(color) { + return this.prefix + "38;5;" + this.rgb.apply(this, this.hex(color)) + this.suffix + this.text + this.reset(); + }; + module2.exports = Kuler; + } +}); + +// node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js +var require_namespace_ansi = __commonJS({ + "node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js"(exports2, module2) { + var colorspace = require_colorspace(); + var kuler = require_kuler(); + module2.exports = function ansiModifier(args, options) { + var namespace = options.namespace; + var ansi = options.colors !== false ? kuler(namespace + ":", colorspace(namespace)) : namespace + ":"; + args[0] = ansi + " " + args[0]; + return args; + }; + } +}); + +// node_modules/enabled/index.js +var require_enabled = __commonJS({ + "node_modules/enabled/index.js"(exports2, module2) { + "use strict"; + module2.exports = function enabled(name, variable) { + if (!variable) return false; + var variables = variable.split(/[\s,]+/), i = 0; + for (; i < variables.length; i++) { + variable = variables[i].replace("*", ".*?"); + if ("-" === variable.charAt(0)) { + if (new RegExp("^" + variable.substr(1) + "$").test(name)) { + return false; + } + continue; + } + if (new RegExp("^" + variable + "$").test(name)) { + return true; + } + } + return false; + }; + } +}); + +// node_modules/@dabh/diagnostics/adapters/index.js +var require_adapters = __commonJS({ + "node_modules/@dabh/diagnostics/adapters/index.js"(exports2, module2) { + var enabled = require_enabled(); + module2.exports = function create(fn2) { + return function adapter(namespace) { + try { + return enabled(namespace, fn2()); + } catch (e) { + } + return false; + }; + }; + } +}); + +// node_modules/@dabh/diagnostics/adapters/process.env.js +var require_process_env = __commonJS({ + "node_modules/@dabh/diagnostics/adapters/process.env.js"(exports2, module2) { + var adapter = require_adapters(); + module2.exports = adapter(function processenv() { + return process.env.DEBUG || process.env.DIAGNOSTICS; + }); + } +}); + +// node_modules/@dabh/diagnostics/logger/console.js +var require_console2 = __commonJS({ + "node_modules/@dabh/diagnostics/logger/console.js"(exports2, module2) { + module2.exports = function(meta, messages) { + try { + Function.prototype.apply.call(console.log, console, messages); + } catch (e) { + } + }; + } +}); + +// node_modules/@dabh/diagnostics/node/development.js +var require_development = __commonJS({ + "node_modules/@dabh/diagnostics/node/development.js"(exports2, module2) { + var create = require_diagnostics(); + var tty = __require("tty").isatty(1); + var diagnostics = create(function dev(namespace, options) { + options = options || {}; + options.colors = "colors" in options ? options.colors : tty; + options.namespace = namespace; + options.prod = false; + options.dev = true; + if (!dev.enabled(namespace) && !(options.force || dev.force)) { + return dev.nope(options); + } + return dev.yep(options); + }); + diagnostics.modify(require_namespace_ansi()); + diagnostics.use(require_process_env()); + diagnostics.set(require_console2()); + module2.exports = diagnostics; + } +}); + +// node_modules/@dabh/diagnostics/node/index.js +var require_node3 = __commonJS({ + "node_modules/@dabh/diagnostics/node/index.js"(exports2, module2) { + if (process.env.NODE_ENV === "production") { + module2.exports = require_production(); + } else { + module2.exports = require_development(); + } + } +}); + +// node_modules/winston/lib/winston/tail-file.js +var require_tail_file = __commonJS({ + "node_modules/winston/lib/winston/tail-file.js"(exports2, module2) { + "use strict"; + var fs2 = __require("fs"); + var { StringDecoder } = __require("string_decoder"); + var { Stream } = require_readable(); + function noop2() { + } + module2.exports = (options, iter) => { + const buffer2 = Buffer.alloc(64 * 1024); + const decode2 = new StringDecoder("utf8"); + const stream4 = new Stream(); + let buff = ""; + let pos = 0; + let row = 0; + if (options.start === -1) { + delete options.start; + } + stream4.readable = true; + stream4.destroy = () => { + stream4.destroyed = true; + stream4.emit("end"); + stream4.emit("close"); + }; + fs2.open(options.file, "a+", "0644", (err, fd2) => { + if (err) { + if (!iter) { + stream4.emit("error", err); + } else { + iter(err); + } + stream4.destroy(); + return; + } + (function read() { + if (stream4.destroyed) { + fs2.close(fd2, noop2); + return; + } + return fs2.read(fd2, buffer2, 0, buffer2.length, pos, (error, bytes) => { + if (error) { + if (!iter) { + stream4.emit("error", error); + } else { + iter(error); + } + stream4.destroy(); + return; + } + if (!bytes) { + if (buff) { + if (options.start == null || row > options.start) { + if (!iter) { + stream4.emit("line", buff); + } else { + iter(null, buff); + } + } + row++; + buff = ""; + } + return setTimeout(read, 1e3); + } + let data = decode2.write(buffer2.slice(0, bytes)); + if (!iter) { + stream4.emit("data", data); + } + data = (buff + data).split(/\n+/); + const l = data.length - 1; + let i = 0; + for (; i < l; i++) { + if (options.start == null || row > options.start) { + if (!iter) { + stream4.emit("line", data[i]); + } else { + iter(null, data[i]); + } + } + row++; + } + buff = data[l]; + pos += bytes; + return read(); + }); + })(); + }); + if (!iter) { + return stream4; + } + return stream4.destroy; + }; + } +}); + +// node_modules/winston/lib/winston/transports/file.js +var require_file = __commonJS({ + "node_modules/winston/lib/winston/transports/file.js"(exports2, module2) { + "use strict"; + var fs2 = __require("fs"); + var path = __require("path"); + var asyncSeries = require_series(); + var zlib2 = __require("zlib"); + var { MESSAGE } = require_triple_beam(); + var { Stream, PassThrough } = require_readable(); + var TransportStream = require_winston_transport(); + var debug = require_node3()("winston:file"); + var os2 = __require("os"); + var tailFile = require_tail_file(); + module2.exports = class File extends TransportStream { + /** + * Constructor function for the File transport object responsible for + * persisting log messages and metadata to one or more files. + * @param {Object} options - Options for this instance. + */ + constructor(options = {}) { + super(options); + this.name = options.name || "file"; + function throwIf(target, ...args) { + args.slice(1).forEach((name) => { + if (options[name]) { + throw new Error(`Cannot set ${name} and ${target} together`); + } + }); + } + this._stream = new PassThrough(); + this._stream.setMaxListeners(30); + this._onError = this._onError.bind(this); + if (options.filename || options.dirname) { + throwIf("filename or dirname", "stream"); + this._basename = this.filename = options.filename ? path.basename(options.filename) : "winston.log"; + this.dirname = options.dirname || path.dirname(options.filename); + this.options = options.options || { flags: "a" }; + } else if (options.stream) { + console.warn("options.stream will be removed in winston@4. Use winston.transports.Stream"); + throwIf("stream", "filename", "maxsize"); + this._dest = this._stream.pipe(this._setupStream(options.stream)); + this.dirname = path.dirname(this._dest.path); + } else { + throw new Error("Cannot log to file without filename or stream."); + } + this.maxsize = options.maxsize || null; + this.rotationFormat = options.rotationFormat || false; + this.zippedArchive = options.zippedArchive || false; + this.maxFiles = options.maxFiles || null; + this.eol = typeof options.eol === "string" ? options.eol : os2.EOL; + this.tailable = options.tailable || false; + this.lazy = options.lazy || false; + this._size = 0; + this._pendingSize = 0; + this._created = 0; + this._drain = false; + this._opening = false; + this._ending = false; + this._fileExist = false; + if (this.dirname) this._createLogDirIfNotExist(this.dirname); + if (!this.lazy) this.open(); + } + finishIfEnding() { + if (this._ending) { + if (this._opening) { + this.once("open", () => { + this._stream.once("finish", () => this.emit("finish")); + setImmediate(() => this._stream.end()); + }); + } else { + this._stream.once("finish", () => this.emit("finish")); + setImmediate(() => this._stream.end()); + } + } + } + /** + * Core logging method exposed to Winston. Metadata is optional. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback = () => { + }) { + if (this.silent) { + callback(); + return true; + } + if (this._drain) { + this._stream.once("drain", () => { + this._drain = false; + this.log(info, callback); + }); + return; + } + if (this._rotate) { + this._stream.once("rotate", () => { + this._rotate = false; + this.log(info, callback); + }); + return; + } + if (this.lazy) { + if (!this._fileExist) { + if (!this._opening) { + this.open(); + } + this.once("open", () => { + this._fileExist = true; + this.log(info, callback); + return; + }); + return; + } + if (this._needsNewFile(this._pendingSize)) { + this._dest.once("close", () => { + if (!this._opening) { + this.open(); + } + this.once("open", () => { + this.log(info, callback); + return; + }); + return; + }); + return; + } + } + const output = `${info[MESSAGE]}${this.eol}`; + const bytes = Buffer.byteLength(output); + function logged() { + this._size += bytes; + this._pendingSize -= bytes; + debug("logged %s %s", this._size, output); + this.emit("logged", info); + if (this._rotate) { + return; + } + if (this._opening) { + return; + } + if (!this._needsNewFile()) { + return; + } + if (this.lazy) { + this._endStream(() => { + this.emit("fileclosed"); + }); + return; + } + this._rotate = true; + this._endStream(() => this._rotateFile()); + } + this._pendingSize += bytes; + if (this._opening && !this.rotatedWhileOpening && this._needsNewFile(this._size + this._pendingSize)) { + this.rotatedWhileOpening = true; + } + const written = this._stream.write(output, logged.bind(this)); + if (!written) { + this._drain = true; + this._stream.once("drain", () => { + this._drain = false; + callback(); + }); + } else { + callback(); + } + debug("written", written, this._drain); + this.finishIfEnding(); + return written; + } + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * TODO: Refactor me. + */ + query(options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } + options = normalizeQuery(options); + const file = path.join(this.dirname, this.filename); + let buff = ""; + let results = []; + let row = 0; + const stream4 = fs2.createReadStream(file, { + encoding: "utf8" + }); + stream4.on("error", (err) => { + if (stream4.readable) { + stream4.destroy(); + } + if (!callback) { + return; + } + return err.code !== "ENOENT" ? callback(err) : callback(null, results); + }); + stream4.on("data", (data) => { + data = (buff + data).split(/\n+/); + const l = data.length - 1; + let i = 0; + for (; i < l; i++) { + if (!options.start || row >= options.start) { + add(data[i]); + } + row++; + } + buff = data[l]; + }); + stream4.on("close", () => { + if (buff) { + add(buff, true); + } + if (options.order === "desc") { + results = results.reverse(); + } + if (callback) callback(null, results); + }); + function add(buff2, attempt) { + try { + const log = JSON.parse(buff2); + if (check(log)) { + push(log); + } + } catch (e) { + if (!attempt) { + stream4.emit("error", e); + } + } + } + function push(log) { + if (options.rows && results.length >= options.rows && options.order !== "desc") { + if (stream4.readable) { + stream4.destroy(); + } + return; + } + if (options.fields) { + log = options.fields.reduce((obj, key) => { + obj[key] = log[key]; + return obj; + }, {}); + } + if (options.order === "desc") { + if (results.length >= options.rows) { + results.shift(); + } + } + results.push(log); + } + function check(log) { + if (!log) { + return; + } + if (typeof log !== "object") { + return; + } + const time = new Date(log.timestamp); + if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) { + return; + } + return true; + } + function normalizeQuery(options2) { + options2 = options2 || {}; + options2.rows = options2.rows || options2.limit || 10; + options2.start = options2.start || 0; + options2.until = options2.until || /* @__PURE__ */ new Date(); + if (typeof options2.until !== "object") { + options2.until = new Date(options2.until); + } + options2.from = options2.from || options2.until - 24 * 60 * 60 * 1e3; + if (typeof options2.from !== "object") { + options2.from = new Date(options2.from); + } + options2.order = options2.order || "desc"; + return options2; + } + } + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + * TODO: Refactor me. + */ + stream(options = {}) { + const file = path.join(this.dirname, this.filename); + const stream4 = new Stream(); + const tail = { + file, + start: options.start + }; + stream4.destroy = tailFile(tail, (err, line) => { + if (err) { + return stream4.emit("error", err); + } + try { + stream4.emit("data", line); + line = JSON.parse(line); + stream4.emit("log", line); + } catch (e) { + stream4.emit("error", e); + } + }); + return stream4; + } + /** + * Checks to see the filesize of. + * @returns {undefined} + */ + open() { + if (!this.filename) return; + if (this._opening) return; + this._opening = true; + this.stat((err, size5) => { + if (err) { + return this.emit("error", err); + } + debug("stat done: %s { size: %s }", this.filename, size5); + this._size = size5; + this._dest = this._createStream(this._stream); + this._opening = false; + this.once("open", () => { + if (!this._stream.emit("rotate")) { + this._rotate = false; + } + }); + }); + } + /** + * Stat the file and assess information in order to create the proper stream. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + stat(callback) { + const target = this._getFile(); + const fullpath = path.join(this.dirname, target); + fs2.stat(fullpath, (err, stat) => { + if (err && err.code === "ENOENT") { + debug("ENOENT\xA0ok", fullpath); + this.filename = target; + return callback(null, 0); + } + if (err) { + debug(`err ${err.code} ${fullpath}`); + return callback(err); + } + if (!stat || this._needsNewFile(stat.size)) { + return this._incFile(() => this.stat(callback)); + } + this.filename = target; + callback(null, stat.size); + }); + } + /** + * Closes the stream associated with this instance. + * @param {function} cb - TODO: add param description. + * @returns {undefined} + */ + close(cb) { + if (!this._stream) { + return; + } + this._stream.end(() => { + if (cb) { + cb(); + } + this.emit("flush"); + this.emit("closed"); + }); + } + /** + * TODO: add method description. + * @param {number} size - TODO: add param description. + * @returns {undefined} + */ + _needsNewFile(size5) { + size5 = size5 || this._size; + return this.maxsize && size5 >= this.maxsize; + } + /** + * TODO: add method description. + * @param {Error} err - TODO: add param description. + * @returns {undefined} + */ + _onError(err) { + this.emit("error", err); + } + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + _setupStream(stream4) { + stream4.on("error", this._onError); + return stream4; + } + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + _cleanupStream(stream4) { + stream4.removeListener("error", this._onError); + stream4.destroy(); + return stream4; + } + /** + * TODO: add method description. + */ + _rotateFile() { + this._incFile(() => this.open()); + } + /** + * Unpipe from the stream that has been marked as full and end it so it + * flushes to disk. + * + * @param {function} callback - Callback for when the current file has closed. + * @private + */ + _endStream(callback = () => { + }) { + if (this._dest) { + this._stream.unpipe(this._dest); + this._dest.end(() => { + this._cleanupStream(this._dest); + callback(); + }); + } else { + callback(); + } + } + /** + * Returns the WritableStream for the active file on this instance. If we + * should gzip the file then a zlib stream is returned. + * + * @param {ReadableStream} source –PassThrough to pipe to the file when open. + * @returns {WritableStream} Stream that writes to disk for the active file. + */ + _createStream(source) { + const fullpath = path.join(this.dirname, this.filename); + debug("create stream start", fullpath, this.options); + const dest = fs2.createWriteStream(fullpath, this.options).on("error", (err) => debug(err)).on("close", () => debug("close", dest.path, dest.bytesWritten)).on("open", () => { + debug("file open ok", fullpath); + this.emit("open", fullpath); + source.pipe(dest); + if (this.rotatedWhileOpening) { + this._stream = new PassThrough(); + this._stream.setMaxListeners(30); + this._rotateFile(); + this.rotatedWhileOpening = false; + this._cleanupStream(dest); + source.end(); + } + }); + debug("create stream ok", fullpath); + return dest; + } + /** + * TODO: add method description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + _incFile(callback) { + debug("_incFile", this.filename); + const ext = path.extname(this._basename); + const basename = path.basename(this._basename, ext); + const tasks = []; + if (this.zippedArchive) { + tasks.push( + function(cb) { + const num2 = this._created > 0 && !this.tailable ? this._created : ""; + this._compressFile( + path.join(this.dirname, `${basename}${num2}${ext}`), + path.join(this.dirname, `${basename}${num2}${ext}.gz`), + cb + ); + }.bind(this) + ); + } + tasks.push( + function(cb) { + if (!this.tailable) { + this._created += 1; + this._checkMaxFilesIncrementing(ext, basename, cb); + } else { + this._checkMaxFilesTailable(ext, basename, cb); + } + }.bind(this) + ); + asyncSeries(tasks, callback); + } + /** + * Gets the next filename to use for this instance in the case that log + * filesizes are being capped. + * @returns {string} - TODO: add return description. + * @private + */ + _getFile() { + const ext = path.extname(this._basename); + const basename = path.basename(this._basename, ext); + const isRotation = this.rotationFormat ? this.rotationFormat() : this._created; + return !this.tailable && this._created ? `${basename}${isRotation}${ext}` : `${basename}${ext}`; + } + /** + * Increment the number of files created or checked by this instance. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + _checkMaxFilesIncrementing(ext, basename, callback) { + if (!this.maxFiles || this._created < this.maxFiles) { + return setImmediate(callback); + } + const oldest = this._created - this.maxFiles; + const isOldest = oldest !== 0 ? oldest : ""; + const isZipped = this.zippedArchive ? ".gz" : ""; + const filePath = `${basename}${isOldest}${ext}${isZipped}`; + const target = path.join(this.dirname, filePath); + fs2.unlink(target, callback); + } + /** + * Roll files forward based on integer, up to maxFiles. e.g. if base if + * file.log and it becomes oversized, roll to file1.log, and allow file.log + * to be re-used. If file is oversized again, roll file1.log to file2.log, + * roll file.log to file1.log, and so on. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + _checkMaxFilesTailable(ext, basename, callback) { + const tasks = []; + if (!this.maxFiles) { + return; + } + const isZipped = this.zippedArchive ? ".gz" : ""; + for (let x2 = this.maxFiles - 1; x2 > 1; x2--) { + tasks.push(function(i, cb) { + let fileName = `${basename}${i - 1}${ext}${isZipped}`; + const tmppath = path.join(this.dirname, fileName); + fs2.exists(tmppath, (exists) => { + if (!exists) { + return cb(null); + } + fileName = `${basename}${i}${ext}${isZipped}`; + fs2.rename(tmppath, path.join(this.dirname, fileName), cb); + }); + }.bind(this, x2)); + } + asyncSeries(tasks, () => { + fs2.rename( + path.join(this.dirname, `${basename}${ext}${isZipped}`), + path.join(this.dirname, `${basename}1${ext}${isZipped}`), + callback + ); + }); + } + /** + * Compresses src to dest with gzip and unlinks src + * @param {string} src - path to source file. + * @param {string} dest - path to zipped destination file. + * @param {Function} callback - callback called after file has been compressed. + * @returns {undefined} + * @private + */ + _compressFile(src, dest, callback) { + fs2.access(src, fs2.F_OK, (err) => { + if (err) { + return callback(); + } + var gzip = zlib2.createGzip(); + var inp = fs2.createReadStream(src); + var out = fs2.createWriteStream(dest); + out.on("finish", () => { + fs2.unlink(src, callback); + }); + inp.pipe(gzip).pipe(out); + }); + } + _createLogDirIfNotExist(dirPath) { + if (!fs2.existsSync(dirPath)) { + fs2.mkdirSync(dirPath, { recursive: true }); + } + } + }; + } +}); + +// node_modules/winston/lib/winston/transports/http.js +var require_http = __commonJS({ + "node_modules/winston/lib/winston/transports/http.js"(exports2, module2) { + "use strict"; + var http3 = __require("http"); + var https2 = __require("https"); + var { Stream } = require_readable(); + var TransportStream = require_winston_transport(); + var { configure } = require_safe_stable_stringify(); + module2.exports = class Http extends TransportStream { + /** + * Constructor function for the Http transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + // eslint-disable-next-line max-statements + constructor(options = {}) { + super(options); + this.options = options; + this.name = options.name || "http"; + this.ssl = !!options.ssl; + this.host = options.host || "localhost"; + this.port = options.port; + this.auth = options.auth; + this.path = options.path || ""; + this.maximumDepth = options.maximumDepth; + this.agent = options.agent; + this.headers = options.headers || {}; + this.headers["content-type"] = "application/json"; + this.batch = options.batch || false; + this.batchInterval = options.batchInterval || 5e3; + this.batchCount = options.batchCount || 10; + this.batchOptions = []; + this.batchTimeoutID = -1; + this.batchCallback = {}; + if (!this.port) { + this.port = this.ssl ? 443 : 80; + } + } + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + this._request(info, null, null, (err, res) => { + if (res && res.statusCode !== 200) { + err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`); + } + if (err) { + this.emit("warn", err); + } else { + this.emit("logged", info); + } + }); + if (callback) { + setImmediate(callback); + } + } + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * @returns {undefined} + */ + query(options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } + options = { + method: "query", + params: this.normalizeQuery(options) + }; + const auth = options.params.auth || null; + delete options.params.auth; + const path = options.params.path || null; + delete options.params.path; + this._request(options, auth, path, (err, res, body) => { + if (res && res.statusCode !== 200) { + err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`); + } + if (err) { + return callback(err); + } + if (typeof body === "string") { + try { + body = JSON.parse(body); + } catch (e) { + return callback(e); + } + } + callback(null, body); + }); + } + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description + */ + stream(options = {}) { + const stream4 = new Stream(); + options = { + method: "stream", + params: options + }; + const path = options.params.path || null; + delete options.params.path; + const auth = options.params.auth || null; + delete options.params.auth; + let buff = ""; + const req = this._request(options, auth, path); + stream4.destroy = () => req.destroy(); + req.on("data", (data) => { + data = (buff + data).split(/\n+/); + const l = data.length - 1; + let i = 0; + for (; i < l; i++) { + try { + stream4.emit("log", JSON.parse(data[i])); + } catch (e) { + stream4.emit("error", e); + } + } + buff = data[l]; + }); + req.on("error", (err) => stream4.emit("error", err)); + return stream4; + } + /** + * Make a request to a winstond server or any http server which can + * handle json-rpc. + * @param {function} options - Options to sent the request. + * @param {Object?} auth - authentication options + * @param {string} path - request path + * @param {function} callback - Continuation to respond to when complete. + */ + _request(options, auth, path, callback) { + options = options || {}; + auth = auth || this.auth; + path = path || this.path || ""; + if (this.batch) { + this._doBatch(options, callback, auth, path); + } else { + this._doRequest(options, callback, auth, path); + } + } + /** + * Send or memorize the options according to batch configuration + * @param {function} options - Options to sent the request. + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + _doBatch(options, callback, auth, path) { + this.batchOptions.push(options); + if (this.batchOptions.length === 1) { + const me = this; + this.batchCallback = callback; + this.batchTimeoutID = setTimeout(function() { + me.batchTimeoutID = -1; + me._doBatchRequest(me.batchCallback, auth, path); + }, this.batchInterval); + } + if (this.batchOptions.length === this.batchCount) { + this._doBatchRequest(this.batchCallback, auth, path); + } + } + /** + * Initiate a request with the memorized batch options, stop the batch timeout + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + _doBatchRequest(callback, auth, path) { + if (this.batchTimeoutID > 0) { + clearTimeout(this.batchTimeoutID); + this.batchTimeoutID = -1; + } + const batchOptionsCopy = this.batchOptions.slice(); + this.batchOptions = []; + this._doRequest(batchOptionsCopy, callback, auth, path); + } + /** + * Make a request to a winstond server or any http server which can + * handle json-rpc. + * @param {function} options - Options to sent the request. + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + _doRequest(options, callback, auth, path) { + const headers = Object.assign({}, this.headers); + if (auth && auth.bearer) { + headers.Authorization = `Bearer ${auth.bearer}`; + } + const req = (this.ssl ? https2 : http3).request({ + ...this.options, + method: "POST", + host: this.host, + port: this.port, + path: `/${path.replace(/^\//, "")}`, + headers, + auth: auth && auth.username && auth.password ? `${auth.username}:${auth.password}` : "", + agent: this.agent + }); + req.on("error", callback); + req.on("response", (res) => res.on("end", () => callback(null, res)).resume()); + const jsonStringify = configure({ + ...this.maximumDepth && { maximumDepth: this.maximumDepth } + }); + req.end(Buffer.from(jsonStringify(options, this.options.replacer), "utf8")); + } + }; + } +}); + +// node_modules/is-stream/index.js +var require_is_stream = __commonJS({ + "node_modules/is-stream/index.js"(exports2, module2) { + "use strict"; + var isStream2 = (stream4) => stream4 !== null && typeof stream4 === "object" && typeof stream4.pipe === "function"; + isStream2.writable = (stream4) => isStream2(stream4) && stream4.writable !== false && typeof stream4._write === "function" && typeof stream4._writableState === "object"; + isStream2.readable = (stream4) => isStream2(stream4) && stream4.readable !== false && typeof stream4._read === "function" && typeof stream4._readableState === "object"; + isStream2.duplex = (stream4) => isStream2.writable(stream4) && isStream2.readable(stream4); + isStream2.transform = (stream4) => isStream2.duplex(stream4) && typeof stream4._transform === "function"; + module2.exports = isStream2; + } +}); + +// node_modules/winston/lib/winston/transports/stream.js +var require_stream2 = __commonJS({ + "node_modules/winston/lib/winston/transports/stream.js"(exports2, module2) { + "use strict"; + var isStream2 = require_is_stream(); + var { MESSAGE } = require_triple_beam(); + var os2 = __require("os"); + var TransportStream = require_winston_transport(); + module2.exports = class Stream extends TransportStream { + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + constructor(options = {}) { + super(options); + if (!options.stream || !isStream2(options.stream)) { + throw new Error("options.stream is required."); + } + this._stream = options.stream; + this._stream.setMaxListeners(Infinity); + this.isObjectMode = options.stream._writableState.objectMode; + this.eol = typeof options.eol === "string" ? options.eol : os2.EOL; + } + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + setImmediate(() => this.emit("logged", info)); + if (this.isObjectMode) { + this._stream.write(info); + if (callback) { + callback(); + } + return; + } + this._stream.write(`${info[MESSAGE]}${this.eol}`); + if (callback) { + callback(); + } + return; + } + }; + } +}); + +// node_modules/winston/lib/winston/transports/index.js +var require_transports = __commonJS({ + "node_modules/winston/lib/winston/transports/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "Console", { + configurable: true, + enumerable: true, + get() { + return require_console(); + } + }); + Object.defineProperty(exports2, "File", { + configurable: true, + enumerable: true, + get() { + return require_file(); + } + }); + Object.defineProperty(exports2, "Http", { + configurable: true, + enumerable: true, + get() { + return require_http(); + } + }); + Object.defineProperty(exports2, "Stream", { + configurable: true, + enumerable: true, + get() { + return require_stream2(); + } + }); + } +}); + +// node_modules/winston/lib/winston/config/index.js +var require_config2 = __commonJS({ + "node_modules/winston/lib/winston/config/index.js"(exports2) { + "use strict"; + var logform = require_logform(); + var { configs } = require_triple_beam(); + exports2.cli = logform.levels(configs.cli); + exports2.npm = logform.levels(configs.npm); + exports2.syslog = logform.levels(configs.syslog); + exports2.addColors = logform.levels; + } +}); + +// node_modules/async/eachOf.js +var require_eachOf = __commonJS({ + "node_modules/async/eachOf.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _isArrayLike = require_isArrayLike(); + var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + var _breakLoop = require_breakLoop(); + var _breakLoop2 = _interopRequireDefault(_breakLoop); + var _eachOfLimit = require_eachOfLimit2(); + var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + var _once = require_once(); + var _once2 = _interopRequireDefault(_once); + var _onlyOnce = require_onlyOnce(); + var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + var _wrapAsync = require_wrapAsync(); + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + var _awaitify = require_awaitify(); + var _awaitify2 = _interopRequireDefault(_awaitify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback); + var index2 = 0, completed = 0, { length } = coll, canceled = false; + if (length === 0) { + callback(null); + } + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return; + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + for (; index2 < length; index2++) { + iteratee(coll[index2], index2, (0, _onlyOnce2.default)(iteratorCallback)); + } + } + function eachOfGeneric(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); + } + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); + } + exports2.default = (0, _awaitify2.default)(eachOf, 3); + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/withoutIndex.js +var require_withoutIndex = __commonJS({ + "node_modules/async/internal/withoutIndex.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = _withoutIndex; + function _withoutIndex(iteratee) { + return (value, index2, callback) => iteratee(value, callback); + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/forEach.js +var require_forEach = __commonJS({ + "node_modules/async/forEach.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _eachOf = require_eachOf(); + var _eachOf2 = _interopRequireDefault(_eachOf); + var _withoutIndex = require_withoutIndex(); + var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + var _wrapAsync = require_wrapAsync(); + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + var _awaitify = require_awaitify(); + var _awaitify2 = _interopRequireDefault(_awaitify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function eachLimit(coll, iteratee, callback) { + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); + } + exports2.default = (0, _awaitify2.default)(eachLimit, 3); + module2.exports = exports2.default; + } +}); + +// node_modules/fn.name/index.js +var require_fn = __commonJS({ + "node_modules/fn.name/index.js"(exports2, module2) { + "use strict"; + var toString3 = Object.prototype.toString; + module2.exports = function name(fn2) { + if ("string" === typeof fn2.displayName && fn2.constructor.name) { + return fn2.displayName; + } else if ("string" === typeof fn2.name && fn2.name) { + return fn2.name; + } + if ("object" === typeof fn2 && fn2.constructor && "string" === typeof fn2.constructor.name) return fn2.constructor.name; + var named = fn2.toString(), type = toString3.call(fn2).slice(8, -1); + if ("Function" === type) { + named = named.substring(named.indexOf("(") + 1, named.indexOf(")")); + } else { + named = type; + } + return named || "anonymous"; + }; + } +}); + +// node_modules/one-time/index.js +var require_one_time = __commonJS({ + "node_modules/one-time/index.js"(exports2, module2) { + "use strict"; + var name = require_fn(); + module2.exports = function one(fn2) { + var called = 0, value; + function onetime() { + if (called) return value; + called = 1; + value = fn2.apply(this, arguments); + fn2 = null; + return value; + } + onetime.displayName = name(fn2); + return onetime; + }; + } +}); + +// node_modules/stack-trace/lib/stack-trace.js +var require_stack_trace = __commonJS({ + "node_modules/stack-trace/lib/stack-trace.js"(exports2) { + exports2.get = function(belowFn) { + var oldLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Infinity; + var dummyObject = {}; + var v8Handler = Error.prepareStackTrace; + Error.prepareStackTrace = function(dummyObject2, v8StackTrace2) { + return v8StackTrace2; + }; + Error.captureStackTrace(dummyObject, belowFn || exports2.get); + var v8StackTrace = dummyObject.stack; + Error.prepareStackTrace = v8Handler; + Error.stackTraceLimit = oldLimit; + return v8StackTrace; + }; + exports2.parse = function(err) { + if (!err.stack) { + return []; + } + var self2 = this; + var lines = err.stack.split("\n").slice(1); + return lines.map(function(line) { + if (line.match(/^\s*[-]{4,}$/)) { + return self2._createParsedCallSite({ + fileName: line, + lineNumber: null, + functionName: null, + typeName: null, + methodName: null, + columnNumber: null, + "native": null + }); + } + var lineMatch = line.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/); + if (!lineMatch) { + return; + } + var object = null; + var method = null; + var functionName = null; + var typeName = null; + var methodName = null; + var isNative = lineMatch[5] === "native"; + if (lineMatch[1]) { + functionName = lineMatch[1]; + var methodStart = functionName.lastIndexOf("."); + if (functionName[methodStart - 1] == ".") + methodStart--; + if (methodStart > 0) { + object = functionName.substr(0, methodStart); + method = functionName.substr(methodStart + 1); + var objectEnd = object.indexOf(".Module"); + if (objectEnd > 0) { + functionName = functionName.substr(objectEnd + 1); + object = object.substr(0, objectEnd); + } + } + typeName = null; + } + if (method) { + typeName = object; + methodName = method; + } + if (method === "") { + methodName = null; + functionName = null; + } + var properties = { + fileName: lineMatch[2] || null, + lineNumber: parseInt(lineMatch[3], 10) || null, + functionName, + typeName, + methodName, + columnNumber: parseInt(lineMatch[4], 10) || null, + "native": isNative + }; + return self2._createParsedCallSite(properties); + }).filter(function(callSite) { + return !!callSite; + }); + }; + function CallSite(properties) { + for (var property in properties) { + this[property] = properties[property]; + } + } + var strProperties = [ + "this", + "typeName", + "functionName", + "methodName", + "fileName", + "lineNumber", + "columnNumber", + "function", + "evalOrigin" + ]; + var boolProperties = [ + "topLevel", + "eval", + "native", + "constructor" + ]; + strProperties.forEach(function(property) { + CallSite.prototype[property] = null; + CallSite.prototype["get" + property[0].toUpperCase() + property.substr(1)] = function() { + return this[property]; + }; + }); + boolProperties.forEach(function(property) { + CallSite.prototype[property] = false; + CallSite.prototype["is" + property[0].toUpperCase() + property.substr(1)] = function() { + return this[property]; + }; + }); + exports2._createParsedCallSite = function(properties) { + return new CallSite(properties); + }; + } +}); + +// node_modules/winston/lib/winston/exception-stream.js +var require_exception_stream = __commonJS({ + "node_modules/winston/lib/winston/exception-stream.js"(exports2, module2) { + "use strict"; + var { Writable } = require_readable(); + module2.exports = class ExceptionStream extends Writable { + /** + * Constructor function for the ExceptionStream responsible for wrapping a + * TransportStream; only allowing writes of `info` objects with + * `info.exception` set to true. + * @param {!TransportStream} transport - Stream to filter to exceptions + */ + constructor(transport) { + super({ objectMode: true }); + if (!transport) { + throw new Error("ExceptionStream requires a TransportStream instance."); + } + this.handleExceptions = true; + this.transport = transport; + } + /** + * Writes the info object to our transport instance if (and only if) the + * `exception` property is set on the info. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {mixed} - TODO: add return description. + * @private + */ + _write(info, enc, callback) { + if (info.exception) { + return this.transport.log(info, callback); + } + callback(); + return true; + } + }; + } +}); + +// node_modules/winston/lib/winston/exception-handler.js +var require_exception_handler = __commonJS({ + "node_modules/winston/lib/winston/exception-handler.js"(exports2, module2) { + "use strict"; + var os2 = __require("os"); + var asyncForEach = require_forEach(); + var debug = require_node3()("winston:exception"); + var once = require_one_time(); + var stackTrace = require_stack_trace(); + var ExceptionStream = require_exception_stream(); + module2.exports = class ExceptionHandler { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + constructor(logger) { + if (!logger) { + throw new Error("Logger is required to handle exceptions"); + } + this.logger = logger; + this.handlers = /* @__PURE__ */ new Map(); + } + /** + * Handles `uncaughtException` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + handle(...args) { + args.forEach((arg) => { + if (Array.isArray(arg)) { + return arg.forEach((handler) => this._addHandler(handler)); + } + this._addHandler(arg); + }); + if (!this.catcher) { + this.catcher = this._uncaughtException.bind(this); + process.on("uncaughtException", this.catcher); + } + } + /** + * Removes any handlers to `uncaughtException` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + unhandle() { + if (this.catcher) { + process.removeListener("uncaughtException", this.catcher); + this.catcher = false; + Array.from(this.handlers.values()).forEach((wrapper) => this.logger.unpipe(wrapper)); + } + } + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + getAllInfo(err) { + let message = null; + if (err) { + message = typeof err === "string" ? err : err.message; + } + return { + error: err, + // TODO (indexzero): how do we configure this? + level: "error", + message: [ + `uncaughtException: ${message || "(no error message)"}`, + err && err.stack || " No stack trace" + ].join("\n"), + stack: err && err.stack, + exception: true, + date: (/* @__PURE__ */ new Date()).toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; + } + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getOsInfo() { + return { + loadavg: os2.loadavg(), + uptime: os2.uptime() + }; + } + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + getTrace(err) { + const trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map((site) => { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + function: site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + native: site.isNative() + }; + }); + } + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleExceptions = true; + const wrapper = new ExceptionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); + } + } + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + _uncaughtException(err) { + const info = this.getAllInfo(err); + const handlers = this._getExceptionHandlers(); + let doExit = typeof this.logger.exitOnError === "function" ? this.logger.exitOnError(err) : this.logger.exitOnError; + let timeout; + if (!handlers.length && doExit) { + console.warn("winston: exitOnError cannot be true with no exception handlers."); + console.warn("winston: not exiting process."); + doExit = false; + } + function gracefulExit() { + debug("doExit", doExit); + debug("process._exiting", process._exiting); + if (doExit && !process._exiting) { + if (timeout) { + clearTimeout(timeout); + } + process.exit(1); + } + } + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } + asyncForEach(handlers, (handler, next) => { + const done = once(next); + const transport = handler.transport || handler; + function onDone(event) { + return () => { + debug(event); + done(); + }; + } + transport._ending = true; + transport.once("finish", onDone("finished")); + transport.once("error", onDone("error")); + }, () => doExit && gracefulExit()); + this.logger.log(info); + if (doExit) { + timeout = setTimeout(gracefulExit, 3e3); + } + } + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + _getExceptionHandlers() { + return this.logger.transports.filter((wrap) => { + const transport = wrap.transport || wrap; + return transport.handleExceptions; + }); + } + }; + } +}); + +// node_modules/winston/lib/winston/rejection-stream.js +var require_rejection_stream = __commonJS({ + "node_modules/winston/lib/winston/rejection-stream.js"(exports2, module2) { + "use strict"; + var { Writable } = require_readable(); + module2.exports = class RejectionStream extends Writable { + /** + * Constructor function for the RejectionStream responsible for wrapping a + * TransportStream; only allowing writes of `info` objects with + * `info.rejection` set to true. + * @param {!TransportStream} transport - Stream to filter to rejections + */ + constructor(transport) { + super({ objectMode: true }); + if (!transport) { + throw new Error("RejectionStream requires a TransportStream instance."); + } + this.handleRejections = true; + this.transport = transport; + } + /** + * Writes the info object to our transport instance if (and only if) the + * `rejection` property is set on the info. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {mixed} - TODO: add return description. + * @private + */ + _write(info, enc, callback) { + if (info.rejection) { + return this.transport.log(info, callback); + } + callback(); + return true; + } + }; + } +}); + +// node_modules/winston/lib/winston/rejection-handler.js +var require_rejection_handler = __commonJS({ + "node_modules/winston/lib/winston/rejection-handler.js"(exports2, module2) { + "use strict"; + var os2 = __require("os"); + var asyncForEach = require_forEach(); + var debug = require_node3()("winston:rejection"); + var once = require_one_time(); + var stackTrace = require_stack_trace(); + var RejectionStream = require_rejection_stream(); + module2.exports = class RejectionHandler { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + constructor(logger) { + if (!logger) { + throw new Error("Logger is required to handle rejections"); + } + this.logger = logger; + this.handlers = /* @__PURE__ */ new Map(); + } + /** + * Handles `unhandledRejection` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + handle(...args) { + args.forEach((arg) => { + if (Array.isArray(arg)) { + return arg.forEach((handler) => this._addHandler(handler)); + } + this._addHandler(arg); + }); + if (!this.catcher) { + this.catcher = this._unhandledRejection.bind(this); + process.on("unhandledRejection", this.catcher); + } + } + /** + * Removes any handlers to `unhandledRejection` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + unhandle() { + if (this.catcher) { + process.removeListener("unhandledRejection", this.catcher); + this.catcher = false; + Array.from(this.handlers.values()).forEach( + (wrapper) => this.logger.unpipe(wrapper) + ); + } + } + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + getAllInfo(err) { + let message = null; + if (err) { + message = typeof err === "string" ? err : err.message; + } + return { + error: err, + // TODO (indexzero): how do we configure this? + level: "error", + message: [ + `unhandledRejection: ${message || "(no error message)"}`, + err && err.stack || " No stack trace" + ].join("\n"), + stack: err && err.stack, + rejection: true, + date: (/* @__PURE__ */ new Date()).toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; + } + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getOsInfo() { + return { + loadavg: os2.loadavg(), + uptime: os2.uptime() + }; + } + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + getTrace(err) { + const trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map((site) => { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + function: site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + native: site.isNative() + }; + }); + } + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleRejections = true; + const wrapper = new RejectionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); + } + } + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + _unhandledRejection(err) { + const info = this.getAllInfo(err); + const handlers = this._getRejectionHandlers(); + let doExit = typeof this.logger.exitOnError === "function" ? this.logger.exitOnError(err) : this.logger.exitOnError; + let timeout; + if (!handlers.length && doExit) { + console.warn("winston: exitOnError cannot be true with no rejection handlers."); + console.warn("winston: not exiting process."); + doExit = false; + } + function gracefulExit() { + debug("doExit", doExit); + debug("process._exiting", process._exiting); + if (doExit && !process._exiting) { + if (timeout) { + clearTimeout(timeout); + } + process.exit(1); + } + } + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } + asyncForEach( + handlers, + (handler, next) => { + const done = once(next); + const transport = handler.transport || handler; + function onDone(event) { + return () => { + debug(event); + done(); + }; + } + transport._ending = true; + transport.once("finish", onDone("finished")); + transport.once("error", onDone("error")); + }, + () => doExit && gracefulExit() + ); + this.logger.log(info); + if (doExit) { + timeout = setTimeout(gracefulExit, 3e3); + } + } + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + _getRejectionHandlers() { + return this.logger.transports.filter((wrap) => { + const transport = wrap.transport || wrap; + return transport.handleRejections; + }); + } + }; + } +}); + +// node_modules/winston/lib/winston/profiler.js +var require_profiler = __commonJS({ + "node_modules/winston/lib/winston/profiler.js"(exports2, module2) { + "use strict"; + var Profiler = class { + /** + * Constructor function for the Profiler instance used by + * `Logger.prototype.startTimer`. When done is called the timer will finish + * and log the duration. + * @param {!Logger} logger - TODO: add param description. + * @private + */ + constructor(logger) { + const Logger2 = require_logger(); + if (typeof logger !== "object" || Array.isArray(logger) || !(logger instanceof Logger2)) { + throw new Error("Logger is required for profiling"); + } else { + this.logger = logger; + this.start = Date.now(); + } + } + /** + * Ends the current timer (i.e. Profiler) instance and logs the `msg` along + * with the duration since creation. + * @returns {mixed} - TODO: add return description. + * @private + */ + done(...args) { + if (typeof args[args.length - 1] === "function") { + console.warn("Callback function no longer supported as of winston@3.0.0"); + args.pop(); + } + const info = typeof args[args.length - 1] === "object" ? args.pop() : {}; + info.level = info.level || "info"; + info.durationMs = Date.now() - this.start; + return this.logger.write(info); + } + }; + module2.exports = Profiler; + } +}); + +// node_modules/winston/lib/winston/logger.js +var require_logger = __commonJS({ + "node_modules/winston/lib/winston/logger.js"(exports2, module2) { + "use strict"; + var { Stream, Transform } = require_readable(); + var asyncForEach = require_forEach(); + var { LEVEL, SPLAT } = require_triple_beam(); + var isStream2 = require_is_stream(); + var ExceptionHandler = require_exception_handler(); + var RejectionHandler = require_rejection_handler(); + var LegacyTransportStream = require_legacy(); + var Profiler = require_profiler(); + var { warn } = require_common2(); + var config3 = require_config2(); + var formatRegExp = /%[scdjifoO%]/g; + var Logger2 = class extends Transform { + /** + * Constructor function for the Logger object responsible for persisting log + * messages and metadata to one or more transports. + * @param {!Object} options - foo + */ + constructor(options) { + super({ objectMode: true }); + this.configure(options); + } + child(defaultRequestMetadata) { + const logger = this; + return Object.create(logger, { + write: { + value: function(info) { + const infoClone = Object.assign( + {}, + defaultRequestMetadata, + info + ); + if (info instanceof Error) { + infoClone.stack = info.stack; + infoClone.message = info.message; + } + logger.write(infoClone); + } + } + }); + } + /** + * This will wholesale reconfigure this instance by: + * 1. Resetting all transports. Older transports will be removed implicitly. + * 2. Set all other options including levels, colors, rewriters, filters, + * exceptionHandlers, etc. + * @param {!Object} options - TODO: add param description. + * @returns {undefined} + */ + configure({ + silent, + format, + defaultMeta, + levels, + level = "info", + exitOnError = true, + transports, + colors, + emitErrs, + formatters, + padLevels, + rewriters, + stripColors, + exceptionHandlers, + rejectionHandlers + } = {}) { + if (this.transports.length) { + this.clear(); + } + this.silent = silent; + this.format = format || this.format || require_json()(); + this.defaultMeta = defaultMeta || null; + this.levels = levels || this.levels || config3.npm.levels; + this.level = level; + if (this.exceptions) { + this.exceptions.unhandle(); + } + if (this.rejections) { + this.rejections.unhandle(); + } + this.exceptions = new ExceptionHandler(this); + this.rejections = new RejectionHandler(this); + this.profilers = {}; + this.exitOnError = exitOnError; + if (transports) { + transports = Array.isArray(transports) ? transports : [transports]; + transports.forEach((transport) => this.add(transport)); + } + if (colors || emitErrs || formatters || padLevels || rewriters || stripColors) { + throw new Error( + [ + "{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.", + "Use a custom winston.format(function) instead.", + "See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md" + ].join("\n") + ); + } + if (exceptionHandlers) { + this.exceptions.handle(exceptionHandlers); + } + if (rejectionHandlers) { + this.rejections.handle(rejectionHandlers); + } + } + isLevelEnabled(level) { + const givenLevelValue = getLevelValue(this.levels, level); + if (givenLevelValue === null) { + return false; + } + const configuredLevelValue = getLevelValue(this.levels, this.level); + if (configuredLevelValue === null) { + return false; + } + if (!this.transports || this.transports.length === 0) { + return configuredLevelValue >= givenLevelValue; + } + const index2 = this.transports.findIndex((transport) => { + let transportLevelValue = getLevelValue(this.levels, transport.level); + if (transportLevelValue === null) { + transportLevelValue = configuredLevelValue; + } + return transportLevelValue >= givenLevelValue; + }); + return index2 !== -1; + } + /* eslint-disable valid-jsdoc */ + /** + * Ensure backwards compatibility with a `log` method + * @param {mixed} level - Level the log message is written at. + * @param {mixed} msg - TODO: add param description. + * @param {mixed} meta - TODO: add param description. + * @returns {Logger} - TODO: add return description. + * + * @example + * // Supports the existing API: + * logger.log('info', 'Hello world', { custom: true }); + * logger.log('info', new Error('Yo, it\'s on fire')); + * + * // Requires winston.format.splat() + * logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true }); + * + * // And the new API with a single JSON literal: + * logger.log({ level: 'info', message: 'Hello world', custom: true }); + * logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') }); + * + * // Also requires winston.format.splat() + * logger.log({ + * level: 'info', + * message: '%s %d%%', + * [SPLAT]: ['A string', 50], + * meta: { thisIsMeta: true } + * }); + * + */ + /* eslint-enable valid-jsdoc */ + log(level, msg, ...splat) { + if (arguments.length === 1) { + level[LEVEL] = level.level; + this._addDefaultMeta(level); + this.write(level); + return this; + } + if (arguments.length === 2) { + if (msg && typeof msg === "object") { + msg[LEVEL] = msg.level = level; + this._addDefaultMeta(msg); + this.write(msg); + return this; + } + msg = { [LEVEL]: level, level, message: msg }; + this._addDefaultMeta(msg); + this.write(msg); + return this; + } + const [meta] = splat; + if (typeof meta === "object" && meta !== null) { + const tokens = msg && msg.match && msg.match(formatRegExp); + if (!tokens) { + const info = Object.assign({}, this.defaultMeta, meta, { + [LEVEL]: level, + [SPLAT]: splat, + level, + message: msg + }); + if (meta.message) info.message = `${info.message} ${meta.message}`; + if (meta.stack) info.stack = meta.stack; + if (meta.cause) info.cause = meta.cause; + this.write(info); + return this; + } + } + this.write(Object.assign({}, this.defaultMeta, { + [LEVEL]: level, + [SPLAT]: splat, + level, + message: msg + })); + return this; + } + /** + * Pushes data so that it can be picked up by all of our pipe targets. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - Continues stream processing. + * @returns {undefined} + * @private + */ + _transform(info, enc, callback) { + if (this.silent) { + return callback(); + } + if (!info[LEVEL]) { + info[LEVEL] = info.level; + } + if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) { + console.error("[winston] Unknown logger level: %s", info[LEVEL]); + } + if (!this._readableState.pipes) { + console.error( + "[winston] Attempt to write logs with no transports, which can increase memory usage: %j", + info + ); + } + try { + this.push(this.format.transform(info, this.format.options)); + } finally { + this._writableState.sync = false; + callback(); + } + } + /** + * Delays the 'finish' event until all transport pipe targets have + * also emitted 'finish' or are already finished. + * @param {mixed} callback - Continues stream processing. + */ + _final(callback) { + const transports = this.transports.slice(); + asyncForEach( + transports, + (transport, next) => { + if (!transport || transport.finished) return setImmediate(next); + transport.once("finish", next); + transport.end(); + }, + callback + ); + } + /** + * Adds the transport to this logger instance by piping to it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + add(transport) { + const target = !isStream2(transport) || transport.log.length > 2 ? new LegacyTransportStream({ transport }) : transport; + if (!target._writableState || !target._writableState.objectMode) { + throw new Error( + "Transports must WritableStreams in objectMode. Set { objectMode: true }." + ); + } + this._onEvent("error", target); + this._onEvent("warn", target); + this.pipe(target); + if (transport.handleExceptions) { + this.exceptions.handle(); + } + if (transport.handleRejections) { + this.rejections.handle(); + } + return this; + } + /** + * Removes the transport from this logger instance by unpiping from it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + remove(transport) { + if (!transport) return this; + let target = transport; + if (!isStream2(transport) || transport.log.length > 2) { + target = this.transports.filter( + (match) => match.transport === transport + )[0]; + } + if (target) { + this.unpipe(target); + } + return this; + } + /** + * Removes all transports from this logger instance. + * @returns {Logger} - TODO: add return description. + */ + clear() { + this.unpipe(); + return this; + } + /** + * Cleans up resources (streams, event listeners) for all transports + * associated with this instance (if necessary). + * @returns {Logger} - TODO: add return description. + */ + close() { + this.exceptions.unhandle(); + this.rejections.unhandle(); + this.clear(); + this.emit("close"); + return this; + } + /** + * Sets the `target` levels specified on this instance. + * @param {Object} Target levels to use on this instance. + */ + setLevels() { + warn.deprecated("setLevels"); + } + /** + * Queries the all transports for this instance with the specified `options`. + * This will aggregate each transport's results into one object containing + * a property per transport. + * @param {Object} options - Query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + */ + query(options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } + options = options || {}; + const results = {}; + const queryObject = Object.assign({}, options.query || {}); + function queryTransport(transport, next) { + if (options.query && typeof transport.formatQuery === "function") { + options.query = transport.formatQuery(queryObject); + } + transport.query(options, (err, res) => { + if (err) { + return next(err); + } + if (typeof transport.formatResults === "function") { + res = transport.formatResults(res, options.format); + } + next(null, res); + }); + } + function addResults(transport, next) { + queryTransport(transport, (err, result) => { + if (next) { + result = err || result; + if (result) { + results[transport.name] = result; + } + next(); + } + next = null; + }); + } + asyncForEach( + this.transports.filter((transport) => !!transport.query), + addResults, + () => callback(null, results) + ); + } + /** + * Returns a log stream for all transports. Options object is optional. + * @param{Object} options={} - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + */ + stream(options = {}) { + const out = new Stream(); + const streams = []; + out._streams = streams; + out.destroy = () => { + let i = streams.length; + while (i--) { + streams[i].destroy(); + } + }; + this.transports.filter((transport) => !!transport.stream).forEach((transport) => { + const str = transport.stream(options); + if (!str) { + return; + } + streams.push(str); + str.on("log", (log) => { + log.transport = log.transport || []; + log.transport.push(transport.name); + out.emit("log", log); + }); + str.on("error", (err) => { + err.transport = err.transport || []; + err.transport.push(transport.name); + out.emit("error", err); + }); + }); + return out; + } + /** + * Returns an object corresponding to a specific timing. When done is called + * the timer will finish and log the duration. e.g.: + * @returns {Profile} - TODO: add return description. + * @example + * const timer = winston.startTimer() + * setTimeout(() => { + * timer.done({ + * message: 'Logging message' + * }); + * }, 1000); + */ + startTimer() { + return new Profiler(this); + } + /** + * Tracks the time inbetween subsequent calls to this method with the same + * `id` parameter. The second call to this method will log the difference in + * milliseconds along with the message. + * @param {string} id Unique id of the profiler + * @returns {Logger} - TODO: add return description. + */ + profile(id2, ...args) { + const time = Date.now(); + if (this.profilers[id2]) { + const timeEnd = this.profilers[id2]; + delete this.profilers[id2]; + if (typeof args[args.length - 2] === "function") { + console.warn( + "Callback function no longer supported as of winston@3.0.0" + ); + args.pop(); + } + const info = typeof args[args.length - 1] === "object" ? args.pop() : {}; + info.level = info.level || "info"; + info.durationMs = time - timeEnd; + info.message = info.message || id2; + return this.write(info); + } + this.profilers[id2] = time; + return this; + } + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + handleExceptions(...args) { + console.warn( + "Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()" + ); + this.exceptions.handle(...args); + } + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + unhandleExceptions(...args) { + console.warn( + "Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()" + ); + this.exceptions.unhandle(...args); + } + /** + * Throw a more meaningful deprecation notice + * @throws {Error} - TODO: add throws description. + */ + cli() { + throw new Error( + [ + "Logger.cli() was removed in winston@3.0.0", + "Use a custom winston.formats.cli() instead.", + "See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md" + ].join("\n") + ); + } + /** + * Bubbles the `event` that occured on the specified `transport` up + * from this instance. + * @param {string} event - The event that occured + * @param {Object} transport - Transport on which the event occured + * @private + */ + _onEvent(event, transport) { + function transportEvent(err) { + if (event === "error" && !this.transports.includes(transport)) { + this.add(transport); + } + this.emit(event, err, transport); + } + if (!transport["__winston" + event]) { + transport["__winston" + event] = transportEvent.bind(this); + transport.on(event, transport["__winston" + event]); + } + } + _addDefaultMeta(msg) { + if (this.defaultMeta) { + Object.assign(msg, this.defaultMeta); + } + } + }; + function getLevelValue(levels, level) { + const value = levels[level]; + if (!value && value !== 0) { + return null; + } + return value; + } + Object.defineProperty(Logger2.prototype, "transports", { + configurable: false, + enumerable: true, + get() { + const { pipes } = this._readableState; + return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes; + } + }); + module2.exports = Logger2; + } +}); + +// node_modules/winston/lib/winston/create-logger.js +var require_create_logger = __commonJS({ + "node_modules/winston/lib/winston/create-logger.js"(exports2, module2) { + "use strict"; + var { LEVEL } = require_triple_beam(); + var config3 = require_config2(); + var Logger2 = require_logger(); + var debug = require_node3()("winston:create-logger"); + function isLevelEnabledFunctionName(level) { + return "is" + level.charAt(0).toUpperCase() + level.slice(1) + "Enabled"; + } + module2.exports = function(opts = {}) { + opts.levels = opts.levels || config3.npm.levels; + class DerivedLogger extends Logger2 { + /** + * Create a new class derived logger for which the levels can be attached to + * the prototype of. This is a V8 optimization that is well know to increase + * performance of prototype functions. + * @param {!Object} options - Options for the created logger. + */ + constructor(options) { + super(options); + } + } + const logger = new DerivedLogger(opts); + Object.keys(opts.levels).forEach(function(level) { + debug('Define prototype method for "%s"', level); + if (level === "log") { + console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.'); + return; + } + DerivedLogger.prototype[level] = function(...args) { + const self2 = this || logger; + if (args.length === 1) { + const [msg] = args; + const info = msg && msg.message && msg || { message: msg }; + info.level = info[LEVEL] = level; + self2._addDefaultMeta(info); + self2.write(info); + return this || logger; + } + if (args.length === 0) { + self2.log(level, ""); + return self2; + } + return self2.log(level, ...args); + }; + DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function() { + return (this || logger).isLevelEnabled(level); + }; + }); + return logger; + }; + } +}); + +// node_modules/winston/lib/winston/container.js +var require_container = __commonJS({ + "node_modules/winston/lib/winston/container.js"(exports2, module2) { + "use strict"; + var createLogger = require_create_logger(); + module2.exports = class Container { + /** + * Constructor function for the Container object responsible for managing a + * set of `winston.Logger` instances based on string ids. + * @param {!Object} [options={}] - Default pass-thru options for Loggers. + */ + constructor(options = {}) { + this.loggers = /* @__PURE__ */ new Map(); + this.options = options; + } + /** + * Retrieves a `winston.Logger` instance for the specified `id`. If an + * instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + add(id2, options) { + if (!this.loggers.has(id2)) { + options = Object.assign({}, options || this.options); + const existing = options.transports || this.options.transports; + if (existing) { + options.transports = Array.isArray(existing) ? existing.slice() : [existing]; + } else { + options.transports = []; + } + const logger = createLogger(options); + logger.on("close", () => this._delete(id2)); + this.loggers.set(id2, logger); + } + return this.loggers.get(id2); + } + /** + * Retreives a `winston.Logger` instance for the specified `id`. If + * an instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + get(id2, options) { + return this.add(id2, options); + } + /** + * Check if the container has a logger with the id. + * @param {?string} id - The id of the Logger instance to find. + * @returns {boolean} - Boolean value indicating if this instance has a + * logger with the specified `id`. + */ + has(id2) { + return !!this.loggers.has(id2); + } + /** + * Closes a `Logger` instance with the specified `id` if it exists. + * If no `id` is supplied then all Loggers are closed. + * @param {?string} id - The id of the Logger instance to close. + * @returns {undefined} + */ + close(id2) { + if (id2) { + return this._removeLogger(id2); + } + this.loggers.forEach((val, key) => this._removeLogger(key)); + } + /** + * Remove a logger based on the id. + * @param {!string} id - The id of the logger to remove. + * @returns {undefined} + * @private + */ + _removeLogger(id2) { + if (!this.loggers.has(id2)) { + return; + } + const logger = this.loggers.get(id2); + logger.close(); + this._delete(id2); + } + /** + * Deletes a `Logger` instance with the specified `id`. + * @param {!string} id - The id of the Logger instance to delete from + * container. + * @returns {undefined} + * @private + */ + _delete(id2) { + this.loggers.delete(id2); + } + }; + } +}); + +// node_modules/winston/lib/winston.js +var require_winston = __commonJS({ + "node_modules/winston/lib/winston.js"(exports2) { + "use strict"; + var logform = require_logform(); + var { warn } = require_common2(); + exports2.version = require_package2().version; + exports2.transports = require_transports(); + exports2.config = require_config2(); + exports2.addColors = logform.levels; + exports2.format = logform.format; + exports2.createLogger = require_create_logger(); + exports2.Logger = require_logger(); + exports2.ExceptionHandler = require_exception_handler(); + exports2.RejectionHandler = require_rejection_handler(); + exports2.Container = require_container(); + exports2.Transport = require_winston_transport(); + exports2.loggers = new exports2.Container(); + var defaultLogger = exports2.createLogger(); + Object.keys(exports2.config.npm.levels).concat([ + "log", + "query", + "stream", + "add", + "remove", + "clear", + "profile", + "startTimer", + "handleExceptions", + "unhandleExceptions", + "handleRejections", + "unhandleRejections", + "configure", + "child" + ]).forEach( + (method) => exports2[method] = (...args) => defaultLogger[method](...args) + ); + Object.defineProperty(exports2, "level", { + get() { + return defaultLogger.level; + }, + set(val) { + defaultLogger.level = val; + } + }); + Object.defineProperty(exports2, "exceptions", { + get() { + return defaultLogger.exceptions; + } + }); + Object.defineProperty(exports2, "rejections", { + get() { + return defaultLogger.rejections; + } + }); + ["exitOnError"].forEach((prop) => { + Object.defineProperty(exports2, prop, { + get() { + return defaultLogger[prop]; + }, + set(val) { + defaultLogger[prop] = val; + } + }); + }); + Object.defineProperty(exports2, "default", { + get() { + return { + exceptionHandlers: defaultLogger.exceptionHandlers, + rejectionHandlers: defaultLogger.rejectionHandlers, + transports: defaultLogger.transports + }; + } + }); + warn.deprecated(exports2, "setLevels"); + warn.forFunctions(exports2, "useFormat", ["cli"]); + warn.forProperties(exports2, "useFormat", ["padLevels", "stripColors"]); + warn.forFunctions(exports2, "deprecated", [ + "addRewriter", + "addFilter", + "clone", + "extend" + ]); + warn.forProperties(exports2, "deprecated", ["emitErrs", "levelLength"]); + } +}); + +// node_modules/object-hash/index.js +var require_object_hash = __commonJS({ + "node_modules/object-hash/index.js"(exports2, module2) { + "use strict"; + var crypto4 = __require("crypto"); + exports2 = module2.exports = objectHash; + function objectHash(object, options) { + options = applyDefaults(object, options); + return hash2(object, options); + } + exports2.sha1 = function(object) { + return objectHash(object); + }; + exports2.keys = function(object) { + return objectHash(object, { excludeValues: true, algorithm: "sha1", encoding: "hex" }); + }; + exports2.MD5 = function(object) { + return objectHash(object, { algorithm: "md5", encoding: "hex" }); + }; + exports2.keysMD5 = function(object) { + return objectHash(object, { algorithm: "md5", encoding: "hex", excludeValues: true }); + }; + var hashes = crypto4.getHashes ? crypto4.getHashes().slice() : ["sha1", "md5"]; + hashes.push("passthrough"); + var encodings = ["buffer", "hex", "binary", "base64"]; + function applyDefaults(object, sourceOptions) { + sourceOptions = sourceOptions || {}; + var options = {}; + options.algorithm = sourceOptions.algorithm || "sha1"; + options.encoding = sourceOptions.encoding || "hex"; + options.excludeValues = sourceOptions.excludeValues ? true : false; + options.algorithm = options.algorithm.toLowerCase(); + options.encoding = options.encoding.toLowerCase(); + options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; + options.respectType = sourceOptions.respectType === false ? false : true; + options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; + options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; + options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; + options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; + options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; + options.replacer = sourceOptions.replacer || void 0; + options.excludeKeys = sourceOptions.excludeKeys || void 0; + if (typeof object === "undefined") { + throw new Error("Object argument required."); + } + for (var i = 0; i < hashes.length; ++i) { + if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { + options.algorithm = hashes[i]; + } + } + if (hashes.indexOf(options.algorithm) === -1) { + throw new Error('Algorithm "' + options.algorithm + '" not supported. supported values: ' + hashes.join(", ")); + } + if (encodings.indexOf(options.encoding) === -1 && options.algorithm !== "passthrough") { + throw new Error('Encoding "' + options.encoding + '" not supported. supported values: ' + encodings.join(", ")); + } + return options; + } + function isNativeFunction(f) { + if (typeof f !== "function") { + return false; + } + var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; + return exp.exec(Function.prototype.toString.call(f)) != null; + } + function hash2(object, options) { + var hashingStream; + if (options.algorithm !== "passthrough") { + hashingStream = crypto4.createHash(options.algorithm); + } else { + hashingStream = new PassThrough(); + } + if (typeof hashingStream.write === "undefined") { + hashingStream.write = hashingStream.update; + hashingStream.end = hashingStream.update; + } + var hasher = typeHasher(options, hashingStream); + hasher.dispatch(object); + if (!hashingStream.update) { + hashingStream.end(""); + } + if (hashingStream.digest) { + return hashingStream.digest(options.encoding === "buffer" ? void 0 : options.encoding); + } + var buf = hashingStream.read(); + if (options.encoding === "buffer") { + return buf; + } + return buf.toString(options.encoding); + } + exports2.writeToStream = function(object, options, stream4) { + if (typeof stream4 === "undefined") { + stream4 = options; + options = {}; + } + options = applyDefaults(object, options); + return typeHasher(options, stream4).dispatch(object); + }; + function typeHasher(options, writeTo, context) { + context = context || []; + var write = function(str) { + if (writeTo.update) { + return writeTo.update(str, "utf8"); + } else { + return writeTo.write(str, "utf8"); + } + }; + return { + dispatch: function(value) { + if (options.replacer) { + value = options.replacer(value); + } + var type = typeof value; + if (value === null) { + type = "null"; + } + return this["_" + type](value); + }, + _object: function(object) { + var pattern = /\[object (.*)\]/i; + var objString = Object.prototype.toString.call(object); + var objType = pattern.exec(objString); + if (!objType) { + objType = "unknown:[" + objString + "]"; + } else { + objType = objType[1]; + } + objType = objType.toLowerCase(); + var objectNumber = null; + if ((objectNumber = context.indexOf(object)) >= 0) { + return this.dispatch("[CIRCULAR:" + objectNumber + "]"); + } else { + context.push(object); + } + if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) { + write("buffer:"); + return write(object); + } + if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") { + if (this["_" + objType]) { + this["_" + objType](object); + } else if (options.ignoreUnknown) { + return write("[" + objType + "]"); + } else { + throw new Error('Unknown object type "' + objType + '"'); + } + } else { + var keys = Object.keys(object); + if (options.unorderedObjects) { + keys = keys.sort(); + } + if (options.respectType !== false && !isNativeFunction(object)) { + keys.splice(0, 0, "prototype", "__proto__", "constructor"); + } + if (options.excludeKeys) { + keys = keys.filter(function(key) { + return !options.excludeKeys(key); + }); + } + write("object:" + keys.length + ":"); + var self2 = this; + return keys.forEach(function(key) { + self2.dispatch(key); + write(":"); + if (!options.excludeValues) { + self2.dispatch(object[key]); + } + write(","); + }); + } + }, + _array: function(arr, unordered) { + unordered = typeof unordered !== "undefined" ? unordered : options.unorderedArrays !== false; + var self2 = this; + write("array:" + arr.length + ":"); + if (!unordered || arr.length <= 1) { + return arr.forEach(function(entry) { + return self2.dispatch(entry); + }); + } + var contextAdditions = []; + var entries = arr.map(function(entry) { + var strm = new PassThrough(); + var localContext = context.slice(); + var hasher = typeHasher(options, strm, localContext); + hasher.dispatch(entry); + contextAdditions = contextAdditions.concat(localContext.slice(context.length)); + return strm.read().toString(); + }); + context = context.concat(contextAdditions); + entries.sort(); + return this._array(entries, false); + }, + _date: function(date) { + return write("date:" + date.toJSON()); + }, + _symbol: function(sym) { + return write("symbol:" + sym.toString()); + }, + _error: function(err) { + return write("error:" + err.toString()); + }, + _boolean: function(bool) { + return write("bool:" + bool.toString()); + }, + _string: function(string) { + write("string:" + string.length + ":"); + write(string.toString()); + }, + _function: function(fn2) { + write("fn:"); + if (isNativeFunction(fn2)) { + this.dispatch("[native]"); + } else { + this.dispatch(fn2.toString()); + } + if (options.respectFunctionNames !== false) { + this.dispatch("function-name:" + String(fn2.name)); + } + if (options.respectFunctionProperties) { + this._object(fn2); + } + }, + _number: function(number) { + return write("number:" + number.toString()); + }, + _xml: function(xml) { + return write("xml:" + xml.toString()); + }, + _null: function() { + return write("Null"); + }, + _undefined: function() { + return write("Undefined"); + }, + _regexp: function(regex) { + return write("regex:" + regex.toString()); + }, + _uint8array: function(arr) { + write("uint8array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint8clampedarray: function(arr) { + write("uint8clampedarray:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int8array: function(arr) { + write("int8array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint16array: function(arr) { + write("uint16array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int16array: function(arr) { + write("int16array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint32array: function(arr) { + write("uint32array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int32array: function(arr) { + write("int32array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float32array: function(arr) { + write("float32array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float64array: function(arr) { + write("float64array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _arraybuffer: function(arr) { + write("arraybuffer:"); + return this.dispatch(new Uint8Array(arr)); + }, + _url: function(url2) { + return write("url:" + url2.toString(), "utf8"); + }, + _map: function(map) { + write("map:"); + var arr = Array.from(map); + return this._array(arr, options.unorderedSets !== false); + }, + _set: function(set) { + write("set:"); + var arr = Array.from(set); + return this._array(arr, options.unorderedSets !== false); + }, + _file: function(file) { + write("file:"); + return this.dispatch([file.name, file.size, file.type, file.lastModfied]); + }, + _blob: function() { + if (options.ignoreUnknown) { + return write("[blob]"); + } + throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n'); + }, + _domwindow: function() { + return write("domwindow"); + }, + _bigint: function(number) { + return write("bigint:" + number.toString()); + }, + /* Node.js standard native objects */ + _process: function() { + return write("process"); + }, + _timer: function() { + return write("timer"); + }, + _pipe: function() { + return write("pipe"); + }, + _tcp: function() { + return write("tcp"); + }, + _udp: function() { + return write("udp"); + }, + _tty: function() { + return write("tty"); + }, + _statwatcher: function() { + return write("statwatcher"); + }, + _securecontext: function() { + return write("securecontext"); + }, + _connection: function() { + return write("connection"); + }, + _zlib: function() { + return write("zlib"); + }, + _context: function() { + return write("context"); + }, + _nodescript: function() { + return write("nodescript"); + }, + _httpparser: function() { + return write("httpparser"); + }, + _dataview: function() { + return write("dataview"); + }, + _signal: function() { + return write("signal"); + }, + _fsevent: function() { + return write("fsevent"); + }, + _tlswrap: function() { + return write("tlswrap"); + } + }; + } + function PassThrough() { + return { + buf: "", + write: function(b2) { + this.buf += b2; + }, + end: function(b2) { + this.buf += b2; + }, + read: function() { + return this.buf; + } + }; + } + } +}); + +// node_modules/moment/moment.js +var require_moment = __commonJS({ + "node_modules/moment/moment.js"(exports2, module2) { + (function(global2, factory) { + typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global2.moment = factory(); + })(exports2, function() { + "use strict"; + var hookCallback; + function hooks() { + return hookCallback.apply(null, arguments); + } + function setHookCallback(callback) { + hookCallback = callback; + } + function isArray2(input) { + return input instanceof Array || Object.prototype.toString.call(input) === "[object Array]"; + } + function isObject2(input) { + return input != null && Object.prototype.toString.call(input) === "[object Object]"; + } + function hasOwnProp(a, b2) { + return Object.prototype.hasOwnProperty.call(a, b2); + } + function isObjectEmpty(obj) { + if (Object.getOwnPropertyNames) { + return Object.getOwnPropertyNames(obj).length === 0; + } else { + var k2; + for (k2 in obj) { + if (hasOwnProp(obj, k2)) { + return false; + } + } + return true; + } + } + function isUndefined2(input) { + return input === void 0; + } + function isNumber2(input) { + return typeof input === "number" || Object.prototype.toString.call(input) === "[object Number]"; + } + function isDate2(input) { + return input instanceof Date || Object.prototype.toString.call(input) === "[object Date]"; + } + function map(arr, fn2) { + var res = [], i, arrLen = arr.length; + for (i = 0; i < arrLen; ++i) { + res.push(fn2(arr[i], i)); + } + return res; + } + function extend2(a, b2) { + for (var i in b2) { + if (hasOwnProp(b2, i)) { + a[i] = b2[i]; + } + } + if (hasOwnProp(b2, "toString")) { + a.toString = b2.toString; + } + if (hasOwnProp(b2, "valueOf")) { + a.valueOf = b2.valueOf; + } + return a; + } + function createUTC(input, format2, locale2, strict) { + return createLocalOrUTC(input, format2, locale2, strict, true).utc(); + } + function defaultParsingFlags() { + return { + empty: false, + unusedTokens: [], + unusedInput: [], + overflow: -2, + charsLeftOver: 0, + nullInput: false, + invalidEra: null, + invalidMonth: null, + invalidFormat: false, + userInvalidated: false, + iso: false, + parsedDateParts: [], + era: null, + meridiem: null, + rfc2822: false, + weekdayMismatch: false + }; + } + function getParsingFlags(m2) { + if (m2._pf == null) { + m2._pf = defaultParsingFlags(); + } + return m2._pf; + } + var some; + if (Array.prototype.some) { + some = Array.prototype.some; + } else { + some = function(fun) { + var t = Object(this), len = t.length >>> 0, i; + for (i = 0; i < len; i++) { + if (i in t && fun.call(this, t[i], i, t)) { + return true; + } + } + return false; + }; + } + function isValid(m2) { + var flags = null, parsedParts = false, isNowValid = m2._d && !isNaN(m2._d.getTime()); + if (isNowValid) { + flags = getParsingFlags(m2); + parsedParts = some.call(flags.parsedDateParts, function(i) { + return i != null; + }); + isNowValid = flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts); + if (m2._strict) { + isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === void 0; + } + } + if (Object.isFrozen == null || !Object.isFrozen(m2)) { + m2._isValid = isNowValid; + } else { + return isNowValid; + } + return m2._isValid; + } + function createInvalid(flags) { + var m2 = createUTC(NaN); + if (flags != null) { + extend2(getParsingFlags(m2), flags); + } else { + getParsingFlags(m2).userInvalidated = true; + } + return m2; + } + var momentProperties = hooks.momentProperties = [], updateInProgress = false; + function copyConfig(to3, from6) { + var i, prop, val, momentPropertiesLen = momentProperties.length; + if (!isUndefined2(from6._isAMomentObject)) { + to3._isAMomentObject = from6._isAMomentObject; + } + if (!isUndefined2(from6._i)) { + to3._i = from6._i; + } + if (!isUndefined2(from6._f)) { + to3._f = from6._f; + } + if (!isUndefined2(from6._l)) { + to3._l = from6._l; + } + if (!isUndefined2(from6._strict)) { + to3._strict = from6._strict; + } + if (!isUndefined2(from6._tzm)) { + to3._tzm = from6._tzm; + } + if (!isUndefined2(from6._isUTC)) { + to3._isUTC = from6._isUTC; + } + if (!isUndefined2(from6._offset)) { + to3._offset = from6._offset; + } + if (!isUndefined2(from6._pf)) { + to3._pf = getParsingFlags(from6); + } + if (!isUndefined2(from6._locale)) { + to3._locale = from6._locale; + } + if (momentPropertiesLen > 0) { + for (i = 0; i < momentPropertiesLen; i++) { + prop = momentProperties[i]; + val = from6[prop]; + if (!isUndefined2(val)) { + to3[prop] = val; + } + } + } + return to3; + } + function Moment(config3) { + copyConfig(this, config3); + this._d = new Date(config3._d != null ? config3._d.getTime() : NaN); + if (!this.isValid()) { + this._d = /* @__PURE__ */ new Date(NaN); + } + if (updateInProgress === false) { + updateInProgress = true; + hooks.updateOffset(this); + updateInProgress = false; + } + } + function isMoment(obj) { + return obj instanceof Moment || obj != null && obj._isAMomentObject != null; + } + function warn(msg) { + if (hooks.suppressDeprecationWarnings === false && typeof console !== "undefined" && console.warn) { + console.warn("Deprecation warning: " + msg); + } + } + function deprecate(msg, fn2) { + var firstTime = true; + return extend2(function() { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(null, msg); + } + if (firstTime) { + var args = [], arg, i, key, argLen = arguments.length; + for (i = 0; i < argLen; i++) { + arg = ""; + if (typeof arguments[i] === "object") { + arg += "\n[" + i + "] "; + for (key in arguments[0]) { + if (hasOwnProp(arguments[0], key)) { + arg += key + ": " + arguments[0][key] + ", "; + } + } + arg = arg.slice(0, -2); + } else { + arg = arguments[i]; + } + args.push(arg); + } + warn( + msg + "\nArguments: " + Array.prototype.slice.call(args).join("") + "\n" + new Error().stack + ); + firstTime = false; + } + return fn2.apply(this, arguments); + }, fn2); + } + var deprecations = {}; + function deprecateSimple(name, msg) { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(name, msg); + } + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } + } + hooks.suppressDeprecationWarnings = false; + hooks.deprecationHandler = null; + function isFunction2(input) { + return typeof Function !== "undefined" && input instanceof Function || Object.prototype.toString.call(input) === "[object Function]"; + } + function set(config3) { + var prop, i; + for (i in config3) { + if (hasOwnProp(config3, i)) { + prop = config3[i]; + if (isFunction2(prop)) { + this[i] = prop; + } else { + this["_" + i] = prop; + } + } + } + this._config = config3; + this._dayOfMonthOrdinalParseLenient = new RegExp( + (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + "|" + /\d{1,2}/.source + ); + } + function mergeConfigs(parentConfig, childConfig) { + var res = extend2({}, parentConfig), prop; + for (prop in childConfig) { + if (hasOwnProp(childConfig, prop)) { + if (isObject2(parentConfig[prop]) && isObject2(childConfig[prop])) { + res[prop] = {}; + extend2(res[prop], parentConfig[prop]); + extend2(res[prop], childConfig[prop]); + } else if (childConfig[prop] != null) { + res[prop] = childConfig[prop]; + } else { + delete res[prop]; + } + } + } + for (prop in parentConfig) { + if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject2(parentConfig[prop])) { + res[prop] = extend2({}, res[prop]); + } + } + return res; + } + function Locale(config3) { + if (config3 != null) { + this.set(config3); + } + } + var keys; + if (Object.keys) { + keys = Object.keys; + } else { + keys = function(obj) { + var i, res = []; + for (i in obj) { + if (hasOwnProp(obj, i)) { + res.push(i); + } + } + return res; + }; + } + var defaultCalendar = { + sameDay: "[Today at] LT", + nextDay: "[Tomorrow at] LT", + nextWeek: "dddd [at] LT", + lastDay: "[Yesterday at] LT", + lastWeek: "[Last] dddd [at] LT", + sameElse: "L" + }; + function calendar(key, mom, now2) { + var output = this._calendar[key] || this._calendar["sameElse"]; + return isFunction2(output) ? output.call(mom, now2) : output; + } + function zeroFill(number, targetLength, forceSign) { + var absNumber = "" + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign3 = number >= 0; + return (sign3 ? forceSign ? "+" : "" : "-") + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; + } + var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, formatFunctions = {}, formatTokenFunctions = {}; + function addFormatToken(token2, padded, ordinal2, callback) { + var func = callback; + if (typeof callback === "string") { + func = function() { + return this[callback](); + }; + } + if (token2) { + formatTokenFunctions[token2] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function() { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal2) { + formatTokenFunctions[ordinal2] = function() { + return this.localeData().ordinal( + func.apply(this, arguments), + token2 + ); + }; + } + } + function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ""); + } + return input.replace(/\\/g, ""); + } + function makeFormatFunction(format2) { + var array = format2.match(formattingTokens), i, length; + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); + } + } + return function(mom) { + var output = "", i2; + for (i2 = 0; i2 < length; i2++) { + output += isFunction2(array[i2]) ? array[i2].call(mom, format2) : array[i2]; + } + return output; + }; + } + function formatMoment(m2, format2) { + if (!m2.isValid()) { + return m2.localeData().invalidDate(); + } + format2 = expandFormat(format2, m2.localeData()); + formatFunctions[format2] = formatFunctions[format2] || makeFormatFunction(format2); + return formatFunctions[format2](m2); + } + function expandFormat(format2, locale2) { + var i = 5; + function replaceLongDateFormatTokens(input) { + return locale2.longDateFormat(input) || input; + } + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format2)) { + format2 = format2.replace( + localFormattingTokens, + replaceLongDateFormatTokens + ); + localFormattingTokens.lastIndex = 0; + i -= 1; + } + return format2; + } + var defaultLongDateFormat = { + LTS: "h:mm:ss A", + LT: "h:mm A", + L: "MM/DD/YYYY", + LL: "MMMM D, YYYY", + LLL: "MMMM D, YYYY h:mm A", + LLLL: "dddd, MMMM D, YYYY h:mm A" + }; + function longDateFormat(key) { + var format2 = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()]; + if (format2 || !formatUpper) { + return format2; + } + this._longDateFormat[key] = formatUpper.match(formattingTokens).map(function(tok) { + if (tok === "MMMM" || tok === "MM" || tok === "DD" || tok === "dddd") { + return tok.slice(1); + } + return tok; + }).join(""); + return this._longDateFormat[key]; + } + var defaultInvalidDate = "Invalid date"; + function invalidDate() { + return this._invalidDate; + } + var defaultOrdinal = "%d", defaultDayOfMonthOrdinalParse = /\d{1,2}/; + function ordinal(number) { + return this._ordinal.replace("%d", number); + } + var defaultRelativeTime = { + future: "in %s", + past: "%s ago", + s: "a few seconds", + ss: "%d seconds", + m: "a minute", + mm: "%d minutes", + h: "an hour", + hh: "%d hours", + d: "a day", + dd: "%d days", + w: "a week", + ww: "%d weeks", + M: "a month", + MM: "%d months", + y: "a year", + yy: "%d years" + }; + function relativeTime(number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return isFunction2(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); + } + function pastFuture(diff2, output) { + var format2 = this._relativeTime[diff2 > 0 ? "future" : "past"]; + return isFunction2(format2) ? format2(output) : format2.replace(/%s/i, output); + } + var aliases = { + D: "date", + dates: "date", + date: "date", + d: "day", + days: "day", + day: "day", + e: "weekday", + weekdays: "weekday", + weekday: "weekday", + E: "isoWeekday", + isoweekdays: "isoWeekday", + isoweekday: "isoWeekday", + DDD: "dayOfYear", + dayofyears: "dayOfYear", + dayofyear: "dayOfYear", + h: "hour", + hours: "hour", + hour: "hour", + ms: "millisecond", + milliseconds: "millisecond", + millisecond: "millisecond", + m: "minute", + minutes: "minute", + minute: "minute", + M: "month", + months: "month", + month: "month", + Q: "quarter", + quarters: "quarter", + quarter: "quarter", + s: "second", + seconds: "second", + second: "second", + gg: "weekYear", + weekyears: "weekYear", + weekyear: "weekYear", + GG: "isoWeekYear", + isoweekyears: "isoWeekYear", + isoweekyear: "isoWeekYear", + w: "week", + weeks: "week", + week: "week", + W: "isoWeek", + isoweeks: "isoWeek", + isoweek: "isoWeek", + y: "year", + years: "year", + year: "year" + }; + function normalizeUnits(units) { + return typeof units === "string" ? aliases[units] || aliases[units.toLowerCase()] : void 0; + } + function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, normalizedProp, prop; + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } + } + } + return normalizedInput; + } + var priorities = { + date: 9, + day: 11, + weekday: 11, + isoWeekday: 11, + dayOfYear: 4, + hour: 13, + millisecond: 16, + minute: 14, + month: 8, + quarter: 7, + second: 15, + weekYear: 1, + isoWeekYear: 1, + week: 5, + isoWeek: 5, + year: 1 + }; + function getPrioritizedUnits(unitsObj) { + var units = [], u; + for (u in unitsObj) { + if (hasOwnProp(unitsObj, u)) { + units.push({ unit: u, priority: priorities[u] }); + } + } + units.sort(function(a, b2) { + return a.priority - b2.priority; + }); + return units; + } + var match1 = /\d/, match2 = /\d\d/, match3 = /\d{3}/, match4 = /\d{4}/, match6 = /[+-]?\d{6}/, match1to2 = /\d\d?/, match3to4 = /\d\d\d\d?/, match5to6 = /\d\d\d\d\d\d?/, match1to3 = /\d{1,3}/, match1to4 = /\d{1,4}/, match1to6 = /[+-]?\d{1,6}/, matchUnsigned = /\d+/, matchSigned = /[+-]?\d+/, matchOffset = /Z|[+-]\d\d:?\d\d/gi, matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, match1to2NoLeadingZero = /^[1-9]\d?/, match1to2HasZero = /^([1-9]\d|\d)/, regexes; + regexes = {}; + function addRegexToken(token2, regex, strictRegex) { + regexes[token2] = isFunction2(regex) ? regex : function(isStrict, localeData2) { + return isStrict && strictRegex ? strictRegex : regex; + }; + } + function getParseRegexForToken(token2, config3) { + if (!hasOwnProp(regexes, token2)) { + return new RegExp(unescapeFormat(token2)); + } + return regexes[token2](config3._strict, config3._locale); + } + function unescapeFormat(s) { + return regexEscape( + s.replace("\\", "").replace( + /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, + function(matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + } + ) + ); + } + function regexEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); + } + function absFloor(number) { + if (number < 0) { + return Math.ceil(number) || 0; + } else { + return Math.floor(number); + } + } + function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, value = 0; + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + value = absFloor(coercedNumber); + } + return value; + } + var tokens = {}; + function addParseToken(token2, callback) { + var i, func = callback, tokenLen; + if (typeof token2 === "string") { + token2 = [token2]; + } + if (isNumber2(callback)) { + func = function(input, array) { + array[callback] = toInt(input); + }; + } + tokenLen = token2.length; + for (i = 0; i < tokenLen; i++) { + tokens[token2[i]] = func; + } + } + function addWeekParseToken(token2, callback) { + addParseToken(token2, function(input, array, config3, token3) { + config3._w = config3._w || {}; + callback(input, config3._w, config3, token3); + }); + } + function addTimeToArrayFromToken(token2, input, config3) { + if (input != null && hasOwnProp(tokens, token2)) { + tokens[token2](input, config3._a, config3, token2); + } + } + function isLeapYear(year) { + return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0; + } + var YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, WEEK = 7, WEEKDAY = 8; + addFormatToken("Y", 0, 0, function() { + var y2 = this.year(); + return y2 <= 9999 ? zeroFill(y2, 4) : "+" + y2; + }); + addFormatToken(0, ["YY", 2], 0, function() { + return this.year() % 100; + }); + addFormatToken(0, ["YYYY", 4], 0, "year"); + addFormatToken(0, ["YYYYY", 5], 0, "year"); + addFormatToken(0, ["YYYYYY", 6, true], 0, "year"); + addRegexToken("Y", matchSigned); + addRegexToken("YY", match1to2, match2); + addRegexToken("YYYY", match1to4, match4); + addRegexToken("YYYYY", match1to6, match6); + addRegexToken("YYYYYY", match1to6, match6); + addParseToken(["YYYYY", "YYYYYY"], YEAR); + addParseToken("YYYY", function(input, array) { + array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); + }); + addParseToken("YY", function(input, array) { + array[YEAR] = hooks.parseTwoDigitYear(input); + }); + addParseToken("Y", function(input, array) { + array[YEAR] = parseInt(input, 10); + }); + function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; + } + hooks.parseTwoDigitYear = function(input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2e3); + }; + var getSetYear = makeGetSet("FullYear", true); + function getIsLeapYear() { + return isLeapYear(this.year()); + } + function makeGetSet(unit, keepTime) { + return function(value) { + if (value != null) { + set$1(this, unit, value); + hooks.updateOffset(this, keepTime); + return this; + } else { + return get(this, unit); + } + }; + } + function get(mom, unit) { + if (!mom.isValid()) { + return NaN; + } + var d = mom._d, isUTC = mom._isUTC; + switch (unit) { + case "Milliseconds": + return isUTC ? d.getUTCMilliseconds() : d.getMilliseconds(); + case "Seconds": + return isUTC ? d.getUTCSeconds() : d.getSeconds(); + case "Minutes": + return isUTC ? d.getUTCMinutes() : d.getMinutes(); + case "Hours": + return isUTC ? d.getUTCHours() : d.getHours(); + case "Date": + return isUTC ? d.getUTCDate() : d.getDate(); + case "Day": + return isUTC ? d.getUTCDay() : d.getDay(); + case "Month": + return isUTC ? d.getUTCMonth() : d.getMonth(); + case "FullYear": + return isUTC ? d.getUTCFullYear() : d.getFullYear(); + default: + return NaN; + } + } + function set$1(mom, unit, value) { + var d, isUTC, year, month, date; + if (!mom.isValid() || isNaN(value)) { + return; + } + d = mom._d; + isUTC = mom._isUTC; + switch (unit) { + case "Milliseconds": + return void (isUTC ? d.setUTCMilliseconds(value) : d.setMilliseconds(value)); + case "Seconds": + return void (isUTC ? d.setUTCSeconds(value) : d.setSeconds(value)); + case "Minutes": + return void (isUTC ? d.setUTCMinutes(value) : d.setMinutes(value)); + case "Hours": + return void (isUTC ? d.setUTCHours(value) : d.setHours(value)); + case "Date": + return void (isUTC ? d.setUTCDate(value) : d.setDate(value)); + // case 'Day': // Not real + // return void (isUTC ? d.setUTCDay(value) : d.setDay(value)); + // case 'Month': // Not used because we need to pass two variables + // return void (isUTC ? d.setUTCMonth(value) : d.setMonth(value)); + case "FullYear": + break; + // See below ... + default: + return; + } + year = value; + month = mom.month(); + date = mom.date(); + date = date === 29 && month === 1 && !isLeapYear(year) ? 28 : date; + void (isUTC ? d.setUTCFullYear(year, month, date) : d.setFullYear(year, month, date)); + } + function stringGet(units) { + units = normalizeUnits(units); + if (isFunction2(this[units])) { + return this[units](); + } + return this; + } + function stringSet(units, value) { + if (typeof units === "object") { + units = normalizeObjectUnits(units); + var prioritized = getPrioritizedUnits(units), i, prioritizedLen = prioritized.length; + for (i = 0; i < prioritizedLen; i++) { + this[prioritized[i].unit](units[prioritized[i].unit]); + } + } else { + units = normalizeUnits(units); + if (isFunction2(this[units])) { + return this[units](value); + } + } + return this; + } + function mod2(n, x2) { + return (n % x2 + x2) % x2; + } + var indexOf; + if (Array.prototype.indexOf) { + indexOf = Array.prototype.indexOf; + } else { + indexOf = function(o) { + var i; + for (i = 0; i < this.length; ++i) { + if (this[i] === o) { + return i; + } + } + return -1; + }; + } + function daysInMonth(year, month) { + if (isNaN(year) || isNaN(month)) { + return NaN; + } + var modMonth = mod2(month, 12); + year += (month - modMonth) / 12; + return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2; + } + addFormatToken("M", ["MM", 2], "Mo", function() { + return this.month() + 1; + }); + addFormatToken("MMM", 0, 0, function(format2) { + return this.localeData().monthsShort(this, format2); + }); + addFormatToken("MMMM", 0, 0, function(format2) { + return this.localeData().months(this, format2); + }); + addRegexToken("M", match1to2, match1to2NoLeadingZero); + addRegexToken("MM", match1to2, match2); + addRegexToken("MMM", function(isStrict, locale2) { + return locale2.monthsShortRegex(isStrict); + }); + addRegexToken("MMMM", function(isStrict, locale2) { + return locale2.monthsRegex(isStrict); + }); + addParseToken(["M", "MM"], function(input, array) { + array[MONTH] = toInt(input) - 1; + }); + addParseToken(["MMM", "MMMM"], function(input, array, config3, token2) { + var month = config3._locale.monthsParse(input, token2, config3._strict); + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config3).invalidMonth = input; + } + }); + var defaultLocaleMonths = "January_February_March_April_May_June_July_August_September_October_November_December".split( + "_" + ), defaultLocaleMonthsShort = "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, defaultMonthsShortRegex = matchWord, defaultMonthsRegex = matchWord; + function localeMonths(m2, format2) { + if (!m2) { + return isArray2(this._months) ? this._months : this._months["standalone"]; + } + return isArray2(this._months) ? this._months[m2.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format2) ? "format" : "standalone"][m2.month()]; + } + function localeMonthsShort(m2, format2) { + if (!m2) { + return isArray2(this._monthsShort) ? this._monthsShort : this._monthsShort["standalone"]; + } + return isArray2(this._monthsShort) ? this._monthsShort[m2.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format2) ? "format" : "standalone"][m2.month()]; + } + function handleStrictParse(monthName, format2, strict) { + var i, ii2, mom, llc = monthName.toLocaleLowerCase(); + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + for (i = 0; i < 12; ++i) { + mom = createUTC([2e3, i]); + this._shortMonthsParse[i] = this.monthsShort( + mom, + "" + ).toLocaleLowerCase(); + this._longMonthsParse[i] = this.months(mom, "").toLocaleLowerCase(); + } + } + if (strict) { + if (format2 === "MMM") { + ii2 = indexOf.call(this._shortMonthsParse, llc); + return ii2 !== -1 ? ii2 : null; + } else { + ii2 = indexOf.call(this._longMonthsParse, llc); + return ii2 !== -1 ? ii2 : null; + } + } else { + if (format2 === "MMM") { + ii2 = indexOf.call(this._shortMonthsParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._longMonthsParse, llc); + return ii2 !== -1 ? ii2 : null; + } else { + ii2 = indexOf.call(this._longMonthsParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._shortMonthsParse, llc); + return ii2 !== -1 ? ii2 : null; + } + } + } + function localeMonthsParse(monthName, format2, strict) { + var i, mom, regex; + if (this._monthsParseExact) { + return handleStrictParse.call(this, monthName, format2, strict); + } + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } + for (i = 0; i < 12; i++) { + mom = createUTC([2e3, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp( + "^" + this.months(mom, "").replace(".", "") + "$", + "i" + ); + this._shortMonthsParse[i] = new RegExp( + "^" + this.monthsShort(mom, "").replace(".", "") + "$", + "i" + ); + } + if (!strict && !this._monthsParse[i]) { + regex = "^" + this.months(mom, "") + "|^" + this.monthsShort(mom, ""); + this._monthsParse[i] = new RegExp(regex.replace(".", ""), "i"); + } + if (strict && format2 === "MMMM" && this._longMonthsParse[i].test(monthName)) { + return i; + } else if (strict && format2 === "MMM" && this._shortMonthsParse[i].test(monthName)) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } + } + function setMonth(mom, value) { + if (!mom.isValid()) { + return mom; + } + if (typeof value === "string") { + if (/^\d+$/.test(value)) { + value = toInt(value); + } else { + value = mom.localeData().monthsParse(value); + if (!isNumber2(value)) { + return mom; + } + } + } + var month = value, date = mom.date(); + date = date < 29 ? date : Math.min(date, daysInMonth(mom.year(), month)); + void (mom._isUTC ? mom._d.setUTCMonth(month, date) : mom._d.setMonth(month, date)); + return mom; + } + function getSetMonth(value) { + if (value != null) { + setMonth(this, value); + hooks.updateOffset(this, true); + return this; + } else { + return get(this, "Month"); + } + } + function getDaysInMonth() { + return daysInMonth(this.year(), this.month()); + } + function monthsShortRegex(isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, "_monthsRegex")) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsShortStrictRegex; + } else { + return this._monthsShortRegex; + } + } else { + if (!hasOwnProp(this, "_monthsShortRegex")) { + this._monthsShortRegex = defaultMonthsShortRegex; + } + return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex; + } + } + function monthsRegex(isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, "_monthsRegex")) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsStrictRegex; + } else { + return this._monthsRegex; + } + } else { + if (!hasOwnProp(this, "_monthsRegex")) { + this._monthsRegex = defaultMonthsRegex; + } + return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex; + } + } + function computeMonthsParse() { + function cmpLenRev(a, b2) { + return b2.length - a.length; + } + var shortPieces = [], longPieces = [], mixedPieces = [], i, mom, shortP, longP; + for (i = 0; i < 12; i++) { + mom = createUTC([2e3, i]); + shortP = regexEscape(this.monthsShort(mom, "")); + longP = regexEscape(this.months(mom, "")); + shortPieces.push(shortP); + longPieces.push(longP); + mixedPieces.push(longP); + mixedPieces.push(shortP); + } + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + this._monthsRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); + this._monthsShortRegex = this._monthsRegex; + this._monthsStrictRegex = new RegExp( + "^(" + longPieces.join("|") + ")", + "i" + ); + this._monthsShortStrictRegex = new RegExp( + "^(" + shortPieces.join("|") + ")", + "i" + ); + } + function createDate(y2, m2, d, h, M2, s, ms) { + var date; + if (y2 < 100 && y2 >= 0) { + date = new Date(y2 + 400, m2, d, h, M2, s, ms); + if (isFinite(date.getFullYear())) { + date.setFullYear(y2); + } + } else { + date = new Date(y2, m2, d, h, M2, s, ms); + } + return date; + } + function createUTCDate(y2) { + var date, args; + if (y2 < 100 && y2 >= 0) { + args = Array.prototype.slice.call(arguments); + args[0] = y2 + 400; + date = new Date(Date.UTC.apply(null, args)); + if (isFinite(date.getUTCFullYear())) { + date.setUTCFullYear(y2); + } + } else { + date = new Date(Date.UTC.apply(null, arguments)); + } + return date; + } + function firstWeekOffset(year, dow, doy) { + var fwd = 7 + dow - doy, fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; + return -fwdlw + fwd - 1; + } + function dayOfYearFromWeeks(year, week, weekday, dow, doy) { + var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear; + if (dayOfYear <= 0) { + resYear = year - 1; + resDayOfYear = daysInYear(resYear) + dayOfYear; + } else if (dayOfYear > daysInYear(year)) { + resYear = year + 1; + resDayOfYear = dayOfYear - daysInYear(year); + } else { + resYear = year; + resDayOfYear = dayOfYear; + } + return { + year: resYear, + dayOfYear: resDayOfYear + }; + } + function weekOfYear(mom, dow, doy) { + var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear; + if (week < 1) { + resYear = mom.year() - 1; + resWeek = week + weeksInYear(resYear, dow, doy); + } else if (week > weeksInYear(mom.year(), dow, doy)) { + resWeek = week - weeksInYear(mom.year(), dow, doy); + resYear = mom.year() + 1; + } else { + resYear = mom.year(); + resWeek = week; + } + return { + week: resWeek, + year: resYear + }; + } + function weeksInYear(year, dow, doy) { + var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy); + return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; + } + addFormatToken("w", ["ww", 2], "wo", "week"); + addFormatToken("W", ["WW", 2], "Wo", "isoWeek"); + addRegexToken("w", match1to2, match1to2NoLeadingZero); + addRegexToken("ww", match1to2, match2); + addRegexToken("W", match1to2, match1to2NoLeadingZero); + addRegexToken("WW", match1to2, match2); + addWeekParseToken( + ["w", "ww", "W", "WW"], + function(input, week, config3, token2) { + week[token2.substr(0, 1)] = toInt(input); + } + ); + function localeWeek(mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; + } + var defaultLocaleWeek = { + dow: 0, + // Sunday is the first day of the week. + doy: 6 + // The week that contains Jan 6th is the first week of the year. + }; + function localeFirstDayOfWeek() { + return this._week.dow; + } + function localeFirstDayOfYear() { + return this._week.doy; + } + function getSetWeek(input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, "d"); + } + function getSetISOWeek(input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, "d"); + } + addFormatToken("d", 0, "do", "day"); + addFormatToken("dd", 0, 0, function(format2) { + return this.localeData().weekdaysMin(this, format2); + }); + addFormatToken("ddd", 0, 0, function(format2) { + return this.localeData().weekdaysShort(this, format2); + }); + addFormatToken("dddd", 0, 0, function(format2) { + return this.localeData().weekdays(this, format2); + }); + addFormatToken("e", 0, 0, "weekday"); + addFormatToken("E", 0, 0, "isoWeekday"); + addRegexToken("d", match1to2); + addRegexToken("e", match1to2); + addRegexToken("E", match1to2); + addRegexToken("dd", function(isStrict, locale2) { + return locale2.weekdaysMinRegex(isStrict); + }); + addRegexToken("ddd", function(isStrict, locale2) { + return locale2.weekdaysShortRegex(isStrict); + }); + addRegexToken("dddd", function(isStrict, locale2) { + return locale2.weekdaysRegex(isStrict); + }); + addWeekParseToken(["dd", "ddd", "dddd"], function(input, week, config3, token2) { + var weekday = config3._locale.weekdaysParse(input, token2, config3._strict); + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config3).invalidWeekday = input; + } + }); + addWeekParseToken(["d", "e", "E"], function(input, week, config3, token2) { + week[token2] = toInt(input); + }); + function parseWeekday(input, locale2) { + if (typeof input !== "string") { + return input; + } + if (!isNaN(input)) { + return parseInt(input, 10); + } + input = locale2.weekdaysParse(input); + if (typeof input === "number") { + return input; + } + return null; + } + function parseIsoWeekday(input, locale2) { + if (typeof input === "string") { + return locale2.weekdaysParse(input) % 7 || 7; + } + return isNaN(input) ? null : input; + } + function shiftWeekdays(ws2, n) { + return ws2.slice(n, 7).concat(ws2.slice(0, n)); + } + var defaultLocaleWeekdays = "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), defaultLocaleWeekdaysShort = "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), defaultLocaleWeekdaysMin = "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), defaultWeekdaysRegex = matchWord, defaultWeekdaysShortRegex = matchWord, defaultWeekdaysMinRegex = matchWord; + function localeWeekdays(m2, format2) { + var weekdays = isArray2(this._weekdays) ? this._weekdays : this._weekdays[m2 && m2 !== true && this._weekdays.isFormat.test(format2) ? "format" : "standalone"]; + return m2 === true ? shiftWeekdays(weekdays, this._week.dow) : m2 ? weekdays[m2.day()] : weekdays; + } + function localeWeekdaysShort(m2) { + return m2 === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m2 ? this._weekdaysShort[m2.day()] : this._weekdaysShort; + } + function localeWeekdaysMin(m2) { + return m2 === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m2 ? this._weekdaysMin[m2.day()] : this._weekdaysMin; + } + function handleStrictParse$1(weekdayName, format2, strict) { + var i, ii2, mom, llc = weekdayName.toLocaleLowerCase(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._shortWeekdaysParse = []; + this._minWeekdaysParse = []; + for (i = 0; i < 7; ++i) { + mom = createUTC([2e3, 1]).day(i); + this._minWeekdaysParse[i] = this.weekdaysMin( + mom, + "" + ).toLocaleLowerCase(); + this._shortWeekdaysParse[i] = this.weekdaysShort( + mom, + "" + ).toLocaleLowerCase(); + this._weekdaysParse[i] = this.weekdays(mom, "").toLocaleLowerCase(); + } + } + if (strict) { + if (format2 === "dddd") { + ii2 = indexOf.call(this._weekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } else if (format2 === "ddd") { + ii2 = indexOf.call(this._shortWeekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } else { + ii2 = indexOf.call(this._minWeekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } + } else { + if (format2 === "dddd") { + ii2 = indexOf.call(this._weekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._shortWeekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._minWeekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } else if (format2 === "ddd") { + ii2 = indexOf.call(this._shortWeekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._weekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._minWeekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } else { + ii2 = indexOf.call(this._minWeekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._weekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._shortWeekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } + } + } + function localeWeekdaysParse(weekdayName, format2, strict) { + var i, mom, regex; + if (this._weekdaysParseExact) { + return handleStrictParse$1.call(this, weekdayName, format2, strict); + } + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._minWeekdaysParse = []; + this._shortWeekdaysParse = []; + this._fullWeekdaysParse = []; + } + for (i = 0; i < 7; i++) { + mom = createUTC([2e3, 1]).day(i); + if (strict && !this._fullWeekdaysParse[i]) { + this._fullWeekdaysParse[i] = new RegExp( + "^" + this.weekdays(mom, "").replace(".", "\\.?") + "$", + "i" + ); + this._shortWeekdaysParse[i] = new RegExp( + "^" + this.weekdaysShort(mom, "").replace(".", "\\.?") + "$", + "i" + ); + this._minWeekdaysParse[i] = new RegExp( + "^" + this.weekdaysMin(mom, "").replace(".", "\\.?") + "$", + "i" + ); + } + if (!this._weekdaysParse[i]) { + regex = "^" + this.weekdays(mom, "") + "|^" + this.weekdaysShort(mom, "") + "|^" + this.weekdaysMin(mom, ""); + this._weekdaysParse[i] = new RegExp(regex.replace(".", ""), "i"); + } + if (strict && format2 === "dddd" && this._fullWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format2 === "ddd" && this._shortWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format2 === "dd" && this._minWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { + return i; + } + } + } + function getSetDayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var day = get(this, "Day"); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, "d"); + } else { + return day; + } + } + function getSetLocaleDayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, "d"); + } + function getSetISODayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + var weekday = parseIsoWeekday(input, this.localeData()); + return this.day(this.day() % 7 ? weekday : weekday - 7); + } else { + return this.day() || 7; + } + } + function weekdaysRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, "_weekdaysRegex")) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysStrictRegex; + } else { + return this._weekdaysRegex; + } + } else { + if (!hasOwnProp(this, "_weekdaysRegex")) { + this._weekdaysRegex = defaultWeekdaysRegex; + } + return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; + } + } + function weekdaysShortRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, "_weekdaysRegex")) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysShortStrictRegex; + } else { + return this._weekdaysShortRegex; + } + } else { + if (!hasOwnProp(this, "_weekdaysShortRegex")) { + this._weekdaysShortRegex = defaultWeekdaysShortRegex; + } + return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; + } + } + function weekdaysMinRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, "_weekdaysRegex")) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysMinStrictRegex; + } else { + return this._weekdaysMinRegex; + } + } else { + if (!hasOwnProp(this, "_weekdaysMinRegex")) { + this._weekdaysMinRegex = defaultWeekdaysMinRegex; + } + return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; + } + } + function computeWeekdaysParse() { + function cmpLenRev(a, b2) { + return b2.length - a.length; + } + var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; + for (i = 0; i < 7; i++) { + mom = createUTC([2e3, 1]).day(i); + minp = regexEscape(this.weekdaysMin(mom, "")); + shortp = regexEscape(this.weekdaysShort(mom, "")); + longp = regexEscape(this.weekdays(mom, "")); + minPieces.push(minp); + shortPieces.push(shortp); + longPieces.push(longp); + mixedPieces.push(minp); + mixedPieces.push(shortp); + mixedPieces.push(longp); + } + minPieces.sort(cmpLenRev); + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + this._weekdaysRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); + this._weekdaysShortRegex = this._weekdaysRegex; + this._weekdaysMinRegex = this._weekdaysRegex; + this._weekdaysStrictRegex = new RegExp( + "^(" + longPieces.join("|") + ")", + "i" + ); + this._weekdaysShortStrictRegex = new RegExp( + "^(" + shortPieces.join("|") + ")", + "i" + ); + this._weekdaysMinStrictRegex = new RegExp( + "^(" + minPieces.join("|") + ")", + "i" + ); + } + function hFormat() { + return this.hours() % 12 || 12; + } + function kFormat() { + return this.hours() || 24; + } + addFormatToken("H", ["HH", 2], 0, "hour"); + addFormatToken("h", ["hh", 2], 0, hFormat); + addFormatToken("k", ["kk", 2], 0, kFormat); + addFormatToken("hmm", 0, 0, function() { + return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2); + }); + addFormatToken("hmmss", 0, 0, function() { + return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); + }); + addFormatToken("Hmm", 0, 0, function() { + return "" + this.hours() + zeroFill(this.minutes(), 2); + }); + addFormatToken("Hmmss", 0, 0, function() { + return "" + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); + }); + function meridiem(token2, lowercase) { + addFormatToken(token2, 0, 0, function() { + return this.localeData().meridiem( + this.hours(), + this.minutes(), + lowercase + ); + }); + } + meridiem("a", true); + meridiem("A", false); + function matchMeridiem(isStrict, locale2) { + return locale2._meridiemParse; + } + addRegexToken("a", matchMeridiem); + addRegexToken("A", matchMeridiem); + addRegexToken("H", match1to2, match1to2HasZero); + addRegexToken("h", match1to2, match1to2NoLeadingZero); + addRegexToken("k", match1to2, match1to2NoLeadingZero); + addRegexToken("HH", match1to2, match2); + addRegexToken("hh", match1to2, match2); + addRegexToken("kk", match1to2, match2); + addRegexToken("hmm", match3to4); + addRegexToken("hmmss", match5to6); + addRegexToken("Hmm", match3to4); + addRegexToken("Hmmss", match5to6); + addParseToken(["H", "HH"], HOUR); + addParseToken(["k", "kk"], function(input, array, config3) { + var kInput = toInt(input); + array[HOUR] = kInput === 24 ? 0 : kInput; + }); + addParseToken(["a", "A"], function(input, array, config3) { + config3._isPm = config3._locale.isPM(input); + config3._meridiem = input; + }); + addParseToken(["h", "hh"], function(input, array, config3) { + array[HOUR] = toInt(input); + getParsingFlags(config3).bigHour = true; + }); + addParseToken("hmm", function(input, array, config3) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + getParsingFlags(config3).bigHour = true; + }); + addParseToken("hmmss", function(input, array, config3) { + var pos1 = input.length - 4, pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + getParsingFlags(config3).bigHour = true; + }); + addParseToken("Hmm", function(input, array, config3) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + }); + addParseToken("Hmmss", function(input, array, config3) { + var pos1 = input.length - 4, pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + }); + function localeIsPM(input) { + return (input + "").toLowerCase().charAt(0) === "p"; + } + var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, getSetHour = makeGetSet("Hours", true); + function localeMeridiem(hours2, minutes2, isLower) { + if (hours2 > 11) { + return isLower ? "pm" : "PM"; + } else { + return isLower ? "am" : "AM"; + } + } + var baseConfig = { + calendar: defaultCalendar, + longDateFormat: defaultLongDateFormat, + invalidDate: defaultInvalidDate, + ordinal: defaultOrdinal, + dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, + relativeTime: defaultRelativeTime, + months: defaultLocaleMonths, + monthsShort: defaultLocaleMonthsShort, + week: defaultLocaleWeek, + weekdays: defaultLocaleWeekdays, + weekdaysMin: defaultLocaleWeekdaysMin, + weekdaysShort: defaultLocaleWeekdaysShort, + meridiemParse: defaultLocaleMeridiemParse + }; + var locales = {}, localeFamilies = {}, globalLocale; + function commonPrefix(arr1, arr2) { + var i, minl = Math.min(arr1.length, arr2.length); + for (i = 0; i < minl; i += 1) { + if (arr1[i] !== arr2[i]) { + return i; + } + } + return minl; + } + function normalizeLocale(key) { + return key ? key.toLowerCase().replace("_", "-") : key; + } + function chooseLocale(names) { + var i = 0, j2, next, locale2, split3; + while (i < names.length) { + split3 = normalizeLocale(names[i]).split("-"); + j2 = split3.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split("-") : null; + while (j2 > 0) { + locale2 = loadLocale(split3.slice(0, j2).join("-")); + if (locale2) { + return locale2; + } + if (next && next.length >= j2 && commonPrefix(split3, next) >= j2 - 1) { + break; + } + j2--; + } + i++; + } + return globalLocale; + } + function isLocaleNameSane(name) { + return !!(name && name.match("^[^/\\\\]*$")); + } + function loadLocale(name) { + var oldLocale = null, aliasedRequire; + if (locales[name] === void 0 && typeof module2 !== "undefined" && module2 && module2.exports && isLocaleNameSane(name)) { + try { + oldLocale = globalLocale._abbr; + aliasedRequire = __require; + aliasedRequire("./locale/" + name); + getSetGlobalLocale(oldLocale); + } catch (e) { + locales[name] = null; + } + } + return locales[name]; + } + function getSetGlobalLocale(key, values) { + var data; + if (key) { + if (isUndefined2(values)) { + data = getLocale(key); + } else { + data = defineLocale(key, values); + } + if (data) { + globalLocale = data; + } else { + if (typeof console !== "undefined" && console.warn) { + console.warn( + "Locale " + key + " not found. Did you forget to load it?" + ); + } + } + } + return globalLocale._abbr; + } + function defineLocale(name, config3) { + if (config3 !== null) { + var locale2, parentConfig = baseConfig; + config3.abbr = name; + if (locales[name] != null) { + deprecateSimple( + "defineLocaleOverride", + "use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info." + ); + parentConfig = locales[name]._config; + } else if (config3.parentLocale != null) { + if (locales[config3.parentLocale] != null) { + parentConfig = locales[config3.parentLocale]._config; + } else { + locale2 = loadLocale(config3.parentLocale); + if (locale2 != null) { + parentConfig = locale2._config; + } else { + if (!localeFamilies[config3.parentLocale]) { + localeFamilies[config3.parentLocale] = []; + } + localeFamilies[config3.parentLocale].push({ + name, + config: config3 + }); + return null; + } + } + } + locales[name] = new Locale(mergeConfigs(parentConfig, config3)); + if (localeFamilies[name]) { + localeFamilies[name].forEach(function(x2) { + defineLocale(x2.name, x2.config); + }); + } + getSetGlobalLocale(name); + return locales[name]; + } else { + delete locales[name]; + return null; + } + } + function updateLocale(name, config3) { + if (config3 != null) { + var locale2, tmpLocale, parentConfig = baseConfig; + if (locales[name] != null && locales[name].parentLocale != null) { + locales[name].set(mergeConfigs(locales[name]._config, config3)); + } else { + tmpLocale = loadLocale(name); + if (tmpLocale != null) { + parentConfig = tmpLocale._config; + } + config3 = mergeConfigs(parentConfig, config3); + if (tmpLocale == null) { + config3.abbr = name; + } + locale2 = new Locale(config3); + locale2.parentLocale = locales[name]; + locales[name] = locale2; + } + getSetGlobalLocale(name); + } else { + if (locales[name] != null) { + if (locales[name].parentLocale != null) { + locales[name] = locales[name].parentLocale; + if (name === getSetGlobalLocale()) { + getSetGlobalLocale(name); + } + } else if (locales[name] != null) { + delete locales[name]; + } + } + } + return locales[name]; + } + function getLocale(key) { + var locale2; + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } + if (!key) { + return globalLocale; + } + if (!isArray2(key)) { + locale2 = loadLocale(key); + if (locale2) { + return locale2; + } + key = [key]; + } + return chooseLocale(key); + } + function listLocales() { + return keys(locales); + } + function checkOverflow(m2) { + var overflow, a = m2._a; + if (a && getParsingFlags(m2).overflow === -2) { + overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1; + if (getParsingFlags(m2)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { + overflow = DATE; + } + if (getParsingFlags(m2)._overflowWeeks && overflow === -1) { + overflow = WEEK; + } + if (getParsingFlags(m2)._overflowWeekday && overflow === -1) { + overflow = WEEKDAY; + } + getParsingFlags(m2).overflow = overflow; + } + return m2; + } + var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, isoDates = [ + ["YYYYYY-MM-DD", /[+-]\d{6}-\d\d-\d\d/], + ["YYYY-MM-DD", /\d{4}-\d\d-\d\d/], + ["GGGG-[W]WW-E", /\d{4}-W\d\d-\d/], + ["GGGG-[W]WW", /\d{4}-W\d\d/, false], + ["YYYY-DDD", /\d{4}-\d{3}/], + ["YYYY-MM", /\d{4}-\d\d/, false], + ["YYYYYYMMDD", /[+-]\d{10}/], + ["YYYYMMDD", /\d{8}/], + ["GGGG[W]WWE", /\d{4}W\d{3}/], + ["GGGG[W]WW", /\d{4}W\d{2}/, false], + ["YYYYDDD", /\d{7}/], + ["YYYYMM", /\d{6}/, false], + ["YYYY", /\d{4}/, false] + ], isoTimes = [ + ["HH:mm:ss.SSSS", /\d\d:\d\d:\d\d\.\d+/], + ["HH:mm:ss,SSSS", /\d\d:\d\d:\d\d,\d+/], + ["HH:mm:ss", /\d\d:\d\d:\d\d/], + ["HH:mm", /\d\d:\d\d/], + ["HHmmss.SSSS", /\d\d\d\d\d\d\.\d+/], + ["HHmmss,SSSS", /\d\d\d\d\d\d,\d+/], + ["HHmmss", /\d\d\d\d\d\d/], + ["HHmm", /\d\d\d\d/], + ["HH", /\d\d/] + ], aspNetJsonRegex = /^\/?Date\((-?\d+)/i, rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, obsOffsets = { + UT: 0, + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60 + }; + function configFromISO(config3) { + var i, l, string = config3._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat, isoDatesLen = isoDates.length, isoTimesLen = isoTimes.length; + if (match) { + getParsingFlags(config3).iso = true; + for (i = 0, l = isoDatesLen; i < l; i++) { + if (isoDates[i][1].exec(match[1])) { + dateFormat = isoDates[i][0]; + allowTime = isoDates[i][2] !== false; + break; + } + } + if (dateFormat == null) { + config3._isValid = false; + return; + } + if (match[3]) { + for (i = 0, l = isoTimesLen; i < l; i++) { + if (isoTimes[i][1].exec(match[3])) { + timeFormat = (match[2] || " ") + isoTimes[i][0]; + break; + } + } + if (timeFormat == null) { + config3._isValid = false; + return; + } + } + if (!allowTime && timeFormat != null) { + config3._isValid = false; + return; + } + if (match[4]) { + if (tzRegex.exec(match[4])) { + tzFormat = "Z"; + } else { + config3._isValid = false; + return; + } + } + config3._f = dateFormat + (timeFormat || "") + (tzFormat || ""); + configFromStringAndFormat(config3); + } else { + config3._isValid = false; + } + } + function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { + var result = [ + untruncateYear(yearStr), + defaultLocaleMonthsShort.indexOf(monthStr), + parseInt(dayStr, 10), + parseInt(hourStr, 10), + parseInt(minuteStr, 10) + ]; + if (secondStr) { + result.push(parseInt(secondStr, 10)); + } + return result; + } + function untruncateYear(yearStr) { + var year = parseInt(yearStr, 10); + if (year <= 49) { + return 2e3 + year; + } else if (year <= 999) { + return 1900 + year; + } + return year; + } + function preprocessRFC2822(s) { + return s.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").replace(/^\s\s*/, "").replace(/\s\s*$/, ""); + } + function checkWeekday(weekdayStr, parsedInput, config3) { + if (weekdayStr) { + var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), weekdayActual = new Date( + parsedInput[0], + parsedInput[1], + parsedInput[2] + ).getDay(); + if (weekdayProvided !== weekdayActual) { + getParsingFlags(config3).weekdayMismatch = true; + config3._isValid = false; + return false; + } + } + return true; + } + function calculateOffset(obsOffset, militaryOffset, numOffset) { + if (obsOffset) { + return obsOffsets[obsOffset]; + } else if (militaryOffset) { + return 0; + } else { + var hm2 = parseInt(numOffset, 10), m2 = hm2 % 100, h = (hm2 - m2) / 100; + return h * 60 + m2; + } + } + function configFromRFC2822(config3) { + var match = rfc2822.exec(preprocessRFC2822(config3._i)), parsedArray; + if (match) { + parsedArray = extractFromRFC2822Strings( + match[4], + match[3], + match[2], + match[5], + match[6], + match[7] + ); + if (!checkWeekday(match[1], parsedArray, config3)) { + return; + } + config3._a = parsedArray; + config3._tzm = calculateOffset(match[8], match[9], match[10]); + config3._d = createUTCDate.apply(null, config3._a); + config3._d.setUTCMinutes(config3._d.getUTCMinutes() - config3._tzm); + getParsingFlags(config3).rfc2822 = true; + } else { + config3._isValid = false; + } + } + function configFromString(config3) { + var matched = aspNetJsonRegex.exec(config3._i); + if (matched !== null) { + config3._d = /* @__PURE__ */ new Date(+matched[1]); + return; + } + configFromISO(config3); + if (config3._isValid === false) { + delete config3._isValid; + } else { + return; + } + configFromRFC2822(config3); + if (config3._isValid === false) { + delete config3._isValid; + } else { + return; + } + if (config3._strict) { + config3._isValid = false; + } else { + hooks.createFromInputFallback(config3); + } + } + hooks.createFromInputFallback = deprecate( + "value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.", + function(config3) { + config3._d = /* @__PURE__ */ new Date(config3._i + (config3._useUTC ? " UTC" : "")); + } + ); + function defaults2(a, b2, c) { + if (a != null) { + return a; + } + if (b2 != null) { + return b2; + } + return c; + } + function currentDateArray(config3) { + var nowValue = new Date(hooks.now()); + if (config3._useUTC) { + return [ + nowValue.getUTCFullYear(), + nowValue.getUTCMonth(), + nowValue.getUTCDate() + ]; + } + return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; + } + function configFromArray(config3) { + var i, date, input = [], currentDate, expectedWeekday, yearToUse; + if (config3._d) { + return; + } + currentDate = currentDateArray(config3); + if (config3._w && config3._a[DATE] == null && config3._a[MONTH] == null) { + dayOfYearFromWeekInfo(config3); + } + if (config3._dayOfYear != null) { + yearToUse = defaults2(config3._a[YEAR], currentDate[YEAR]); + if (config3._dayOfYear > daysInYear(yearToUse) || config3._dayOfYear === 0) { + getParsingFlags(config3)._overflowDayOfYear = true; + } + date = createUTCDate(yearToUse, 0, config3._dayOfYear); + config3._a[MONTH] = date.getUTCMonth(); + config3._a[DATE] = date.getUTCDate(); + } + for (i = 0; i < 3 && config3._a[i] == null; ++i) { + config3._a[i] = input[i] = currentDate[i]; + } + for (; i < 7; i++) { + config3._a[i] = input[i] = config3._a[i] == null ? i === 2 ? 1 : 0 : config3._a[i]; + } + if (config3._a[HOUR] === 24 && config3._a[MINUTE] === 0 && config3._a[SECOND] === 0 && config3._a[MILLISECOND] === 0) { + config3._nextDay = true; + config3._a[HOUR] = 0; + } + config3._d = (config3._useUTC ? createUTCDate : createDate).apply( + null, + input + ); + expectedWeekday = config3._useUTC ? config3._d.getUTCDay() : config3._d.getDay(); + if (config3._tzm != null) { + config3._d.setUTCMinutes(config3._d.getUTCMinutes() - config3._tzm); + } + if (config3._nextDay) { + config3._a[HOUR] = 24; + } + if (config3._w && typeof config3._w.d !== "undefined" && config3._w.d !== expectedWeekday) { + getParsingFlags(config3).weekdayMismatch = true; + } + } + function dayOfYearFromWeekInfo(config3) { + var w2, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; + w2 = config3._w; + if (w2.GG != null || w2.W != null || w2.E != null) { + dow = 1; + doy = 4; + weekYear = defaults2( + w2.GG, + config3._a[YEAR], + weekOfYear(createLocal(), 1, 4).year + ); + week = defaults2(w2.W, 1); + weekday = defaults2(w2.E, 1); + if (weekday < 1 || weekday > 7) { + weekdayOverflow = true; + } + } else { + dow = config3._locale._week.dow; + doy = config3._locale._week.doy; + curWeek = weekOfYear(createLocal(), dow, doy); + weekYear = defaults2(w2.gg, config3._a[YEAR], curWeek.year); + week = defaults2(w2.w, curWeek.week); + if (w2.d != null) { + weekday = w2.d; + if (weekday < 0 || weekday > 6) { + weekdayOverflow = true; + } + } else if (w2.e != null) { + weekday = w2.e + dow; + if (w2.e < 0 || w2.e > 6) { + weekdayOverflow = true; + } + } else { + weekday = dow; + } + } + if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { + getParsingFlags(config3)._overflowWeeks = true; + } else if (weekdayOverflow != null) { + getParsingFlags(config3)._overflowWeekday = true; + } else { + temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); + config3._a[YEAR] = temp.year; + config3._dayOfYear = temp.dayOfYear; + } + } + hooks.ISO_8601 = function() { + }; + hooks.RFC_2822 = function() { + }; + function configFromStringAndFormat(config3) { + if (config3._f === hooks.ISO_8601) { + configFromISO(config3); + return; + } + if (config3._f === hooks.RFC_2822) { + configFromRFC2822(config3); + return; + } + config3._a = []; + getParsingFlags(config3).empty = true; + var string = "" + config3._i, i, parsedInput, tokens2, token2, skipped, stringLength = string.length, totalParsedInputLength = 0, era, tokenLen; + tokens2 = expandFormat(config3._f, config3._locale).match(formattingTokens) || []; + tokenLen = tokens2.length; + for (i = 0; i < tokenLen; i++) { + token2 = tokens2[i]; + parsedInput = (string.match(getParseRegexForToken(token2, config3)) || [])[0]; + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config3).unusedInput.push(skipped); + } + string = string.slice( + string.indexOf(parsedInput) + parsedInput.length + ); + totalParsedInputLength += parsedInput.length; + } + if (formatTokenFunctions[token2]) { + if (parsedInput) { + getParsingFlags(config3).empty = false; + } else { + getParsingFlags(config3).unusedTokens.push(token2); + } + addTimeToArrayFromToken(token2, parsedInput, config3); + } else if (config3._strict && !parsedInput) { + getParsingFlags(config3).unusedTokens.push(token2); + } + } + getParsingFlags(config3).charsLeftOver = stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config3).unusedInput.push(string); + } + if (config3._a[HOUR] <= 12 && getParsingFlags(config3).bigHour === true && config3._a[HOUR] > 0) { + getParsingFlags(config3).bigHour = void 0; + } + getParsingFlags(config3).parsedDateParts = config3._a.slice(0); + getParsingFlags(config3).meridiem = config3._meridiem; + config3._a[HOUR] = meridiemFixWrap( + config3._locale, + config3._a[HOUR], + config3._meridiem + ); + era = getParsingFlags(config3).era; + if (era !== null) { + config3._a[YEAR] = config3._locale.erasConvertYear(era, config3._a[YEAR]); + } + configFromArray(config3); + checkOverflow(config3); + } + function meridiemFixWrap(locale2, hour, meridiem2) { + var isPm; + if (meridiem2 == null) { + return hour; + } + if (locale2.meridiemHour != null) { + return locale2.meridiemHour(hour, meridiem2); + } else if (locale2.isPM != null) { + isPm = locale2.isPM(meridiem2); + if (isPm && hour < 12) { + hour += 12; + } + if (!isPm && hour === 12) { + hour = 0; + } + return hour; + } else { + return hour; + } + } + function configFromStringAndArray(config3) { + var tempConfig, bestMoment, scoreToBeat, i, currentScore, validFormatFound, bestFormatIsValid = false, configfLen = config3._f.length; + if (configfLen === 0) { + getParsingFlags(config3).invalidFormat = true; + config3._d = /* @__PURE__ */ new Date(NaN); + return; + } + for (i = 0; i < configfLen; i++) { + currentScore = 0; + validFormatFound = false; + tempConfig = copyConfig({}, config3); + if (config3._useUTC != null) { + tempConfig._useUTC = config3._useUTC; + } + tempConfig._f = config3._f[i]; + configFromStringAndFormat(tempConfig); + if (isValid(tempConfig)) { + validFormatFound = true; + } + currentScore += getParsingFlags(tempConfig).charsLeftOver; + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + getParsingFlags(tempConfig).score = currentScore; + if (!bestFormatIsValid) { + if (scoreToBeat == null || currentScore < scoreToBeat || validFormatFound) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + if (validFormatFound) { + bestFormatIsValid = true; + } + } + } else { + if (currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } + } + } + extend2(config3, bestMoment || tempConfig); + } + function configFromObject(config3) { + if (config3._d) { + return; + } + var i = normalizeObjectUnits(config3._i), dayOrDate = i.day === void 0 ? i.date : i.day; + config3._a = map( + [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], + function(obj) { + return obj && parseInt(obj, 10); + } + ); + configFromArray(config3); + } + function createFromConfig(config3) { + var res = new Moment(checkOverflow(prepareConfig(config3))); + if (res._nextDay) { + res.add(1, "d"); + res._nextDay = void 0; + } + return res; + } + function prepareConfig(config3) { + var input = config3._i, format2 = config3._f; + config3._locale = config3._locale || getLocale(config3._l); + if (input === null || format2 === void 0 && input === "") { + return createInvalid({ nullInput: true }); + } + if (typeof input === "string") { + config3._i = input = config3._locale.preparse(input); + } + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isDate2(input)) { + config3._d = input; + } else if (isArray2(format2)) { + configFromStringAndArray(config3); + } else if (format2) { + configFromStringAndFormat(config3); + } else { + configFromInput(config3); + } + if (!isValid(config3)) { + config3._d = null; + } + return config3; + } + function configFromInput(config3) { + var input = config3._i; + if (isUndefined2(input)) { + config3._d = new Date(hooks.now()); + } else if (isDate2(input)) { + config3._d = new Date(input.valueOf()); + } else if (typeof input === "string") { + configFromString(config3); + } else if (isArray2(input)) { + config3._a = map(input.slice(0), function(obj) { + return parseInt(obj, 10); + }); + configFromArray(config3); + } else if (isObject2(input)) { + configFromObject(config3); + } else if (isNumber2(input)) { + config3._d = new Date(input); + } else { + hooks.createFromInputFallback(config3); + } + } + function createLocalOrUTC(input, format2, locale2, strict, isUTC) { + var c = {}; + if (format2 === true || format2 === false) { + strict = format2; + format2 = void 0; + } + if (locale2 === true || locale2 === false) { + strict = locale2; + locale2 = void 0; + } + if (isObject2(input) && isObjectEmpty(input) || isArray2(input) && input.length === 0) { + input = void 0; + } + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale2; + c._i = input; + c._f = format2; + c._strict = strict; + return createFromConfig(c); + } + function createLocal(input, format2, locale2, strict) { + return createLocalOrUTC(input, format2, locale2, strict, false); + } + var prototypeMin = deprecate( + "moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/", + function() { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other < this ? this : other; + } else { + return createInvalid(); + } + } + ), prototypeMax = deprecate( + "moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/", + function() { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other > this ? this : other; + } else { + return createInvalid(); + } + } + ); + function pickBy(fn2, moments) { + var res, i; + if (moments.length === 1 && isArray2(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (!moments[i].isValid() || moments[i][fn2](res)) { + res = moments[i]; + } + } + return res; + } + function min() { + var args = [].slice.call(arguments, 0); + return pickBy("isBefore", args); + } + function max() { + var args = [].slice.call(arguments, 0); + return pickBy("isAfter", args); + } + var now = function() { + return Date.now ? Date.now() : +/* @__PURE__ */ new Date(); + }; + var ordering = [ + "year", + "quarter", + "month", + "week", + "day", + "hour", + "minute", + "second", + "millisecond" + ]; + function isDurationValid(m2) { + var key, unitHasDecimal = false, i, orderLen = ordering.length; + for (key in m2) { + if (hasOwnProp(m2, key) && !(indexOf.call(ordering, key) !== -1 && (m2[key] == null || !isNaN(m2[key])))) { + return false; + } + } + for (i = 0; i < orderLen; ++i) { + if (m2[ordering[i]]) { + if (unitHasDecimal) { + return false; + } + if (parseFloat(m2[ordering[i]]) !== toInt(m2[ordering[i]])) { + unitHasDecimal = true; + } + } + } + return true; + } + function isValid$1() { + return this._isValid; + } + function createInvalid$1() { + return createDuration(NaN); + } + function Duration(duration) { + var normalizedInput = normalizeObjectUnits(duration), years2 = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months2 = normalizedInput.month || 0, weeks2 = normalizedInput.week || normalizedInput.isoWeek || 0, days2 = normalizedInput.day || 0, hours2 = normalizedInput.hour || 0, minutes2 = normalizedInput.minute || 0, seconds2 = normalizedInput.second || 0, milliseconds2 = normalizedInput.millisecond || 0; + this._isValid = isDurationValid(normalizedInput); + this._milliseconds = +milliseconds2 + seconds2 * 1e3 + // 1000 + minutes2 * 6e4 + // 1000 * 60 + hours2 * 1e3 * 60 * 60; + this._days = +days2 + weeks2 * 7; + this._months = +months2 + quarters * 3 + years2 * 12; + this._data = {}; + this._locale = getLocale(); + this._bubble(); + } + function isDuration(obj) { + return obj instanceof Duration; + } + function absRound(number) { + if (number < 0) { + return Math.round(-1 * number) * -1; + } else { + return Math.round(number); + } + } + function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; + for (i = 0; i < len; i++) { + if (dontConvert && array1[i] !== array2[i] || !dontConvert && toInt(array1[i]) !== toInt(array2[i])) { + diffs++; + } + } + return diffs + lengthDiff; + } + function offset(token2, separator) { + addFormatToken(token2, 0, 0, function() { + var offset2 = this.utcOffset(), sign3 = "+"; + if (offset2 < 0) { + offset2 = -offset2; + sign3 = "-"; + } + return sign3 + zeroFill(~~(offset2 / 60), 2) + separator + zeroFill(~~offset2 % 60, 2); + }); + } + offset("Z", ":"); + offset("ZZ", ""); + addRegexToken("Z", matchShortOffset); + addRegexToken("ZZ", matchShortOffset); + addParseToken(["Z", "ZZ"], function(input, array, config3) { + config3._useUTC = true; + config3._tzm = offsetFromString(matchShortOffset, input); + }); + var chunkOffset = /([\+\-]|\d\d)/gi; + function offsetFromString(matcher, string) { + var matches = (string || "").match(matcher), chunk, parts, minutes2; + if (matches === null) { + return null; + } + chunk = matches[matches.length - 1] || []; + parts = (chunk + "").match(chunkOffset) || ["-", 0, 0]; + minutes2 = +(parts[1] * 60) + toInt(parts[2]); + return minutes2 === 0 ? 0 : parts[0] === "+" ? minutes2 : -minutes2; + } + function cloneWithOffset(input, model) { + var res, diff2; + if (model._isUTC) { + res = model.clone(); + diff2 = (isMoment(input) || isDate2(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); + res._d.setTime(res._d.valueOf() + diff2); + hooks.updateOffset(res, false); + return res; + } else { + return createLocal(input).local(); + } + } + function getDateOffset(m2) { + return -Math.round(m2._d.getTimezoneOffset()); + } + hooks.updateOffset = function() { + }; + function getSetOffset(input, keepLocalTime, keepMinutes) { + var offset2 = this._offset || 0, localAdjust; + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + if (typeof input === "string") { + input = offsetFromString(matchShortOffset, input); + if (input === null) { + return this; + } + } else if (Math.abs(input) < 16 && !keepMinutes) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, "m"); + } + if (offset2 !== input) { + if (!keepLocalTime || this._changeInProgress) { + addSubtract( + this, + createDuration(input - offset2, "m"), + 1, + false + ); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset2 : getDateOffset(this); + } + } + function getSetZone(input, keepLocalTime) { + if (input != null) { + if (typeof input !== "string") { + input = -input; + } + this.utcOffset(input, keepLocalTime); + return this; + } else { + return -this.utcOffset(); + } + } + function setOffsetToUTC(keepLocalTime) { + return this.utcOffset(0, keepLocalTime); + } + function setOffsetToLocal(keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; + if (keepLocalTime) { + this.subtract(getDateOffset(this), "m"); + } + } + return this; + } + function setOffsetToParsedOffset() { + if (this._tzm != null) { + this.utcOffset(this._tzm, false, true); + } else if (typeof this._i === "string") { + var tZone = offsetFromString(matchOffset, this._i); + if (tZone != null) { + this.utcOffset(tZone); + } else { + this.utcOffset(0, true); + } + } + return this; + } + function hasAlignedHourOffset(input) { + if (!this.isValid()) { + return false; + } + input = input ? createLocal(input).utcOffset() : 0; + return (this.utcOffset() - input) % 60 === 0; + } + function isDaylightSavingTime() { + return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset(); + } + function isDaylightSavingTimeShifted() { + if (!isUndefined2(this._isDSTShifted)) { + return this._isDSTShifted; + } + var c = {}, other; + copyConfig(c, this); + c = prepareConfig(c); + if (c._a) { + other = c._isUTC ? createUTC(c._a) : createLocal(c._a); + this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0; + } else { + this._isDSTShifted = false; + } + return this._isDSTShifted; + } + function isLocal() { + return this.isValid() ? !this._isUTC : false; + } + function isUtcOffset() { + return this.isValid() ? this._isUTC : false; + } + function isUtc() { + return this.isValid() ? this._isUTC && this._offset === 0 : false; + } + var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; + function createDuration(input, key) { + var duration = input, match = null, sign3, ret, diffRes; + if (isDuration(input)) { + duration = { + ms: input._milliseconds, + d: input._days, + M: input._months + }; + } else if (isNumber2(input) || !isNaN(+input)) { + duration = {}; + if (key) { + duration[key] = +input; + } else { + duration.milliseconds = +input; + } + } else if (match = aspNetRegex.exec(input)) { + sign3 = match[1] === "-" ? -1 : 1; + duration = { + y: 0, + d: toInt(match[DATE]) * sign3, + h: toInt(match[HOUR]) * sign3, + m: toInt(match[MINUTE]) * sign3, + s: toInt(match[SECOND]) * sign3, + ms: toInt(absRound(match[MILLISECOND] * 1e3)) * sign3 + // the millisecond decimal point is included in the match + }; + } else if (match = isoRegex.exec(input)) { + sign3 = match[1] === "-" ? -1 : 1; + duration = { + y: parseIso(match[2], sign3), + M: parseIso(match[3], sign3), + w: parseIso(match[4], sign3), + d: parseIso(match[5], sign3), + h: parseIso(match[6], sign3), + m: parseIso(match[7], sign3), + s: parseIso(match[8], sign3) + }; + } else if (duration == null) { + duration = {}; + } else if (typeof duration === "object" && ("from" in duration || "to" in duration)) { + diffRes = momentsDifference( + createLocal(duration.from), + createLocal(duration.to) + ); + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } + ret = new Duration(duration); + if (isDuration(input) && hasOwnProp(input, "_locale")) { + ret._locale = input._locale; + } + if (isDuration(input) && hasOwnProp(input, "_isValid")) { + ret._isValid = input._isValid; + } + return ret; + } + createDuration.fn = Duration.prototype; + createDuration.invalid = createInvalid$1; + function parseIso(inp, sign3) { + var res = inp && parseFloat(inp.replace(",", ".")); + return (isNaN(res) ? 0 : res) * sign3; + } + function positiveMomentsDifference(base, other) { + var res = {}; + res.months = other.month() - base.month() + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, "M").isAfter(other)) { + --res.months; + } + res.milliseconds = +other - +base.clone().add(res.months, "M"); + return res; + } + function momentsDifference(base, other) { + var res; + if (!(base.isValid() && other.isValid())) { + return { milliseconds: 0, months: 0 }; + } + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } + return res; + } + function createAdder(direction, name) { + return function(val, period) { + var dur, tmp; + if (period !== null && !isNaN(+period)) { + deprecateSimple( + name, + "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info." + ); + tmp = val; + val = period; + period = tmp; + } + dur = createDuration(val, period); + addSubtract(this, dur, direction); + return this; + }; + } + function addSubtract(mom, duration, isAdding, updateOffset) { + var milliseconds2 = duration._milliseconds, days2 = absRound(duration._days), months2 = absRound(duration._months); + if (!mom.isValid()) { + return; + } + updateOffset = updateOffset == null ? true : updateOffset; + if (months2) { + setMonth(mom, get(mom, "Month") + months2 * isAdding); + } + if (days2) { + set$1(mom, "Date", get(mom, "Date") + days2 * isAdding); + } + if (milliseconds2) { + mom._d.setTime(mom._d.valueOf() + milliseconds2 * isAdding); + } + if (updateOffset) { + hooks.updateOffset(mom, days2 || months2); + } + } + var add = createAdder(1, "add"), subtract = createAdder(-1, "subtract"); + function isString2(input) { + return typeof input === "string" || input instanceof String; + } + function isMomentInput(input) { + return isMoment(input) || isDate2(input) || isString2(input) || isNumber2(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === void 0; + } + function isMomentInputObject(input) { + var objectTest = isObject2(input) && !isObjectEmpty(input), propertyTest = false, properties = [ + "years", + "year", + "y", + "months", + "month", + "M", + "days", + "day", + "d", + "dates", + "date", + "D", + "hours", + "hour", + "h", + "minutes", + "minute", + "m", + "seconds", + "second", + "s", + "milliseconds", + "millisecond", + "ms" + ], i, property, propertyLen = properties.length; + for (i = 0; i < propertyLen; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } + return objectTest && propertyTest; + } + function isNumberOrStringArray(input) { + var arrayTest = isArray2(input), dataTypeTest = false; + if (arrayTest) { + dataTypeTest = input.filter(function(item) { + return !isNumber2(item) && isString2(input); + }).length === 0; + } + return arrayTest && dataTypeTest; + } + function isCalendarSpec(input) { + var objectTest = isObject2(input) && !isObjectEmpty(input), propertyTest = false, properties = [ + "sameDay", + "nextDay", + "lastDay", + "nextWeek", + "lastWeek", + "sameElse" + ], i, property; + for (i = 0; i < properties.length; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } + return objectTest && propertyTest; + } + function getCalendarFormat(myMoment, now2) { + var diff2 = myMoment.diff(now2, "days", true); + return diff2 < -6 ? "sameElse" : diff2 < -1 ? "lastWeek" : diff2 < 0 ? "lastDay" : diff2 < 1 ? "sameDay" : diff2 < 2 ? "nextDay" : diff2 < 7 ? "nextWeek" : "sameElse"; + } + function calendar$1(time, formats) { + if (arguments.length === 1) { + if (!arguments[0]) { + time = void 0; + formats = void 0; + } else if (isMomentInput(arguments[0])) { + time = arguments[0]; + formats = void 0; + } else if (isCalendarSpec(arguments[0])) { + formats = arguments[0]; + time = void 0; + } + } + var now2 = time || createLocal(), sod = cloneWithOffset(now2, this).startOf("day"), format2 = hooks.calendarFormat(this, sod) || "sameElse", output = formats && (isFunction2(formats[format2]) ? formats[format2].call(this, now2) : formats[format2]); + return this.format( + output || this.localeData().calendar(format2, this, createLocal(now2)) + ); + } + function clone() { + return new Moment(this); + } + function isAfter(input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || "millisecond"; + if (units === "millisecond") { + return this.valueOf() > localInput.valueOf(); + } else { + return localInput.valueOf() < this.clone().startOf(units).valueOf(); + } + } + function isBefore(input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || "millisecond"; + if (units === "millisecond") { + return this.valueOf() < localInput.valueOf(); + } else { + return this.clone().endOf(units).valueOf() < localInput.valueOf(); + } + } + function isBetween(from6, to3, units, inclusivity) { + var localFrom = isMoment(from6) ? from6 : createLocal(from6), localTo = isMoment(to3) ? to3 : createLocal(to3); + if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { + return false; + } + inclusivity = inclusivity || "()"; + return (inclusivity[0] === "(" ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ")" ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)); + } + function isSame(input, units) { + var localInput = isMoment(input) ? input : createLocal(input), inputMs; + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || "millisecond"; + if (units === "millisecond") { + return this.valueOf() === localInput.valueOf(); + } else { + inputMs = localInput.valueOf(); + return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); + } + } + function isSameOrAfter(input, units) { + return this.isSame(input, units) || this.isAfter(input, units); + } + function isSameOrBefore(input, units) { + return this.isSame(input, units) || this.isBefore(input, units); + } + function diff(input, units, asFloat) { + var that, zoneDelta, output; + if (!this.isValid()) { + return NaN; + } + that = cloneWithOffset(input, this); + if (!that.isValid()) { + return NaN; + } + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + units = normalizeUnits(units); + switch (units) { + case "year": + output = monthDiff(this, that) / 12; + break; + case "month": + output = monthDiff(this, that); + break; + case "quarter": + output = monthDiff(this, that) / 3; + break; + case "second": + output = (this - that) / 1e3; + break; + // 1000 + case "minute": + output = (this - that) / 6e4; + break; + // 1000 * 60 + case "hour": + output = (this - that) / 36e5; + break; + // 1000 * 60 * 60 + case "day": + output = (this - that - zoneDelta) / 864e5; + break; + // 1000 * 60 * 60 * 24, negate dst + case "week": + output = (this - that - zoneDelta) / 6048e5; + break; + // 1000 * 60 * 60 * 24 * 7, negate dst + default: + output = this - that; + } + return asFloat ? output : absFloor(output); + } + function monthDiff(a, b2) { + if (a.date() < b2.date()) { + return -monthDiff(b2, a); + } + var wholeMonthDiff = (b2.year() - a.year()) * 12 + (b2.month() - a.month()), anchor = a.clone().add(wholeMonthDiff, "months"), anchor2, adjust; + if (b2 - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, "months"); + adjust = (b2 - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, "months"); + adjust = (b2 - anchor) / (anchor2 - anchor); + } + return -(wholeMonthDiff + adjust) || 0; + } + hooks.defaultFormat = "YYYY-MM-DDTHH:mm:ssZ"; + hooks.defaultFormatUtc = "YYYY-MM-DDTHH:mm:ss[Z]"; + function toString3() { + return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); + } + function toISOString(keepOffset) { + if (!this.isValid()) { + return null; + } + var utc = keepOffset !== true, m2 = utc ? this.clone().utc() : this; + if (m2.year() < 0 || m2.year() > 9999) { + return formatMoment( + m2, + utc ? "YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYYYY-MM-DD[T]HH:mm:ss.SSSZ" + ); + } + if (isFunction2(Date.prototype.toISOString)) { + if (utc) { + return this.toDate().toISOString(); + } else { + return new Date(this.valueOf() + this.utcOffset() * 60 * 1e3).toISOString().replace("Z", formatMoment(m2, "Z")); + } + } + return formatMoment( + m2, + utc ? "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYY-MM-DD[T]HH:mm:ss.SSSZ" + ); + } + function inspect() { + if (!this.isValid()) { + return "moment.invalid(/* " + this._i + " */)"; + } + var func = "moment", zone = "", prefix, year, datetime, suffix; + if (!this.isLocal()) { + func = this.utcOffset() === 0 ? "moment.utc" : "moment.parseZone"; + zone = "Z"; + } + prefix = "[" + func + '("]'; + year = 0 <= this.year() && this.year() <= 9999 ? "YYYY" : "YYYYYY"; + datetime = "-MM-DD[T]HH:mm:ss.SSS"; + suffix = zone + '[")]'; + return this.format(prefix + year + datetime + suffix); + } + function format(inputString) { + if (!inputString) { + inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; + } + var output = formatMoment(this, inputString); + return this.localeData().postformat(output); + } + function from5(time, withoutSuffix) { + if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) { + return createDuration({ to: this, from: time }).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } + function fromNow(withoutSuffix) { + return this.from(createLocal(), withoutSuffix); + } + function to2(time, withoutSuffix) { + if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) { + return createDuration({ from: this, to: time }).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } + function toNow(withoutSuffix) { + return this.to(createLocal(), withoutSuffix); + } + function locale(key) { + var newLocaleData; + if (key === void 0) { + return this._locale._abbr; + } else { + newLocaleData = getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; + } + } + var lang = deprecate( + "moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.", + function(key) { + if (key === void 0) { + return this.localeData(); + } else { + return this.locale(key); + } + } + ); + function localeData() { + return this._locale; + } + var MS_PER_SECOND = 1e3, MS_PER_MINUTE = 60 * MS_PER_SECOND, MS_PER_HOUR = 60 * MS_PER_MINUTE, MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; + function mod$1(dividend, divisor) { + return (dividend % divisor + divisor) % divisor; + } + function localStartOfDate(y2, m2, d) { + if (y2 < 100 && y2 >= 0) { + return new Date(y2 + 400, m2, d) - MS_PER_400_YEARS; + } else { + return new Date(y2, m2, d).valueOf(); + } + } + function utcStartOfDate(y2, m2, d) { + if (y2 < 100 && y2 >= 0) { + return Date.UTC(y2 + 400, m2, d) - MS_PER_400_YEARS; + } else { + return Date.UTC(y2, m2, d); + } + } + function startOf(units) { + var time, startOfDate; + units = normalizeUnits(units); + if (units === void 0 || units === "millisecond" || !this.isValid()) { + return this; + } + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + switch (units) { + case "year": + time = startOfDate(this.year(), 0, 1); + break; + case "quarter": + time = startOfDate( + this.year(), + this.month() - this.month() % 3, + 1 + ); + break; + case "month": + time = startOfDate(this.year(), this.month(), 1); + break; + case "week": + time = startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + ); + break; + case "isoWeek": + time = startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + ); + break; + case "day": + case "date": + time = startOfDate(this.year(), this.month(), this.date()); + break; + case "hour": + time = this._d.valueOf(); + time -= mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR + ); + break; + case "minute": + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_MINUTE); + break; + case "second": + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_SECOND); + break; + } + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + function endOf(units) { + var time, startOfDate; + units = normalizeUnits(units); + if (units === void 0 || units === "millisecond" || !this.isValid()) { + return this; + } + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + switch (units) { + case "year": + time = startOfDate(this.year() + 1, 0, 1) - 1; + break; + case "quarter": + time = startOfDate( + this.year(), + this.month() - this.month() % 3 + 3, + 1 + ) - 1; + break; + case "month": + time = startOfDate(this.year(), this.month() + 1, 1) - 1; + break; + case "week": + time = startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + 7 + ) - 1; + break; + case "isoWeek": + time = startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + 7 + ) - 1; + break; + case "day": + case "date": + time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; + break; + case "hour": + time = this._d.valueOf(); + time += MS_PER_HOUR - mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR + ) - 1; + break; + case "minute": + time = this._d.valueOf(); + time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; + break; + case "second": + time = this._d.valueOf(); + time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; + break; + } + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + function valueOf() { + return this._d.valueOf() - (this._offset || 0) * 6e4; + } + function unix() { + return Math.floor(this.valueOf() / 1e3); + } + function toDate() { + return new Date(this.valueOf()); + } + function toArray2() { + var m2 = this; + return [ + m2.year(), + m2.month(), + m2.date(), + m2.hour(), + m2.minute(), + m2.second(), + m2.millisecond() + ]; + } + function toObject() { + var m2 = this; + return { + years: m2.year(), + months: m2.month(), + date: m2.date(), + hours: m2.hours(), + minutes: m2.minutes(), + seconds: m2.seconds(), + milliseconds: m2.milliseconds() + }; + } + function toJSON2() { + return this.isValid() ? this.toISOString() : null; + } + function isValid$2() { + return isValid(this); + } + function parsingFlags() { + return extend2({}, getParsingFlags(this)); + } + function invalidAt() { + return getParsingFlags(this).overflow; + } + function creationData() { + return { + input: this._i, + format: this._f, + locale: this._locale, + isUTC: this._isUTC, + strict: this._strict + }; + } + addFormatToken("N", 0, 0, "eraAbbr"); + addFormatToken("NN", 0, 0, "eraAbbr"); + addFormatToken("NNN", 0, 0, "eraAbbr"); + addFormatToken("NNNN", 0, 0, "eraName"); + addFormatToken("NNNNN", 0, 0, "eraNarrow"); + addFormatToken("y", ["y", 1], "yo", "eraYear"); + addFormatToken("y", ["yy", 2], 0, "eraYear"); + addFormatToken("y", ["yyy", 3], 0, "eraYear"); + addFormatToken("y", ["yyyy", 4], 0, "eraYear"); + addRegexToken("N", matchEraAbbr); + addRegexToken("NN", matchEraAbbr); + addRegexToken("NNN", matchEraAbbr); + addRegexToken("NNNN", matchEraName); + addRegexToken("NNNNN", matchEraNarrow); + addParseToken( + ["N", "NN", "NNN", "NNNN", "NNNNN"], + function(input, array, config3, token2) { + var era = config3._locale.erasParse(input, token2, config3._strict); + if (era) { + getParsingFlags(config3).era = era; + } else { + getParsingFlags(config3).invalidEra = input; + } + } + ); + addRegexToken("y", matchUnsigned); + addRegexToken("yy", matchUnsigned); + addRegexToken("yyy", matchUnsigned); + addRegexToken("yyyy", matchUnsigned); + addRegexToken("yo", matchEraYearOrdinal); + addParseToken(["y", "yy", "yyy", "yyyy"], YEAR); + addParseToken(["yo"], function(input, array, config3, token2) { + var match; + if (config3._locale._eraYearOrdinalRegex) { + match = input.match(config3._locale._eraYearOrdinalRegex); + } + if (config3._locale.eraYearOrdinalParse) { + array[YEAR] = config3._locale.eraYearOrdinalParse(input, match); + } else { + array[YEAR] = parseInt(input, 10); + } + }); + function localeEras(m2, format2) { + var i, l, date, eras = this._eras || getLocale("en")._eras; + for (i = 0, l = eras.length; i < l; ++i) { + switch (typeof eras[i].since) { + case "string": + date = hooks(eras[i].since).startOf("day"); + eras[i].since = date.valueOf(); + break; + } + switch (typeof eras[i].until) { + case "undefined": + eras[i].until = Infinity; + break; + case "string": + date = hooks(eras[i].until).startOf("day").valueOf(); + eras[i].until = date.valueOf(); + break; + } + } + return eras; + } + function localeErasParse(eraName, format2, strict) { + var i, l, eras = this.eras(), name, abbr, narrow; + eraName = eraName.toUpperCase(); + for (i = 0, l = eras.length; i < l; ++i) { + name = eras[i].name.toUpperCase(); + abbr = eras[i].abbr.toUpperCase(); + narrow = eras[i].narrow.toUpperCase(); + if (strict) { + switch (format2) { + case "N": + case "NN": + case "NNN": + if (abbr === eraName) { + return eras[i]; + } + break; + case "NNNN": + if (name === eraName) { + return eras[i]; + } + break; + case "NNNNN": + if (narrow === eraName) { + return eras[i]; + } + break; + } + } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { + return eras[i]; + } + } + } + function localeErasConvertYear(era, year) { + var dir = era.since <= era.until ? 1 : -1; + if (year === void 0) { + return hooks(era.since).year(); + } else { + return hooks(era.since).year() + (year - era.offset) * dir; + } + } + function getEraName() { + var i, l, val, eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + val = this.clone().startOf("day").valueOf(); + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].name; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].name; + } + } + return ""; + } + function getEraNarrow() { + var i, l, val, eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + val = this.clone().startOf("day").valueOf(); + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].narrow; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].narrow; + } + } + return ""; + } + function getEraAbbr() { + var i, l, val, eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + val = this.clone().startOf("day").valueOf(); + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].abbr; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].abbr; + } + } + return ""; + } + function getEraYear() { + var i, l, dir, val, eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + dir = eras[i].since <= eras[i].until ? 1 : -1; + val = this.clone().startOf("day").valueOf(); + if (eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) { + return (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset; + } + } + return this.year(); + } + function erasNameRegex(isStrict) { + if (!hasOwnProp(this, "_erasNameRegex")) { + computeErasParse.call(this); + } + return isStrict ? this._erasNameRegex : this._erasRegex; + } + function erasAbbrRegex(isStrict) { + if (!hasOwnProp(this, "_erasAbbrRegex")) { + computeErasParse.call(this); + } + return isStrict ? this._erasAbbrRegex : this._erasRegex; + } + function erasNarrowRegex(isStrict) { + if (!hasOwnProp(this, "_erasNarrowRegex")) { + computeErasParse.call(this); + } + return isStrict ? this._erasNarrowRegex : this._erasRegex; + } + function matchEraAbbr(isStrict, locale2) { + return locale2.erasAbbrRegex(isStrict); + } + function matchEraName(isStrict, locale2) { + return locale2.erasNameRegex(isStrict); + } + function matchEraNarrow(isStrict, locale2) { + return locale2.erasNarrowRegex(isStrict); + } + function matchEraYearOrdinal(isStrict, locale2) { + return locale2._eraYearOrdinalRegex || matchUnsigned; + } + function computeErasParse() { + var abbrPieces = [], namePieces = [], narrowPieces = [], mixedPieces = [], i, l, erasName, erasAbbr, erasNarrow, eras = this.eras(); + for (i = 0, l = eras.length; i < l; ++i) { + erasName = regexEscape(eras[i].name); + erasAbbr = regexEscape(eras[i].abbr); + erasNarrow = regexEscape(eras[i].narrow); + namePieces.push(erasName); + abbrPieces.push(erasAbbr); + narrowPieces.push(erasNarrow); + mixedPieces.push(erasName); + mixedPieces.push(erasAbbr); + mixedPieces.push(erasNarrow); + } + this._erasRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); + this._erasNameRegex = new RegExp("^(" + namePieces.join("|") + ")", "i"); + this._erasAbbrRegex = new RegExp("^(" + abbrPieces.join("|") + ")", "i"); + this._erasNarrowRegex = new RegExp( + "^(" + narrowPieces.join("|") + ")", + "i" + ); + } + addFormatToken(0, ["gg", 2], 0, function() { + return this.weekYear() % 100; + }); + addFormatToken(0, ["GG", 2], 0, function() { + return this.isoWeekYear() % 100; + }); + function addWeekYearFormatToken(token2, getter) { + addFormatToken(0, [token2, token2.length], 0, getter); + } + addWeekYearFormatToken("gggg", "weekYear"); + addWeekYearFormatToken("ggggg", "weekYear"); + addWeekYearFormatToken("GGGG", "isoWeekYear"); + addWeekYearFormatToken("GGGGG", "isoWeekYear"); + addRegexToken("G", matchSigned); + addRegexToken("g", matchSigned); + addRegexToken("GG", match1to2, match2); + addRegexToken("gg", match1to2, match2); + addRegexToken("GGGG", match1to4, match4); + addRegexToken("gggg", match1to4, match4); + addRegexToken("GGGGG", match1to6, match6); + addRegexToken("ggggg", match1to6, match6); + addWeekParseToken( + ["gggg", "ggggg", "GGGG", "GGGGG"], + function(input, week, config3, token2) { + week[token2.substr(0, 2)] = toInt(input); + } + ); + addWeekParseToken(["gg", "GG"], function(input, week, config3, token2) { + week[token2] = hooks.parseTwoDigitYear(input); + }); + function getSetWeekYear(input) { + return getSetWeekYearHelper.call( + this, + input, + this.week(), + this.weekday() + this.localeData()._week.dow, + this.localeData()._week.dow, + this.localeData()._week.doy + ); + } + function getSetISOWeekYear(input) { + return getSetWeekYearHelper.call( + this, + input, + this.isoWeek(), + this.isoWeekday(), + 1, + 4 + ); + } + function getISOWeeksInYear() { + return weeksInYear(this.year(), 1, 4); + } + function getISOWeeksInISOWeekYear() { + return weeksInYear(this.isoWeekYear(), 1, 4); + } + function getWeeksInYear() { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); + } + function getWeeksInWeekYear() { + var weekInfo = this.localeData()._week; + return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); + } + function getSetWeekYearHelper(input, week, weekday, dow, doy) { + var weeksTarget; + if (input == null) { + return weekOfYear(this, dow, doy).year; + } else { + weeksTarget = weeksInYear(input, dow, doy); + if (week > weeksTarget) { + week = weeksTarget; + } + return setWeekAll.call(this, input, week, weekday, dow, doy); + } + } + function setWeekAll(weekYear, week, weekday, dow, doy) { + var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); + this.year(date.getUTCFullYear()); + this.month(date.getUTCMonth()); + this.date(date.getUTCDate()); + return this; + } + addFormatToken("Q", 0, "Qo", "quarter"); + addRegexToken("Q", match1); + addParseToken("Q", function(input, array) { + array[MONTH] = (toInt(input) - 1) * 3; + }); + function getSetQuarter(input) { + return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); + } + addFormatToken("D", ["DD", 2], "Do", "date"); + addRegexToken("D", match1to2, match1to2NoLeadingZero); + addRegexToken("DD", match1to2, match2); + addRegexToken("Do", function(isStrict, locale2) { + return isStrict ? locale2._dayOfMonthOrdinalParse || locale2._ordinalParse : locale2._dayOfMonthOrdinalParseLenient; + }); + addParseToken(["D", "DD"], DATE); + addParseToken("Do", function(input, array) { + array[DATE] = toInt(input.match(match1to2)[0]); + }); + var getSetDayOfMonth = makeGetSet("Date", true); + addFormatToken("DDD", ["DDDD", 3], "DDDo", "dayOfYear"); + addRegexToken("DDD", match1to3); + addRegexToken("DDDD", match3); + addParseToken(["DDD", "DDDD"], function(input, array, config3) { + config3._dayOfYear = toInt(input); + }); + function getSetDayOfYear(input) { + var dayOfYear = Math.round( + (this.clone().startOf("day") - this.clone().startOf("year")) / 864e5 + ) + 1; + return input == null ? dayOfYear : this.add(input - dayOfYear, "d"); + } + addFormatToken("m", ["mm", 2], 0, "minute"); + addRegexToken("m", match1to2, match1to2HasZero); + addRegexToken("mm", match1to2, match2); + addParseToken(["m", "mm"], MINUTE); + var getSetMinute = makeGetSet("Minutes", false); + addFormatToken("s", ["ss", 2], 0, "second"); + addRegexToken("s", match1to2, match1to2HasZero); + addRegexToken("ss", match1to2, match2); + addParseToken(["s", "ss"], SECOND); + var getSetSecond = makeGetSet("Seconds", false); + addFormatToken("S", 0, 0, function() { + return ~~(this.millisecond() / 100); + }); + addFormatToken(0, ["SS", 2], 0, function() { + return ~~(this.millisecond() / 10); + }); + addFormatToken(0, ["SSS", 3], 0, "millisecond"); + addFormatToken(0, ["SSSS", 4], 0, function() { + return this.millisecond() * 10; + }); + addFormatToken(0, ["SSSSS", 5], 0, function() { + return this.millisecond() * 100; + }); + addFormatToken(0, ["SSSSSS", 6], 0, function() { + return this.millisecond() * 1e3; + }); + addFormatToken(0, ["SSSSSSS", 7], 0, function() { + return this.millisecond() * 1e4; + }); + addFormatToken(0, ["SSSSSSSS", 8], 0, function() { + return this.millisecond() * 1e5; + }); + addFormatToken(0, ["SSSSSSSSS", 9], 0, function() { + return this.millisecond() * 1e6; + }); + addRegexToken("S", match1to3, match1); + addRegexToken("SS", match1to3, match2); + addRegexToken("SSS", match1to3, match3); + var token, getSetMillisecond; + for (token = "SSSS"; token.length <= 9; token += "S") { + addRegexToken(token, matchUnsigned); + } + function parseMs(input, array) { + array[MILLISECOND] = toInt(("0." + input) * 1e3); + } + for (token = "S"; token.length <= 9; token += "S") { + addParseToken(token, parseMs); + } + getSetMillisecond = makeGetSet("Milliseconds", false); + addFormatToken("z", 0, 0, "zoneAbbr"); + addFormatToken("zz", 0, 0, "zoneName"); + function getZoneAbbr() { + return this._isUTC ? "UTC" : ""; + } + function getZoneName() { + return this._isUTC ? "Coordinated Universal Time" : ""; + } + var proto = Moment.prototype; + proto.add = add; + proto.calendar = calendar$1; + proto.clone = clone; + proto.diff = diff; + proto.endOf = endOf; + proto.format = format; + proto.from = from5; + proto.fromNow = fromNow; + proto.to = to2; + proto.toNow = toNow; + proto.get = stringGet; + proto.invalidAt = invalidAt; + proto.isAfter = isAfter; + proto.isBefore = isBefore; + proto.isBetween = isBetween; + proto.isSame = isSame; + proto.isSameOrAfter = isSameOrAfter; + proto.isSameOrBefore = isSameOrBefore; + proto.isValid = isValid$2; + proto.lang = lang; + proto.locale = locale; + proto.localeData = localeData; + proto.max = prototypeMax; + proto.min = prototypeMin; + proto.parsingFlags = parsingFlags; + proto.set = stringSet; + proto.startOf = startOf; + proto.subtract = subtract; + proto.toArray = toArray2; + proto.toObject = toObject; + proto.toDate = toDate; + proto.toISOString = toISOString; + proto.inspect = inspect; + if (typeof Symbol !== "undefined" && Symbol.for != null) { + proto[Symbol.for("nodejs.util.inspect.custom")] = function() { + return "Moment<" + this.format() + ">"; + }; + } + proto.toJSON = toJSON2; + proto.toString = toString3; + proto.unix = unix; + proto.valueOf = valueOf; + proto.creationData = creationData; + proto.eraName = getEraName; + proto.eraNarrow = getEraNarrow; + proto.eraAbbr = getEraAbbr; + proto.eraYear = getEraYear; + proto.year = getSetYear; + proto.isLeapYear = getIsLeapYear; + proto.weekYear = getSetWeekYear; + proto.isoWeekYear = getSetISOWeekYear; + proto.quarter = proto.quarters = getSetQuarter; + proto.month = getSetMonth; + proto.daysInMonth = getDaysInMonth; + proto.week = proto.weeks = getSetWeek; + proto.isoWeek = proto.isoWeeks = getSetISOWeek; + proto.weeksInYear = getWeeksInYear; + proto.weeksInWeekYear = getWeeksInWeekYear; + proto.isoWeeksInYear = getISOWeeksInYear; + proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear; + proto.date = getSetDayOfMonth; + proto.day = proto.days = getSetDayOfWeek; + proto.weekday = getSetLocaleDayOfWeek; + proto.isoWeekday = getSetISODayOfWeek; + proto.dayOfYear = getSetDayOfYear; + proto.hour = proto.hours = getSetHour; + proto.minute = proto.minutes = getSetMinute; + proto.second = proto.seconds = getSetSecond; + proto.millisecond = proto.milliseconds = getSetMillisecond; + proto.utcOffset = getSetOffset; + proto.utc = setOffsetToUTC; + proto.local = setOffsetToLocal; + proto.parseZone = setOffsetToParsedOffset; + proto.hasAlignedHourOffset = hasAlignedHourOffset; + proto.isDST = isDaylightSavingTime; + proto.isLocal = isLocal; + proto.isUtcOffset = isUtcOffset; + proto.isUtc = isUtc; + proto.isUTC = isUtc; + proto.zoneAbbr = getZoneAbbr; + proto.zoneName = getZoneName; + proto.dates = deprecate( + "dates accessor is deprecated. Use date instead.", + getSetDayOfMonth + ); + proto.months = deprecate( + "months accessor is deprecated. Use month instead", + getSetMonth + ); + proto.years = deprecate( + "years accessor is deprecated. Use year instead", + getSetYear + ); + proto.zone = deprecate( + "moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/", + getSetZone + ); + proto.isDSTShifted = deprecate( + "isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information", + isDaylightSavingTimeShifted + ); + function createUnix(input) { + return createLocal(input * 1e3); + } + function createInZone() { + return createLocal.apply(null, arguments).parseZone(); + } + function preParsePostFormat(string) { + return string; + } + var proto$1 = Locale.prototype; + proto$1.calendar = calendar; + proto$1.longDateFormat = longDateFormat; + proto$1.invalidDate = invalidDate; + proto$1.ordinal = ordinal; + proto$1.preparse = preParsePostFormat; + proto$1.postformat = preParsePostFormat; + proto$1.relativeTime = relativeTime; + proto$1.pastFuture = pastFuture; + proto$1.set = set; + proto$1.eras = localeEras; + proto$1.erasParse = localeErasParse; + proto$1.erasConvertYear = localeErasConvertYear; + proto$1.erasAbbrRegex = erasAbbrRegex; + proto$1.erasNameRegex = erasNameRegex; + proto$1.erasNarrowRegex = erasNarrowRegex; + proto$1.months = localeMonths; + proto$1.monthsShort = localeMonthsShort; + proto$1.monthsParse = localeMonthsParse; + proto$1.monthsRegex = monthsRegex; + proto$1.monthsShortRegex = monthsShortRegex; + proto$1.week = localeWeek; + proto$1.firstDayOfYear = localeFirstDayOfYear; + proto$1.firstDayOfWeek = localeFirstDayOfWeek; + proto$1.weekdays = localeWeekdays; + proto$1.weekdaysMin = localeWeekdaysMin; + proto$1.weekdaysShort = localeWeekdaysShort; + proto$1.weekdaysParse = localeWeekdaysParse; + proto$1.weekdaysRegex = weekdaysRegex; + proto$1.weekdaysShortRegex = weekdaysShortRegex; + proto$1.weekdaysMinRegex = weekdaysMinRegex; + proto$1.isPM = localeIsPM; + proto$1.meridiem = localeMeridiem; + function get$1(format2, index2, field, setter) { + var locale2 = getLocale(), utc = createUTC().set(setter, index2); + return locale2[field](utc, format2); + } + function listMonthsImpl(format2, index2, field) { + if (isNumber2(format2)) { + index2 = format2; + format2 = void 0; + } + format2 = format2 || ""; + if (index2 != null) { + return get$1(format2, index2, field, "month"); + } + var i, out = []; + for (i = 0; i < 12; i++) { + out[i] = get$1(format2, i, field, "month"); + } + return out; + } + function listWeekdaysImpl(localeSorted, format2, index2, field) { + if (typeof localeSorted === "boolean") { + if (isNumber2(format2)) { + index2 = format2; + format2 = void 0; + } + format2 = format2 || ""; + } else { + format2 = localeSorted; + index2 = format2; + localeSorted = false; + if (isNumber2(format2)) { + index2 = format2; + format2 = void 0; + } + format2 = format2 || ""; + } + var locale2 = getLocale(), shift = localeSorted ? locale2._week.dow : 0, i, out = []; + if (index2 != null) { + return get$1(format2, (index2 + shift) % 7, field, "day"); + } + for (i = 0; i < 7; i++) { + out[i] = get$1(format2, (i + shift) % 7, field, "day"); + } + return out; + } + function listMonths(format2, index2) { + return listMonthsImpl(format2, index2, "months"); + } + function listMonthsShort(format2, index2) { + return listMonthsImpl(format2, index2, "monthsShort"); + } + function listWeekdays(localeSorted, format2, index2) { + return listWeekdaysImpl(localeSorted, format2, index2, "weekdays"); + } + function listWeekdaysShort(localeSorted, format2, index2) { + return listWeekdaysImpl(localeSorted, format2, index2, "weekdaysShort"); + } + function listWeekdaysMin(localeSorted, format2, index2) { + return listWeekdaysImpl(localeSorted, format2, index2, "weekdaysMin"); + } + getSetGlobalLocale("en", { + eras: [ + { + since: "0001-01-01", + until: Infinity, + offset: 1, + name: "Anno Domini", + narrow: "AD", + abbr: "AD" + }, + { + since: "0000-12-31", + until: -Infinity, + offset: 1, + name: "Before Christ", + narrow: "BC", + abbr: "BC" + } + ], + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal: function(number) { + var b2 = number % 10, output = toInt(number % 100 / 10) === 1 ? "th" : b2 === 1 ? "st" : b2 === 2 ? "nd" : b2 === 3 ? "rd" : "th"; + return number + output; + } + }); + hooks.lang = deprecate( + "moment.lang is deprecated. Use moment.locale instead.", + getSetGlobalLocale + ); + hooks.langData = deprecate( + "moment.langData is deprecated. Use moment.localeData instead.", + getLocale + ); + var mathAbs = Math.abs; + function abs() { + var data = this._data; + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); + return this; + } + function addSubtract$1(duration, input, value, direction) { + var other = createDuration(input, value); + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; + return duration._bubble(); + } + function add$1(input, value) { + return addSubtract$1(this, input, value, 1); + } + function subtract$1(input, value) { + return addSubtract$1(this, input, value, -1); + } + function absCeil(number) { + if (number < 0) { + return Math.floor(number); + } else { + return Math.ceil(number); + } + } + function bubble() { + var milliseconds2 = this._milliseconds, days2 = this._days, months2 = this._months, data = this._data, seconds2, minutes2, hours2, years2, monthsFromDays; + if (!(milliseconds2 >= 0 && days2 >= 0 && months2 >= 0 || milliseconds2 <= 0 && days2 <= 0 && months2 <= 0)) { + milliseconds2 += absCeil(monthsToDays(months2) + days2) * 864e5; + days2 = 0; + months2 = 0; + } + data.milliseconds = milliseconds2 % 1e3; + seconds2 = absFloor(milliseconds2 / 1e3); + data.seconds = seconds2 % 60; + minutes2 = absFloor(seconds2 / 60); + data.minutes = minutes2 % 60; + hours2 = absFloor(minutes2 / 60); + data.hours = hours2 % 24; + days2 += absFloor(hours2 / 24); + monthsFromDays = absFloor(daysToMonths(days2)); + months2 += monthsFromDays; + days2 -= absCeil(monthsToDays(monthsFromDays)); + years2 = absFloor(months2 / 12); + months2 %= 12; + data.days = days2; + data.months = months2; + data.years = years2; + return this; + } + function daysToMonths(days2) { + return days2 * 4800 / 146097; + } + function monthsToDays(months2) { + return months2 * 146097 / 4800; + } + function as2(units) { + if (!this.isValid()) { + return NaN; + } + var days2, months2, milliseconds2 = this._milliseconds; + units = normalizeUnits(units); + if (units === "month" || units === "quarter" || units === "year") { + days2 = this._days + milliseconds2 / 864e5; + months2 = this._months + daysToMonths(days2); + switch (units) { + case "month": + return months2; + case "quarter": + return months2 / 3; + case "year": + return months2 / 12; + } + } else { + days2 = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case "week": + return days2 / 7 + milliseconds2 / 6048e5; + case "day": + return days2 + milliseconds2 / 864e5; + case "hour": + return days2 * 24 + milliseconds2 / 36e5; + case "minute": + return days2 * 1440 + milliseconds2 / 6e4; + case "second": + return days2 * 86400 + milliseconds2 / 1e3; + // Math.floor prevents floating point math errors here + case "millisecond": + return Math.floor(days2 * 864e5) + milliseconds2; + default: + throw new Error("Unknown unit " + units); + } + } + } + function makeAs(alias) { + return function() { + return this.as(alias); + }; + } + var asMilliseconds = makeAs("ms"), asSeconds = makeAs("s"), asMinutes = makeAs("m"), asHours = makeAs("h"), asDays = makeAs("d"), asWeeks = makeAs("w"), asMonths = makeAs("M"), asQuarters = makeAs("Q"), asYears = makeAs("y"), valueOf$1 = asMilliseconds; + function clone$1() { + return createDuration(this); + } + function get$2(units) { + units = normalizeUnits(units); + return this.isValid() ? this[units + "s"]() : NaN; + } + function makeGetter(name) { + return function() { + return this.isValid() ? this._data[name] : NaN; + }; + } + var milliseconds = makeGetter("milliseconds"), seconds = makeGetter("seconds"), minutes = makeGetter("minutes"), hours = makeGetter("hours"), days = makeGetter("days"), months = makeGetter("months"), years = makeGetter("years"); + function weeks() { + return absFloor(this.days() / 7); + } + var round = Math.round, thresholds = { + ss: 44, + // a few seconds to seconds + s: 45, + // seconds to minute + m: 45, + // minutes to hour + h: 22, + // hours to day + d: 26, + // days to month/week + w: null, + // weeks to month + M: 11 + // months to year + }; + function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale2) { + return locale2.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + } + function relativeTime$1(posNegDuration, withoutSuffix, thresholds2, locale2) { + var duration = createDuration(posNegDuration).abs(), seconds2 = round(duration.as("s")), minutes2 = round(duration.as("m")), hours2 = round(duration.as("h")), days2 = round(duration.as("d")), months2 = round(duration.as("M")), weeks2 = round(duration.as("w")), years2 = round(duration.as("y")), a = seconds2 <= thresholds2.ss && ["s", seconds2] || seconds2 < thresholds2.s && ["ss", seconds2] || minutes2 <= 1 && ["m"] || minutes2 < thresholds2.m && ["mm", minutes2] || hours2 <= 1 && ["h"] || hours2 < thresholds2.h && ["hh", hours2] || days2 <= 1 && ["d"] || days2 < thresholds2.d && ["dd", days2]; + if (thresholds2.w != null) { + a = a || weeks2 <= 1 && ["w"] || weeks2 < thresholds2.w && ["ww", weeks2]; + } + a = a || months2 <= 1 && ["M"] || months2 < thresholds2.M && ["MM", months2] || years2 <= 1 && ["y"] || ["yy", years2]; + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale2; + return substituteTimeAgo.apply(null, a); + } + function getSetRelativeTimeRounding(roundingFunction) { + if (roundingFunction === void 0) { + return round; + } + if (typeof roundingFunction === "function") { + round = roundingFunction; + return true; + } + return false; + } + function getSetRelativeTimeThreshold(threshold, limit) { + if (thresholds[threshold] === void 0) { + return false; + } + if (limit === void 0) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + if (threshold === "s") { + thresholds.ss = limit - 1; + } + return true; + } + function humanize(argWithSuffix, argThresholds) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + var withSuffix = false, th = thresholds, locale2, output; + if (typeof argWithSuffix === "object") { + argThresholds = argWithSuffix; + argWithSuffix = false; + } + if (typeof argWithSuffix === "boolean") { + withSuffix = argWithSuffix; + } + if (typeof argThresholds === "object") { + th = Object.assign({}, thresholds, argThresholds); + if (argThresholds.s != null && argThresholds.ss == null) { + th.ss = argThresholds.s - 1; + } + } + locale2 = this.localeData(); + output = relativeTime$1(this, !withSuffix, th, locale2); + if (withSuffix) { + output = locale2.pastFuture(+this, output); + } + return locale2.postformat(output); + } + var abs$1 = Math.abs; + function sign2(x2) { + return (x2 > 0) - (x2 < 0) || +x2; + } + function toISOString$1() { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + var seconds2 = abs$1(this._milliseconds) / 1e3, days2 = abs$1(this._days), months2 = abs$1(this._months), minutes2, hours2, years2, s, total = this.asSeconds(), totalSign, ymSign, daysSign, hmsSign; + if (!total) { + return "P0D"; + } + minutes2 = absFloor(seconds2 / 60); + hours2 = absFloor(minutes2 / 60); + seconds2 %= 60; + minutes2 %= 60; + years2 = absFloor(months2 / 12); + months2 %= 12; + s = seconds2 ? seconds2.toFixed(3).replace(/\.?0+$/, "") : ""; + totalSign = total < 0 ? "-" : ""; + ymSign = sign2(this._months) !== sign2(total) ? "-" : ""; + daysSign = sign2(this._days) !== sign2(total) ? "-" : ""; + hmsSign = sign2(this._milliseconds) !== sign2(total) ? "-" : ""; + return totalSign + "P" + (years2 ? ymSign + years2 + "Y" : "") + (months2 ? ymSign + months2 + "M" : "") + (days2 ? daysSign + days2 + "D" : "") + (hours2 || minutes2 || seconds2 ? "T" : "") + (hours2 ? hmsSign + hours2 + "H" : "") + (minutes2 ? hmsSign + minutes2 + "M" : "") + (seconds2 ? hmsSign + s + "S" : ""); + } + var proto$2 = Duration.prototype; + proto$2.isValid = isValid$1; + proto$2.abs = abs; + proto$2.add = add$1; + proto$2.subtract = subtract$1; + proto$2.as = as2; + proto$2.asMilliseconds = asMilliseconds; + proto$2.asSeconds = asSeconds; + proto$2.asMinutes = asMinutes; + proto$2.asHours = asHours; + proto$2.asDays = asDays; + proto$2.asWeeks = asWeeks; + proto$2.asMonths = asMonths; + proto$2.asQuarters = asQuarters; + proto$2.asYears = asYears; + proto$2.valueOf = valueOf$1; + proto$2._bubble = bubble; + proto$2.clone = clone$1; + proto$2.get = get$2; + proto$2.milliseconds = milliseconds; + proto$2.seconds = seconds; + proto$2.minutes = minutes; + proto$2.hours = hours; + proto$2.days = days; + proto$2.weeks = weeks; + proto$2.months = months; + proto$2.years = years; + proto$2.humanize = humanize; + proto$2.toISOString = toISOString$1; + proto$2.toString = toISOString$1; + proto$2.toJSON = toISOString$1; + proto$2.locale = locale; + proto$2.localeData = localeData; + proto$2.toIsoString = deprecate( + "toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)", + toISOString$1 + ); + proto$2.lang = lang; + addFormatToken("X", 0, 0, "unix"); + addFormatToken("x", 0, 0, "valueOf"); + addRegexToken("x", matchSigned); + addRegexToken("X", matchTimestamp); + addParseToken("X", function(input, array, config3) { + config3._d = new Date(parseFloat(input) * 1e3); + }); + addParseToken("x", function(input, array, config3) { + config3._d = new Date(toInt(input)); + }); + hooks.version = "2.30.1"; + setHookCallback(createLocal); + hooks.fn = proto; + hooks.min = min; + hooks.max = max; + hooks.now = now; + hooks.utc = createUTC; + hooks.unix = createUnix; + hooks.months = listMonths; + hooks.isDate = isDate2; + hooks.locale = getSetGlobalLocale; + hooks.invalid = createInvalid; + hooks.duration = createDuration; + hooks.isMoment = isMoment; + hooks.weekdays = listWeekdays; + hooks.parseZone = createInZone; + hooks.localeData = getLocale; + hooks.isDuration = isDuration; + hooks.monthsShort = listMonthsShort; + hooks.weekdaysMin = listWeekdaysMin; + hooks.defineLocale = defineLocale; + hooks.updateLocale = updateLocale; + hooks.locales = listLocales; + hooks.weekdaysShort = listWeekdaysShort; + hooks.normalizeUnits = normalizeUnits; + hooks.relativeTimeRounding = getSetRelativeTimeRounding; + hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; + hooks.calendarFormat = getCalendarFormat; + hooks.prototype = proto; + hooks.HTML5_FMT = { + DATETIME_LOCAL: "YYYY-MM-DDTHH:mm", + // + DATETIME_LOCAL_SECONDS: "YYYY-MM-DDTHH:mm:ss", + // + DATETIME_LOCAL_MS: "YYYY-MM-DDTHH:mm:ss.SSS", + // + DATE: "YYYY-MM-DD", + // + TIME: "HH:mm", + // + TIME_SECONDS: "HH:mm:ss", + // + TIME_MS: "HH:mm:ss.SSS", + // + WEEK: "GGGG-[W]WW", + // + MONTH: "YYYY-MM" + // + }; + return hooks; + }); + } +}); + +// node_modules/file-stream-rotator/FileStreamRotator.js +var require_FileStreamRotator = __commonJS({ + "node_modules/file-stream-rotator/FileStreamRotator.js"(exports2, module2) { + "use strict"; + var fs2 = __require("fs"); + var path = __require("path"); + var moment = require_moment(); + var crypto4 = __require("crypto"); + var EventEmitter3 = __require("events"); + var FileStreamRotator = {}; + module2.exports = FileStreamRotator; + var staticFrequency = ["daily", "test", "m", "h", "custom"]; + var DATE_FORMAT = "YYYYMMDDHHmm"; + var _checkNumAndType = function(type, num2) { + if (typeof num2 == "number") { + switch (type) { + case "m": + if (num2 < 0 || num2 > 60) { + return false; + } + break; + case "h": + if (num2 < 0 || num2 > 24) { + return false; + } + break; + } + return { type, digit: num2 }; + } + }; + var _checkDailyAndTest = function(freqType) { + switch (freqType) { + case "custom": + case "daily": + return { type: freqType, digit: void 0 }; + break; + case "test": + return { type: freqType, digit: 0 }; + } + return false; + }; + FileStreamRotator.getFrequency = function(frequency) { + var _f = frequency.toLowerCase().match(/^(\d+)([mh])$/); + if (_f) { + return _checkNumAndType(_f[2], parseInt(_f[1])); + } + var dailyOrTest = _checkDailyAndTest(frequency); + if (dailyOrTest) { + return dailyOrTest; + } + return false; + }; + FileStreamRotator.parseFileSize = function(size5) { + if (size5 && typeof size5 == "string") { + var _s2 = size5.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/); + if (_s2) { + switch (_s2[2]) { + case "k": + return _s2[1] * 1024; + case "m": + return _s2[1] * 1024 * 1024; + case "g": + return _s2[1] * 1024 * 1024 * 1024; + } + } + } + return null; + }; + FileStreamRotator.getDate = function(format, date_format, utc) { + date_format = date_format || DATE_FORMAT; + let currentMoment = utc ? moment.utc() : moment().local(); + if (format && staticFrequency.indexOf(format.type) !== -1) { + switch (format.type) { + case "m": + var minute = Math.floor(currentMoment.minutes() / format.digit) * format.digit; + return currentMoment.minutes(minute).format(date_format); + break; + case "h": + var hour = Math.floor(currentMoment.hour() / format.digit) * format.digit; + return currentMoment.hour(hour).format(date_format); + break; + case "daily": + case "custom": + case "test": + return currentMoment.format(date_format); + } + } + return currentMoment.format(date_format); + }; + FileStreamRotator.setAuditLog = function(max_logs, audit_file, log_file) { + var _rtn = null; + if (max_logs) { + var use_days = max_logs.toString().substr(-1); + var _num = max_logs.toString().match(/^(\d+)/); + if (Number(_num[1]) > 0) { + var baseLog = path.dirname(log_file.replace(/%DATE%.+/, "_filename")); + try { + if (audit_file) { + var full_path = path.resolve(audit_file); + _rtn = JSON.parse(fs2.readFileSync(full_path, { encoding: "utf-8" })); + } else { + var full_path = path.resolve(baseLog + "/.audit.json"); + _rtn = JSON.parse(fs2.readFileSync(full_path, { encoding: "utf-8" })); + } + } catch (e) { + if (e.code !== "ENOENT") { + return null; + } + _rtn = { + keep: { + days: false, + amount: Number(_num[1]) + }, + auditLog: audit_file || baseLog + "/.audit.json", + files: [] + }; + } + _rtn.keep = { + days: use_days === "d", + amount: Number(_num[1]) + }; + } + } + return _rtn; + }; + FileStreamRotator.writeAuditLog = function(audit, verbose) { + try { + mkDirForFile(audit.auditLog); + fs2.writeFileSync(audit.auditLog, JSON.stringify(audit, null, 4)); + } catch (e) { + if (verbose) { + console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] Failed to store log audit at:", audit.auditLog, "Error:", e); + } + } + }; + function removeFile(file, verbose) { + if (file.hash === crypto4.createHash(file.hashType).update(file.name + "LOG_FILE" + file.date).digest("hex")) { + try { + if (fs2.existsSync(file.name)) { + fs2.unlinkSync(file.name); + } + } catch (e) { + if (verbose) { + console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] Could not remove old log file: ", file.name); + } + } + } + } + function createCurrentSymLink(logfile, name, verbose) { + let symLinkName = name || "current.log"; + let logPath = path.dirname(logfile); + let logfileName = path.basename(logfile); + let current = logPath + "/" + symLinkName; + try { + let stats = fs2.lstatSync(current); + if (stats.isSymbolicLink()) { + fs2.unlinkSync(current); + fs2.symlinkSync(logfileName, current); + } + } catch (err) { + if (err && err.code == "ENOENT") { + try { + fs2.symlinkSync(logfileName, current); + } catch (e) { + if (verbose) { + console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] Could not create symlink file: ", current, " -> ", logfileName); + } + } + } + } + } + function createLogWatcher(logfile, verbose, cb) { + if (!logfile) return null; + try { + let stats = fs2.lstatSync(logfile); + return fs2.watch(logfile, function(event, filename) { + if (event == "rename") { + try { + let stats2 = fs2.lstatSync(logfile); + } catch (err) { + cb(err, logfile); + } + } + }); + } catch (err) { + if (verbose) { + console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Could not add watcher for " + logfile); + } + } + } + FileStreamRotator.addLogToAudit = function(logfile, audit, stream4, verbose) { + if (audit && audit.files) { + var index2 = audit.files.findIndex(function(file) { + return file.name === logfile; + }); + if (index2 !== -1) { + return audit; + } + var time = Date.now(); + audit.files.push({ + date: time, + name: logfile, + hash: crypto4.createHash(audit.hashType).update(logfile + "LOG_FILE" + time).digest("hex") + }); + if (audit.keep.days) { + var oldestDate = moment().subtract(audit.keep.amount, "days").valueOf(); + var recentFiles = audit.files.filter(function(file) { + if (file.date > oldestDate) { + return true; + } + file.hashType = audit.hashType; + removeFile(file, verbose); + stream4.emit("logRemoved", file); + return false; + }); + audit.files = recentFiles; + } else { + var filesToKeep = audit.files.splice(-audit.keep.amount); + if (audit.files.length > 0) { + audit.files.filter(function(file) { + file.hashType = audit.hashType; + removeFile(file, verbose); + stream4.emit("logRemoved", file); + return false; + }); + } + audit.files = filesToKeep; + } + FileStreamRotator.writeAuditLog(audit, verbose); + } + return audit; + }; + FileStreamRotator.getStream = function(options) { + var frequencyMetaData = null; + var curDate = null; + var self2 = this; + if (!options.filename) { + console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] No filename supplied. Defaulting to STDOUT"); + return process.stdout; + } + if (options.frequency) { + frequencyMetaData = self2.getFrequency(options.frequency); + } + let auditLog = self2.setAuditLog(options.max_logs, options.audit_file, options.filename); + if (auditLog != null) { + auditLog.hashType = options.audit_hash_type !== void 0 ? options.audit_hash_type : "md5"; + } + self2.verbose = options.verbose !== void 0 ? options.verbose : true; + var fileSize = null; + var fileCount = 0; + var curSize = 0; + if (options.size) { + fileSize = FileStreamRotator.parseFileSize(options.size); + } + var dateFormat = options.date_format || DATE_FORMAT; + if (frequencyMetaData && frequencyMetaData.type == "daily") { + if (!options.date_format) { + dateFormat = "YYYY-MM-DD"; + } + if (moment().format(dateFormat) != moment().endOf("day").format(dateFormat) || moment().format(dateFormat) == moment().add(1, "day").format(dateFormat)) { + if (self2.verbose) { + console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Changing type to custom as date format changes more often than once a day or not every day"); + } + frequencyMetaData.type = "custom"; + } + } + if (frequencyMetaData) { + curDate = options.frequency ? self2.getDate(frequencyMetaData, dateFormat, options.utc) : ""; + } + options.create_symlink = options.create_symlink || false; + options.extension = options.extension || ""; + var filename = options.filename; + var oldFile = null; + var logfile = filename + (curDate ? "." + curDate : ""); + if (filename.match(/%DATE%/)) { + logfile = filename.replace(/%DATE%/g, curDate ? curDate : self2.getDate(null, dateFormat, options.utc)); + } + if (fileSize) { + var lastLogFile = null; + var t_log = logfile; + var f = null; + if (auditLog && auditLog.files && auditLog.files instanceof Array && auditLog.files.length > 0) { + var lastEntry = auditLog.files[auditLog.files.length - 1].name; + if (lastEntry.match(t_log)) { + var lastCount = lastEntry.match(t_log + "\\.(\\d+)"); + if (lastCount) { + t_log = lastEntry; + fileCount = lastCount[1]; + } + } + } + if (fileCount == 0 && t_log == logfile) { + t_log += options.extension; + } + while (f = fs2.existsSync(t_log)) { + lastLogFile = t_log; + fileCount++; + t_log = logfile + "." + fileCount + options.extension; + } + if (lastLogFile) { + var lastLogFileStats = fs2.statSync(lastLogFile); + if (lastLogFileStats.size < fileSize) { + t_log = lastLogFile; + fileCount--; + curSize = lastLogFileStats.size; + } + } + logfile = t_log; + } else { + logfile += options.extension; + } + if (self2.verbose) { + console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Logging to: ", logfile); + } + mkDirForFile(logfile); + var file_options = options.file_options || { flags: "a" }; + var rotateStream = fs2.createWriteStream(logfile, file_options); + if (curDate && frequencyMetaData && staticFrequency.indexOf(frequencyMetaData.type) > -1 || fileSize > 0) { + if (self2.verbose) { + console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Rotating file: ", frequencyMetaData ? frequencyMetaData.type : "", fileSize ? "size: " + fileSize : ""); + } + var stream4 = new EventEmitter3(); + stream4.auditLog = auditLog; + stream4.end = function() { + rotateStream.end.apply(rotateStream, arguments); + }; + BubbleEvents(rotateStream, stream4); + stream4.on("close", function() { + if (logWatcher) { + logWatcher.close(); + } + }); + stream4.on("new", function(newLog) { + stream4.auditLog = self2.addLogToAudit(newLog, stream4.auditLog, stream4, self2.verbose); + if (options.create_symlink) { + createCurrentSymLink(newLog, options.symlink_name, self2.verbose); + } + if (options.watch_log) { + stream4.emit("addWatcher", newLog); + } + }); + var logWatcher; + stream4.on("addWatcher", function(newLog) { + if (logWatcher) { + logWatcher.close(); + } + if (!options.watch_log) { + return; + } + logWatcher = createLogWatcher(newLog, self2.verbose, function(err, newLog2) { + stream4.emit("createLog", newLog2); + }); + }); + stream4.on("createLog", function(file) { + try { + let stats = fs2.lstatSync(file); + } catch (err) { + if (rotateStream && rotateStream.end == "function") { + rotateStream.end(); + } + rotateStream = fs2.createWriteStream(file, file_options); + stream4.emit("new", file); + BubbleEvents(rotateStream, stream4); + } + }); + stream4.write = function(str, encoding) { + var newDate = frequencyMetaData ? this.getDate(frequencyMetaData, dateFormat, options.utc) : curDate; + if (newDate != curDate || fileSize && curSize > fileSize) { + var newLogfile = filename + (curDate && frequencyMetaData ? "." + newDate : ""); + if (filename.match(/%DATE%/) && curDate) { + newLogfile = filename.replace(/%DATE%/g, newDate); + } + if (fileSize && curSize > fileSize) { + fileCount++; + newLogfile += "." + fileCount + options.extension; + } else { + fileCount = 0; + newLogfile += options.extension; + } + curSize = 0; + if (self2.verbose) { + console.log(/* @__PURE__ */ new Date(), __require("util").format("[FileStreamRotator] Changing logs from %s to %s", logfile, newLogfile)); + } + curDate = newDate; + oldFile = logfile; + logfile = newLogfile; + if (options.end_stream === true) { + rotateStream.end(); + } else { + rotateStream.destroy(); + } + mkDirForFile(logfile); + rotateStream = fs2.createWriteStream(newLogfile, file_options); + stream4.emit("new", newLogfile); + stream4.emit("rotate", oldFile, newLogfile); + BubbleEvents(rotateStream, stream4); + } + rotateStream.write(str, encoding); + curSize += Buffer.byteLength(str, encoding); + }.bind(this); + process.nextTick(function() { + stream4.emit("new", logfile); + }); + stream4.emit("new", logfile); + return stream4; + } else { + if (self2.verbose) { + console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] File won't be rotated: ", options.frequency, options.size); + } + process.nextTick(function() { + rotateStream.emit("new", logfile); + }); + return rotateStream; + } + }; + var mkDirForFile = function(pathWithFile) { + var _path = path.dirname(pathWithFile); + _path.split(path.sep).reduce( + function(fullPath, folder) { + fullPath += folder + path.sep; + if (!fs2.existsSync(fullPath)) { + try { + fs2.mkdirSync(fullPath); + } catch (e) { + if (e.code !== "EEXIST") { + throw e; + } + } + } + return fullPath; + }, + "" + ); + }; + var BubbleEvents = function BubbleEvents2(emitter, proxy) { + emitter.on("close", function() { + proxy.emit("close"); + }); + emitter.on("finish", function() { + proxy.emit("finish"); + }); + emitter.on("error", function(err) { + proxy.emit("error", err); + }); + emitter.on("open", function(fd2) { + proxy.emit("open", fd2); + }); + }; + } +}); + +// node_modules/winston-daily-rotate-file/daily-rotate-file.js +var require_daily_rotate_file = __commonJS({ + "node_modules/winston-daily-rotate-file/daily-rotate-file.js"(exports2, module2) { + var fs2 = __require("fs"); + var os2 = __require("os"); + var path = __require("path"); + var util3 = __require("util"); + var zlib2 = __require("zlib"); + var hash2 = require_object_hash(); + var MESSAGE = require_triple_beam().MESSAGE; + var PassThrough = __require("stream").PassThrough; + var Transport2 = require_winston_transport(); + var loggerDefaults = { + json: false, + colorize: false, + eol: os2.EOL, + logstash: null, + prettyPrint: false, + label: null, + stringify: false, + depth: null, + showLevel: true, + timestamp: () => { + return (/* @__PURE__ */ new Date()).toISOString(); + } + }; + var DailyRotateFile2 = function(options) { + options = options || {}; + Transport2.call(this, options); + function throwIf(target) { + Array.prototype.slice.call(arguments, 1).forEach((name) => { + if (options[name]) { + throw new Error("Cannot set " + name + " and " + target + " together"); + } + }); + } + function getMaxSize(size5) { + if (size5 && typeof size5 === "string") { + if (size5.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/)) { + return size5; + } + } else if (size5 && Number.isInteger(size5)) { + const sizeK = Math.round(size5 / 1024); + return sizeK === 0 ? "1k" : sizeK + "k"; + } + return null; + } + function isValidFileName(filename) { + return !/["<>|:*?\\/\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test( + filename + ); + } + function isValidDirName(dirname2) { + return !/["<>|\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test( + dirname2 + ); + } + this.options = Object.assign({}, loggerDefaults, options); + if (options.stream) { + throwIf("stream", "filename", "maxsize"); + this.logStream = new PassThrough(); + this.logStream.pipe(options.stream); + } else { + this.filename = options.filename ? path.basename(options.filename) : "winston.log"; + this.dirname = options.dirname || path.dirname(options.filename); + if (!isValidFileName(this.filename) || !isValidDirName(this.dirname)) { + throw new Error("Your path or filename contain an invalid character."); + } + this.logStream = require_FileStreamRotator().getStream({ + filename: path.join(this.dirname, this.filename), + frequency: options.frequency ? options.frequency : "custom", + date_format: options.datePattern ? options.datePattern : "YYYY-MM-DD", + verbose: false, + size: getMaxSize(options.maxSize), + max_logs: options.maxFiles, + end_stream: true, + audit_file: options.auditFile ? options.auditFile : path.join(this.dirname, "." + hash2(options) + "-audit.json"), + file_options: options.options ? options.options : { flags: "a" }, + utc: options.utc ? options.utc : false, + extension: options.extension ? options.extension : "", + create_symlink: options.createSymlink ? options.createSymlink : false, + symlink_name: options.symlinkName ? options.symlinkName : "current.log", + watch_log: options.watchLog ? options.watchLog : false, + audit_hash_type: options.auditHashType ? options.auditHashType : "sha256" + }); + this.logStream.on("new", (newFile) => { + this.emit("new", newFile); + }); + this.logStream.on("rotate", (oldFile, newFile) => { + this.emit("rotate", oldFile, newFile); + }); + this.logStream.on("logRemoved", (params) => { + if (options.zippedArchive) { + const gzName = params.name + ".gz"; + try { + fs2.unlinkSync(gzName); + } catch (err) { + if (err.code !== "ENOENT") { + err.message = `Error occurred while removing ${gzName}: ${err.message}`; + this.emit("error", err); + return; + } + } + this.emit("logRemoved", gzName); + return; + } + this.emit("logRemoved", params.name); + }); + if (options.zippedArchive) { + this.logStream.on("rotate", (oldFile) => { + try { + if (!fs2.existsSync(oldFile)) { + return; + } + } catch (err) { + err.message = `Error occurred while checking existence of ${oldFile}: ${err.message}`; + this.emit("error", err); + return; + } + try { + if (fs2.existsSync(`${oldFile}.gz`)) { + return; + } + } catch (err) { + err.message = `Error occurred while checking existence of ${oldFile}.gz: ${err.message}`; + this.emit("error", err); + return; + } + const gzip = zlib2.createGzip(); + const inp = fs2.createReadStream(oldFile); + inp.on("error", (err) => { + err.message = `Error occurred while reading ${oldFile}: ${err.message}`; + this.emit("error", err); + }); + const out = fs2.createWriteStream(oldFile + ".gz"); + out.on("error", (err) => { + err.message = `Error occurred while writing ${oldFile}.gz: ${err.message}`; + this.emit("error", err); + }); + inp.pipe(gzip).pipe(out).on("finish", () => { + try { + fs2.unlinkSync(oldFile); + } catch (err) { + if (err.code !== "ENOENT") { + err.message = `Error occurred while removing ${oldFile}: ${err.message}`; + this.emit("error", err); + return; + } + } + this.emit("archive", oldFile + ".gz"); + }); + }); + } + if (options.watchLog) { + this.logStream.on("addWatcher", (newFile) => { + this.emit("addWatcher", newFile); + }); + } + } + }; + module2.exports = DailyRotateFile2; + util3.inherits(DailyRotateFile2, Transport2); + DailyRotateFile2.prototype.name = "dailyRotateFile"; + var noop2 = function() { + }; + DailyRotateFile2.prototype.log = function(info, callback) { + callback = callback || noop2; + this.logStream.write(info[MESSAGE] + this.options.eol); + this.emit("logged", info); + callback(null, true); + }; + DailyRotateFile2.prototype.close = function() { + if (this.logStream) { + this.logStream.end(() => { + this.emit("finish"); + }); + } + }; + DailyRotateFile2.prototype.query = function(options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } + if (!this.options.json) { + throw new Error( + "query() may not be used without the json option being set to true" + ); + } + if (!this.filename) { + throw new Error("query() may not be used when initializing with a stream"); + } + let results = []; + options = options || {}; + options.rows = options.rows || options.limit || 10; + options.start = options.start || 0; + options.until = options.until || /* @__PURE__ */ new Date(); + if (typeof options.until !== "object") { + options.until = new Date(options.until); + } + options.from = options.from || options.until - 24 * 60 * 60 * 1e3; + if (typeof options.from !== "object") { + options.from = new Date(options.from); + } + options.order = options.order || "desc"; + const logFiles = (() => { + const fileRegex = new RegExp(this.filename.replace("%DATE%", ".*"), "i"); + return fs2.readdirSync(this.dirname).filter((file) => path.basename(file).match(fileRegex)); + })(); + if (logFiles.length === 0 && callback) { + callback(null, results); + } + const processLogFile = (file) => { + if (!file) { + return; + } + const logFile = path.join(this.dirname, file); + let buff = ""; + let stream4; + if (file.endsWith(".gz")) { + stream4 = new PassThrough(); + const inp = fs2.createReadStream(logFile); + inp.on("error", (err) => { + err.message = `Error occurred while reading ${logFile}: ${err.message}`; + stream4.emit("error", err); + }); + inp.pipe(zlib2.createGunzip()).pipe(stream4); + } else { + stream4 = fs2.createReadStream(logFile, { + encoding: "utf8" + }); + } + stream4.on("error", (err) => { + if (stream4.readable) { + stream4.destroy(); + } + if (!callback) { + return; + } + return err.code === "ENOENT" ? callback(null, results) : callback(err); + }); + stream4.on("data", (data) => { + data = (buff + data).split(/\n+/); + const l = data.length - 1; + for (let i = 0; i < l; i++) { + add(data[i]); + } + buff = data[l]; + }); + stream4.on("end", () => { + if (buff) { + add(buff, true); + } + if (logFiles.length) { + processLogFile(logFiles.shift()); + } else if (callback) { + results.sort((a, b2) => { + const d1 = new Date(a.timestamp).getTime(); + const d2 = new Date(b2.timestamp).getTime(); + return d1 > d2 ? 1 : d1 < d2 ? -1 : 0; + }); + if (options.order === "desc") { + results = results.reverse(); + } + const start = options.start || 0; + const limit = options.limit || results.length; + results = results.slice(start, start + limit); + if (options.fields) { + results = results.map((log) => { + const obj = {}; + options.fields.forEach((key) => { + obj[key] = log[key]; + }); + return obj; + }); + } + callback(null, results); + } + }); + function add(buff2, attempt) { + try { + const log = JSON.parse(buff2); + if (!log || typeof log !== "object") { + return; + } + const time = new Date(log.timestamp); + if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) { + return; + } + results.push(log); + } catch (e) { + if (!attempt) { + stream4.emit("error", e); + } + } + } + }; + processLogFile(logFiles.shift()); + }; + } +}); + +// node_modules/winston-daily-rotate-file/index.js +var require_winston_daily_rotate_file = __commonJS({ + "node_modules/winston-daily-rotate-file/index.js"(exports2, module2) { + var winston2 = require_winston(); + var DailyRotateFile2 = require_daily_rotate_file(); + winston2.transports.DailyRotateFile = DailyRotateFile2; + module2.exports = DailyRotateFile2; + } +}); + +// node_modules/abitype/dist/esm/version.js +var version; +var init_version = __esm({ + "node_modules/abitype/dist/esm/version.js"() { + version = "1.0.8"; + } +}); + +// node_modules/abitype/dist/esm/errors.js +var BaseError; +var init_errors = __esm({ + "node_modules/abitype/dist/esm/errors.js"() { + init_version(); + BaseError = class _BaseError extends Error { + constructor(shortMessage, args = {}) { + const details = args.cause instanceof _BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details; + const docsPath6 = args.cause instanceof _BaseError ? args.cause.docsPath || args.docsPath : args.docsPath; + const message = [ + shortMessage || "An error occurred.", + "", + ...args.metaMessages ? [...args.metaMessages, ""] : [], + ...docsPath6 ? [`Docs: https://abitype.dev${docsPath6}`] : [], + ...details ? [`Details: ${details}`] : [], + `Version: abitype@${version}` + ].join("\n"); + super(message); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "docsPath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metaMessages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "shortMessage", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiTypeError" + }); + if (args.cause) + this.cause = args.cause; + this.details = details; + this.docsPath = docsPath6; + this.metaMessages = args.metaMessages; + this.shortMessage = shortMessage; + } + }; + } +}); + +// node_modules/abitype/dist/esm/regex.js +function execTyped(regex, string) { + const match = regex.exec(string); + return match?.groups; +} +var bytesRegex, integerRegex, isTupleRegex; +var init_regex = __esm({ + "node_modules/abitype/dist/esm/regex.js"() { + bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; + integerRegex = /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; + isTupleRegex = /^\(.+?\).*?$/; + } +}); + +// node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js +function formatAbiParameter(abiParameter) { + let type = abiParameter.type; + if (tupleRegex.test(abiParameter.type) && "components" in abiParameter) { + type = "("; + const length = abiParameter.components.length; + for (let i = 0; i < length; i++) { + const component = abiParameter.components[i]; + type += formatAbiParameter(component); + if (i < length - 1) + type += ", "; + } + const result = execTyped(tupleRegex, abiParameter.type); + type += `)${result?.array ?? ""}`; + return formatAbiParameter({ + ...abiParameter, + type + }); + } + if ("indexed" in abiParameter && abiParameter.indexed) + type = `${type} indexed`; + if (abiParameter.name) + return `${type} ${abiParameter.name}`; + return type; +} +var tupleRegex; +var init_formatAbiParameter = __esm({ + "node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js"() { + init_regex(); + tupleRegex = /^tuple(?(\[(\d*)\])*)$/; + } +}); + +// node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js +function formatAbiParameters(abiParameters) { + let params = ""; + const length = abiParameters.length; + for (let i = 0; i < length; i++) { + const abiParameter = abiParameters[i]; + params += formatAbiParameter(abiParameter); + if (i !== length - 1) + params += ", "; + } + return params; +} +var init_formatAbiParameters = __esm({ + "node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js"() { + init_formatAbiParameter(); + } +}); + +// node_modules/abitype/dist/esm/human-readable/formatAbiItem.js +function formatAbiItem(abiItem) { + if (abiItem.type === "function") + return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== "nonpayable" ? ` ${abiItem.stateMutability}` : ""}${abiItem.outputs?.length ? ` returns (${formatAbiParameters(abiItem.outputs)})` : ""}`; + if (abiItem.type === "event") + return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; + if (abiItem.type === "error") + return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; + if (abiItem.type === "constructor") + return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === "payable" ? " payable" : ""}`; + if (abiItem.type === "fallback") + return `fallback() external${abiItem.stateMutability === "payable" ? " payable" : ""}`; + return "receive() external payable"; +} +var init_formatAbiItem = __esm({ + "node_modules/abitype/dist/esm/human-readable/formatAbiItem.js"() { + init_formatAbiParameters(); + } +}); + +// node_modules/abitype/dist/esm/human-readable/runtime/signatures.js +function isErrorSignature(signature) { + return errorSignatureRegex.test(signature); +} +function execErrorSignature(signature) { + return execTyped(errorSignatureRegex, signature); +} +function isEventSignature(signature) { + return eventSignatureRegex.test(signature); +} +function execEventSignature(signature) { + return execTyped(eventSignatureRegex, signature); +} +function isFunctionSignature(signature) { + return functionSignatureRegex.test(signature); +} +function execFunctionSignature(signature) { + return execTyped(functionSignatureRegex, signature); +} +function isStructSignature(signature) { + return structSignatureRegex.test(signature); +} +function execStructSignature(signature) { + return execTyped(structSignatureRegex, signature); +} +function isConstructorSignature(signature) { + return constructorSignatureRegex.test(signature); +} +function execConstructorSignature(signature) { + return execTyped(constructorSignatureRegex, signature); +} +function isFallbackSignature(signature) { + return fallbackSignatureRegex.test(signature); +} +function execFallbackSignature(signature) { + return execTyped(fallbackSignatureRegex, signature); +} +function isReceiveSignature(signature) { + return receiveSignatureRegex.test(signature); +} +var errorSignatureRegex, eventSignatureRegex, functionSignatureRegex, structSignatureRegex, constructorSignatureRegex, fallbackSignatureRegex, receiveSignatureRegex, modifiers, eventModifiers, functionModifiers; +var init_signatures = __esm({ + "node_modules/abitype/dist/esm/human-readable/runtime/signatures.js"() { + init_regex(); + errorSignatureRegex = /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; + eventSignatureRegex = /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; + functionSignatureRegex = /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/; + structSignatureRegex = /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/; + constructorSignatureRegex = /^constructor\((?.*?)\)(?:\s(?payable{1}))?$/; + fallbackSignatureRegex = /^fallback\(\) external(?:\s(?payable{1}))?$/; + receiveSignatureRegex = /^receive\(\) external payable$/; + modifiers = /* @__PURE__ */ new Set([ + "memory", + "indexed", + "storage", + "calldata" + ]); + eventModifiers = /* @__PURE__ */ new Set(["indexed"]); + functionModifiers = /* @__PURE__ */ new Set([ + "calldata", + "memory", + "storage" + ]); + } +}); + +// node_modules/abitype/dist/esm/human-readable/errors/abiItem.js +var InvalidAbiItemError, UnknownTypeError, UnknownSolidityTypeError; +var init_abiItem = __esm({ + "node_modules/abitype/dist/esm/human-readable/errors/abiItem.js"() { + init_errors(); + InvalidAbiItemError = class extends BaseError { + constructor({ signature }) { + super("Failed to parse ABI item.", { + details: `parseAbiItem(${JSON.stringify(signature, null, 2)})`, + docsPath: "/api/human#parseabiitem-1" + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidAbiItemError" + }); + } + }; + UnknownTypeError = class extends BaseError { + constructor({ type }) { + super("Unknown type.", { + metaMessages: [ + `Type "${type}" is not a valid ABI type. Perhaps you forgot to include a struct signature?` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownTypeError" + }); + } + }; + UnknownSolidityTypeError = class extends BaseError { + constructor({ type }) { + super("Unknown type.", { + metaMessages: [`Type "${type}" is not a valid ABI type.`] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownSolidityTypeError" + }); + } + }; + } +}); + +// node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js +var InvalidAbiParametersError, InvalidParameterError, SolidityProtectedKeywordError, InvalidModifierError, InvalidFunctionModifierError, InvalidAbiTypeParameterError; +var init_abiParameter = __esm({ + "node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js"() { + init_errors(); + InvalidAbiParametersError = class extends BaseError { + constructor({ params }) { + super("Failed to parse ABI parameters.", { + details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`, + docsPath: "/api/human#parseabiparameters-1" + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidAbiParametersError" + }); + } + }; + InvalidParameterError = class extends BaseError { + constructor({ param }) { + super("Invalid ABI parameter.", { + details: param + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidParameterError" + }); + } + }; + SolidityProtectedKeywordError = class extends BaseError { + constructor({ param, name }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `"${name}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "SolidityProtectedKeywordError" + }); + } + }; + InvalidModifierError = class extends BaseError { + constructor({ param, type, modifier }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidModifierError" + }); + } + }; + InvalidFunctionModifierError = class extends BaseError { + constructor({ param, type, modifier }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.`, + `Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidFunctionModifierError" + }); + } + }; + InvalidAbiTypeParameterError = class extends BaseError { + constructor({ abiParameter }) { + super("Invalid ABI parameter.", { + details: JSON.stringify(abiParameter, null, 2), + metaMessages: ["ABI parameter type is invalid."] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidAbiTypeParameterError" + }); + } + }; + } +}); + +// node_modules/abitype/dist/esm/human-readable/errors/signature.js +var InvalidSignatureError, UnknownSignatureError, InvalidStructSignatureError; +var init_signature = __esm({ + "node_modules/abitype/dist/esm/human-readable/errors/signature.js"() { + init_errors(); + InvalidSignatureError = class extends BaseError { + constructor({ signature, type }) { + super(`Invalid ${type} signature.`, { + details: signature + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidSignatureError" + }); + } + }; + UnknownSignatureError = class extends BaseError { + constructor({ signature }) { + super("Unknown signature.", { + details: signature + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownSignatureError" + }); + } + }; + InvalidStructSignatureError = class extends BaseError { + constructor({ signature }) { + super("Invalid struct signature.", { + details: signature, + metaMessages: ["No properties exist."] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidStructSignatureError" + }); + } + }; + } +}); + +// node_modules/abitype/dist/esm/human-readable/errors/struct.js +var CircularReferenceError; +var init_struct = __esm({ + "node_modules/abitype/dist/esm/human-readable/errors/struct.js"() { + init_errors(); + CircularReferenceError = class extends BaseError { + constructor({ type }) { + super("Circular reference detected.", { + metaMessages: [`Struct "${type}" is a circular reference.`] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "CircularReferenceError" + }); + } + }; + } +}); + +// node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js +var InvalidParenthesisError; +var init_splitParameters = __esm({ + "node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js"() { + init_errors(); + InvalidParenthesisError = class extends BaseError { + constructor({ current, depth }) { + super("Unbalanced parentheses.", { + metaMessages: [ + `"${current.trim()}" has too many ${depth > 0 ? "opening" : "closing"} parentheses.` + ], + details: `Depth "${depth}"` + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidParenthesisError" + }); + } + }; + } +}); + +// node_modules/abitype/dist/esm/human-readable/runtime/cache.js +function getParameterCacheKey(param, type, structs) { + let structKey = ""; + if (structs) + for (const struct of Object.entries(structs)) { + if (!struct) + continue; + let propertyKey = ""; + for (const property of struct[1]) { + propertyKey += `[${property.type}${property.name ? `:${property.name}` : ""}]`; + } + structKey += `(${struct[0]}{${propertyKey}})`; + } + if (type) + return `${type}:${param}${structKey}`; + return param; +} +var parameterCache; +var init_cache = __esm({ + "node_modules/abitype/dist/esm/human-readable/runtime/cache.js"() { + parameterCache = /* @__PURE__ */ new Map([ + // Unnamed + ["address", { type: "address" }], + ["bool", { type: "bool" }], + ["bytes", { type: "bytes" }], + ["bytes32", { type: "bytes32" }], + ["int", { type: "int256" }], + ["int256", { type: "int256" }], + ["string", { type: "string" }], + ["uint", { type: "uint256" }], + ["uint8", { type: "uint8" }], + ["uint16", { type: "uint16" }], + ["uint24", { type: "uint24" }], + ["uint32", { type: "uint32" }], + ["uint64", { type: "uint64" }], + ["uint96", { type: "uint96" }], + ["uint112", { type: "uint112" }], + ["uint160", { type: "uint160" }], + ["uint192", { type: "uint192" }], + ["uint256", { type: "uint256" }], + // Named + ["address owner", { type: "address", name: "owner" }], + ["address to", { type: "address", name: "to" }], + ["bool approved", { type: "bool", name: "approved" }], + ["bytes _data", { type: "bytes", name: "_data" }], + ["bytes data", { type: "bytes", name: "data" }], + ["bytes signature", { type: "bytes", name: "signature" }], + ["bytes32 hash", { type: "bytes32", name: "hash" }], + ["bytes32 r", { type: "bytes32", name: "r" }], + ["bytes32 root", { type: "bytes32", name: "root" }], + ["bytes32 s", { type: "bytes32", name: "s" }], + ["string name", { type: "string", name: "name" }], + ["string symbol", { type: "string", name: "symbol" }], + ["string tokenURI", { type: "string", name: "tokenURI" }], + ["uint tokenId", { type: "uint256", name: "tokenId" }], + ["uint8 v", { type: "uint8", name: "v" }], + ["uint256 balance", { type: "uint256", name: "balance" }], + ["uint256 tokenId", { type: "uint256", name: "tokenId" }], + ["uint256 value", { type: "uint256", name: "value" }], + // Indexed + [ + "event:address indexed from", + { type: "address", name: "from", indexed: true } + ], + ["event:address indexed to", { type: "address", name: "to", indexed: true }], + [ + "event:uint indexed tokenId", + { type: "uint256", name: "tokenId", indexed: true } + ], + [ + "event:uint256 indexed tokenId", + { type: "uint256", name: "tokenId", indexed: true } + ] + ]); + } +}); + +// node_modules/abitype/dist/esm/human-readable/runtime/utils.js +function parseSignature(signature, structs = {}) { + if (isFunctionSignature(signature)) + return parseFunctionSignature(signature, structs); + if (isEventSignature(signature)) + return parseEventSignature(signature, structs); + if (isErrorSignature(signature)) + return parseErrorSignature(signature, structs); + if (isConstructorSignature(signature)) + return parseConstructorSignature(signature, structs); + if (isFallbackSignature(signature)) + return parseFallbackSignature(signature); + if (isReceiveSignature(signature)) + return { + type: "receive", + stateMutability: "payable" + }; + throw new UnknownSignatureError({ signature }); +} +function parseFunctionSignature(signature, structs = {}) { + const match = execFunctionSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "function" }); + const inputParams = splitParameters(match.parameters); + const inputs = []; + const inputLength = inputParams.length; + for (let i = 0; i < inputLength; i++) { + inputs.push(parseAbiParameter(inputParams[i], { + modifiers: functionModifiers, + structs, + type: "function" + })); + } + const outputs = []; + if (match.returns) { + const outputParams = splitParameters(match.returns); + const outputLength = outputParams.length; + for (let i = 0; i < outputLength; i++) { + outputs.push(parseAbiParameter(outputParams[i], { + modifiers: functionModifiers, + structs, + type: "function" + })); + } + } + return { + name: match.name, + type: "function", + stateMutability: match.stateMutability ?? "nonpayable", + inputs, + outputs + }; +} +function parseEventSignature(signature, structs = {}) { + const match = execEventSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "event" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) + abiParameters.push(parseAbiParameter(params[i], { + modifiers: eventModifiers, + structs, + type: "event" + })); + return { name: match.name, type: "event", inputs: abiParameters }; +} +function parseErrorSignature(signature, structs = {}) { + const match = execErrorSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "error" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) + abiParameters.push(parseAbiParameter(params[i], { structs, type: "error" })); + return { name: match.name, type: "error", inputs: abiParameters }; +} +function parseConstructorSignature(signature, structs = {}) { + const match = execConstructorSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "constructor" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) + abiParameters.push(parseAbiParameter(params[i], { structs, type: "constructor" })); + return { + type: "constructor", + stateMutability: match.stateMutability ?? "nonpayable", + inputs: abiParameters + }; +} +function parseFallbackSignature(signature) { + const match = execFallbackSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "fallback" }); + return { + type: "fallback", + stateMutability: match.stateMutability ?? "nonpayable" + }; +} +function parseAbiParameter(param, options) { + const parameterCacheKey = getParameterCacheKey(param, options?.type, options?.structs); + if (parameterCache.has(parameterCacheKey)) + return parameterCache.get(parameterCacheKey); + const isTuple = isTupleRegex.test(param); + const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param); + if (!match) + throw new InvalidParameterError({ param }); + if (match.name && isSolidityKeyword(match.name)) + throw new SolidityProtectedKeywordError({ param, name: match.name }); + const name = match.name ? { name: match.name } : {}; + const indexed = match.modifier === "indexed" ? { indexed: true } : {}; + const structs = options?.structs ?? {}; + let type; + let components = {}; + if (isTuple) { + type = "tuple"; + const params = splitParameters(match.type); + const components_ = []; + const length = params.length; + for (let i = 0; i < length; i++) { + components_.push(parseAbiParameter(params[i], { structs })); + } + components = { components: components_ }; + } else if (match.type in structs) { + type = "tuple"; + components = { components: structs[match.type] }; + } else if (dynamicIntegerRegex.test(match.type)) { + type = `${match.type}256`; + } else { + type = match.type; + if (!(options?.type === "struct") && !isSolidityType(type)) + throw new UnknownSolidityTypeError({ type }); + } + if (match.modifier) { + if (!options?.modifiers?.has?.(match.modifier)) + throw new InvalidModifierError({ + param, + type: options?.type, + modifier: match.modifier + }); + if (functionModifiers.has(match.modifier) && !isValidDataLocation(type, !!match.array)) + throw new InvalidFunctionModifierError({ + param, + type: options?.type, + modifier: match.modifier + }); + } + const abiParameter = { + type: `${type}${match.array ?? ""}`, + ...name, + ...indexed, + ...components + }; + parameterCache.set(parameterCacheKey, abiParameter); + return abiParameter; +} +function splitParameters(params, result = [], current = "", depth = 0) { + const length = params.trim().length; + for (let i = 0; i < length; i++) { + const char = params[i]; + const tail = params.slice(i + 1); + switch (char) { + case ",": + return depth === 0 ? splitParameters(tail, [...result, current.trim()]) : splitParameters(tail, result, `${current}${char}`, depth); + case "(": + return splitParameters(tail, result, `${current}${char}`, depth + 1); + case ")": + return splitParameters(tail, result, `${current}${char}`, depth - 1); + default: + return splitParameters(tail, result, `${current}${char}`, depth); + } + } + if (current === "") + return result; + if (depth !== 0) + throw new InvalidParenthesisError({ current, depth }); + result.push(current.trim()); + return result; +} +function isSolidityType(type) { + return type === "address" || type === "bool" || type === "function" || type === "string" || bytesRegex.test(type) || integerRegex.test(type); +} +function isSolidityKeyword(name) { + return name === "address" || name === "bool" || name === "function" || name === "string" || name === "tuple" || bytesRegex.test(name) || integerRegex.test(name) || protectedKeywordsRegex.test(name); +} +function isValidDataLocation(type, isArray2) { + return isArray2 || type === "bytes" || type === "string" || type === "tuple"; +} +var abiParameterWithoutTupleRegex, abiParameterWithTupleRegex, dynamicIntegerRegex, protectedKeywordsRegex; +var init_utils = __esm({ + "node_modules/abitype/dist/esm/human-readable/runtime/utils.js"() { + init_regex(); + init_abiItem(); + init_abiParameter(); + init_signature(); + init_splitParameters(); + init_cache(); + init_signatures(); + abiParameterWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; + abiParameterWithTupleRegex = /^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; + dynamicIntegerRegex = /^u?int$/; + protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/; + } +}); + +// node_modules/abitype/dist/esm/human-readable/runtime/structs.js +function parseStructs(signatures) { + const shallowStructs = {}; + const signaturesLength = signatures.length; + for (let i = 0; i < signaturesLength; i++) { + const signature = signatures[i]; + if (!isStructSignature(signature)) + continue; + const match = execStructSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "struct" }); + const properties = match.properties.split(";"); + const components = []; + const propertiesLength = properties.length; + for (let k2 = 0; k2 < propertiesLength; k2++) { + const property = properties[k2]; + const trimmed = property.trim(); + if (!trimmed) + continue; + const abiParameter = parseAbiParameter(trimmed, { + type: "struct" + }); + components.push(abiParameter); + } + if (!components.length) + throw new InvalidStructSignatureError({ signature }); + shallowStructs[match.name] = components; + } + const resolvedStructs = {}; + const entries = Object.entries(shallowStructs); + const entriesLength = entries.length; + for (let i = 0; i < entriesLength; i++) { + const [name, parameters] = entries[i]; + resolvedStructs[name] = resolveStructs(parameters, shallowStructs); + } + return resolvedStructs; +} +function resolveStructs(abiParameters, structs, ancestors = /* @__PURE__ */ new Set()) { + const components = []; + const length = abiParameters.length; + for (let i = 0; i < length; i++) { + const abiParameter = abiParameters[i]; + const isTuple = isTupleRegex.test(abiParameter.type); + if (isTuple) + components.push(abiParameter); + else { + const match = execTyped(typeWithoutTupleRegex, abiParameter.type); + if (!match?.type) + throw new InvalidAbiTypeParameterError({ abiParameter }); + const { array, type } = match; + if (type in structs) { + if (ancestors.has(type)) + throw new CircularReferenceError({ type }); + components.push({ + ...abiParameter, + type: `tuple${array ?? ""}`, + components: resolveStructs(structs[type] ?? [], structs, /* @__PURE__ */ new Set([...ancestors, type])) + }); + } else { + if (isSolidityType(type)) + components.push(abiParameter); + else + throw new UnknownTypeError({ type }); + } + } + } + return components; +} +var typeWithoutTupleRegex; +var init_structs = __esm({ + "node_modules/abitype/dist/esm/human-readable/runtime/structs.js"() { + init_regex(); + init_abiItem(); + init_abiParameter(); + init_signature(); + init_struct(); + init_signatures(); + init_utils(); + typeWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/; + } +}); + +// node_modules/abitype/dist/esm/human-readable/parseAbi.js +function parseAbi(signatures) { + const structs = parseStructs(signatures); + const abi4 = []; + const length = signatures.length; + for (let i = 0; i < length; i++) { + const signature = signatures[i]; + if (isStructSignature(signature)) + continue; + abi4.push(parseSignature(signature, structs)); + } + return abi4; +} +var init_parseAbi = __esm({ + "node_modules/abitype/dist/esm/human-readable/parseAbi.js"() { + init_signatures(); + init_structs(); + init_utils(); + } +}); + +// node_modules/abitype/dist/esm/human-readable/parseAbiItem.js +function parseAbiItem(signature) { + let abiItem; + if (typeof signature === "string") + abiItem = parseSignature(signature); + else { + const structs = parseStructs(signature); + const length = signature.length; + for (let i = 0; i < length; i++) { + const signature_ = signature[i]; + if (isStructSignature(signature_)) + continue; + abiItem = parseSignature(signature_, structs); + break; + } + } + if (!abiItem) + throw new InvalidAbiItemError({ signature }); + return abiItem; +} +var init_parseAbiItem = __esm({ + "node_modules/abitype/dist/esm/human-readable/parseAbiItem.js"() { + init_abiItem(); + init_signatures(); + init_structs(); + init_utils(); + } +}); + +// node_modules/abitype/dist/esm/human-readable/parseAbiParameters.js +function parseAbiParameters(params) { + const abiParameters = []; + if (typeof params === "string") { + const parameters = splitParameters(params); + const length = parameters.length; + for (let i = 0; i < length; i++) { + abiParameters.push(parseAbiParameter(parameters[i], { modifiers })); + } + } else { + const structs = parseStructs(params); + const length = params.length; + for (let i = 0; i < length; i++) { + const signature = params[i]; + if (isStructSignature(signature)) + continue; + const parameters = splitParameters(signature); + const length2 = parameters.length; + for (let k2 = 0; k2 < length2; k2++) { + abiParameters.push(parseAbiParameter(parameters[k2], { modifiers, structs })); + } + } + } + if (abiParameters.length === 0) + throw new InvalidAbiParametersError({ params }); + return abiParameters; +} +var init_parseAbiParameters = __esm({ + "node_modules/abitype/dist/esm/human-readable/parseAbiParameters.js"() { + init_abiParameter(); + init_signatures(); + init_structs(); + init_utils(); + init_utils(); + } +}); + +// node_modules/abitype/dist/esm/exports/index.js +var init_exports = __esm({ + "node_modules/abitype/dist/esm/exports/index.js"() { + init_formatAbiItem(); + init_parseAbi(); + init_parseAbiItem(); + init_parseAbiParameters(); + } +}); + +// node_modules/viem/_esm/utils/abi/formatAbiItem.js +function formatAbiItem2(abiItem, { includeName = false } = {}) { + if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error") + throw new InvalidDefinitionTypeError(abiItem.type); + return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`; +} +function formatAbiParams(params, { includeName = false } = {}) { + if (!params) + return ""; + return params.map((param) => formatAbiParam(param, { includeName })).join(includeName ? ", " : ","); +} +function formatAbiParam(param, { includeName }) { + if (param.type.startsWith("tuple")) { + return `(${formatAbiParams(param.components, { includeName })})${param.type.slice("tuple".length)}`; + } + return param.type + (includeName && param.name ? ` ${param.name}` : ""); +} +var init_formatAbiItem2 = __esm({ + "node_modules/viem/_esm/utils/abi/formatAbiItem.js"() { + init_abi(); + } +}); + +// node_modules/viem/_esm/utils/data/isHex.js +function isHex(value, { strict = true } = {}) { + if (!value) + return false; + if (typeof value !== "string") + return false; + return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x"); +} +var init_isHex = __esm({ + "node_modules/viem/_esm/utils/data/isHex.js"() { + } +}); + +// node_modules/viem/_esm/utils/data/size.js +function size(value) { + if (isHex(value, { strict: false })) + return Math.ceil((value.length - 2) / 2); + return value.length; +} +var init_size = __esm({ + "node_modules/viem/_esm/utils/data/size.js"() { + init_isHex(); + } +}); + +// node_modules/viem/_esm/errors/version.js +var version2; +var init_version2 = __esm({ + "node_modules/viem/_esm/errors/version.js"() { + version2 = "2.24.1"; + } +}); + +// node_modules/viem/_esm/errors/base.js +function walk(err, fn2) { + if (fn2?.(err)) + return err; + if (err && typeof err === "object" && "cause" in err && err.cause !== void 0) + return walk(err.cause, fn2); + return fn2 ? null : err; +} +var errorConfig, BaseError2; +var init_base = __esm({ + "node_modules/viem/_esm/errors/base.js"() { + init_version2(); + errorConfig = { + getDocsUrl: ({ docsBaseUrl, docsPath: docsPath6 = "", docsSlug }) => docsPath6 ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath6}${docsSlug ? `#${docsSlug}` : ""}` : void 0, + version: `viem@${version2}` + }; + BaseError2 = class _BaseError extends Error { + constructor(shortMessage, args = {}) { + const details = (() => { + if (args.cause instanceof _BaseError) + return args.cause.details; + if (args.cause?.message) + return args.cause.message; + return args.details; + })(); + const docsPath6 = (() => { + if (args.cause instanceof _BaseError) + return args.cause.docsPath || args.docsPath; + return args.docsPath; + })(); + const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath: docsPath6 }); + const message = [ + shortMessage || "An error occurred.", + "", + ...args.metaMessages ? [...args.metaMessages, ""] : [], + ...docsUrl ? [`Docs: ${docsUrl}`] : [], + ...details ? [`Details: ${details}`] : [], + ...errorConfig.version ? [`Version: ${errorConfig.version}`] : [] + ].join("\n"); + super(message, args.cause ? { cause: args.cause } : void 0); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "docsPath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metaMessages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "shortMessage", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "version", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "BaseError" + }); + this.details = details; + this.docsPath = docsPath6; + this.metaMessages = args.metaMessages; + this.name = args.name ?? this.name; + this.shortMessage = shortMessage; + this.version = version2; + } + walk(fn2) { + return walk(this, fn2); + } + }; + } +}); + +// node_modules/viem/_esm/errors/abi.js +var AbiConstructorNotFoundError, AbiConstructorParamsNotFoundError, AbiDecodingDataSizeTooSmallError, AbiDecodingZeroDataError, AbiEncodingArrayLengthMismatchError, AbiEncodingBytesSizeMismatchError, AbiEncodingLengthMismatchError, AbiErrorSignatureNotFoundError, AbiEventSignatureEmptyTopicsError, AbiEventSignatureNotFoundError, AbiEventNotFoundError, AbiFunctionNotFoundError, AbiFunctionOutputsNotFoundError, AbiItemAmbiguityError, BytesSizeMismatchError, DecodeLogDataMismatch, DecodeLogTopicsMismatch, InvalidAbiEncodingTypeError, InvalidAbiDecodingTypeError, InvalidArrayError, InvalidDefinitionTypeError; +var init_abi = __esm({ + "node_modules/viem/_esm/errors/abi.js"() { + init_formatAbiItem2(); + init_size(); + init_base(); + AbiConstructorNotFoundError = class extends BaseError2 { + constructor({ docsPath: docsPath6 }) { + super([ + "A constructor was not found on the ABI.", + "Make sure you are using the correct ABI and that the constructor exists on it." + ].join("\n"), { + docsPath: docsPath6, + name: "AbiConstructorNotFoundError" + }); + } + }; + AbiConstructorParamsNotFoundError = class extends BaseError2 { + constructor({ docsPath: docsPath6 }) { + super([ + "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.", + "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists." + ].join("\n"), { + docsPath: docsPath6, + name: "AbiConstructorParamsNotFoundError" + }); + } + }; + AbiDecodingDataSizeTooSmallError = class extends BaseError2 { + constructor({ data, params, size: size5 }) { + super([`Data size of ${size5} bytes is too small for given parameters.`].join("\n"), { + metaMessages: [ + `Params: (${formatAbiParams(params, { includeName: true })})`, + `Data: ${data} (${size5} bytes)` + ], + name: "AbiDecodingDataSizeTooSmallError" + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "params", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "size", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = data; + this.params = params; + this.size = size5; + } + }; + AbiDecodingZeroDataError = class extends BaseError2 { + constructor() { + super('Cannot decode zero data ("0x") with ABI parameters.', { + name: "AbiDecodingZeroDataError" + }); + } + }; + AbiEncodingArrayLengthMismatchError = class extends BaseError2 { + constructor({ expectedLength, givenLength, type }) { + super([ + `ABI encoding array length mismatch for type ${type}.`, + `Expected length: ${expectedLength}`, + `Given length: ${givenLength}` + ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" }); + } + }; + AbiEncodingBytesSizeMismatchError = class extends BaseError2 { + constructor({ expectedSize, value }) { + super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); + } + }; + AbiEncodingLengthMismatchError = class extends BaseError2 { + constructor({ expectedLength, givenLength }) { + super([ + "ABI encoding params/values length mismatch.", + `Expected length (params): ${expectedLength}`, + `Given length (values): ${givenLength}` + ].join("\n"), { name: "AbiEncodingLengthMismatchError" }); + } + }; + AbiErrorSignatureNotFoundError = class extends BaseError2 { + constructor(signature, { docsPath: docsPath6 }) { + super([ + `Encoded error signature "${signature}" not found on ABI.`, + "Make sure you are using the correct ABI and that the error exists on it.", + `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.` + ].join("\n"), { + docsPath: docsPath6, + name: "AbiErrorSignatureNotFoundError" + }); + Object.defineProperty(this, "signature", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.signature = signature; + } + }; + AbiEventSignatureEmptyTopicsError = class extends BaseError2 { + constructor({ docsPath: docsPath6 }) { + super("Cannot extract event signature from empty topics.", { + docsPath: docsPath6, + name: "AbiEventSignatureEmptyTopicsError" + }); + } + }; + AbiEventSignatureNotFoundError = class extends BaseError2 { + constructor(signature, { docsPath: docsPath6 }) { + super([ + `Encoded event signature "${signature}" not found on ABI.`, + "Make sure you are using the correct ABI and that the event exists on it.", + `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.` + ].join("\n"), { + docsPath: docsPath6, + name: "AbiEventSignatureNotFoundError" + }); + } + }; + AbiEventNotFoundError = class extends BaseError2 { + constructor(eventName, { docsPath: docsPath6 } = {}) { + super([ + `Event ${eventName ? `"${eventName}" ` : ""}not found on ABI.`, + "Make sure you are using the correct ABI and that the event exists on it." + ].join("\n"), { + docsPath: docsPath6, + name: "AbiEventNotFoundError" + }); + } + }; + AbiFunctionNotFoundError = class extends BaseError2 { + constructor(functionName, { docsPath: docsPath6 } = {}) { + super([ + `Function ${functionName ? `"${functionName}" ` : ""}not found on ABI.`, + "Make sure you are using the correct ABI and that the function exists on it." + ].join("\n"), { + docsPath: docsPath6, + name: "AbiFunctionNotFoundError" + }); + } + }; + AbiFunctionOutputsNotFoundError = class extends BaseError2 { + constructor(functionName, { docsPath: docsPath6 }) { + super([ + `Function "${functionName}" does not contain any \`outputs\` on ABI.`, + "Cannot decode function result without knowing what the parameter types are.", + "Make sure you are using the correct ABI and that the function exists on it." + ].join("\n"), { + docsPath: docsPath6, + name: "AbiFunctionOutputsNotFoundError" + }); + } + }; + AbiItemAmbiguityError = class extends BaseError2 { + constructor(x2, y2) { + super("Found ambiguous types in overloaded ABI items.", { + metaMessages: [ + `\`${x2.type}\` in \`${formatAbiItem2(x2.abiItem)}\`, and`, + `\`${y2.type}\` in \`${formatAbiItem2(y2.abiItem)}\``, + "", + "These types encode differently and cannot be distinguished at runtime.", + "Remove one of the ambiguous items in the ABI." + ], + name: "AbiItemAmbiguityError" + }); + } + }; + BytesSizeMismatchError = class extends BaseError2 { + constructor({ expectedSize, givenSize }) { + super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, { + name: "BytesSizeMismatchError" + }); + } + }; + DecodeLogDataMismatch = class extends BaseError2 { + constructor({ abiItem, data, params, size: size5 }) { + super([ + `Data size of ${size5} bytes is too small for non-indexed event parameters.` + ].join("\n"), { + metaMessages: [ + `Params: (${formatAbiParams(params, { includeName: true })})`, + `Data: ${data} (${size5} bytes)` + ], + name: "DecodeLogDataMismatch" + }); + Object.defineProperty(this, "abiItem", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "params", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "size", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.abiItem = abiItem; + this.data = data; + this.params = params; + this.size = size5; + } + }; + DecodeLogTopicsMismatch = class extends BaseError2 { + constructor({ abiItem, param }) { + super([ + `Expected a topic for indexed event parameter${param.name ? ` "${param.name}"` : ""} on event "${formatAbiItem2(abiItem, { includeName: true })}".` + ].join("\n"), { name: "DecodeLogTopicsMismatch" }); + Object.defineProperty(this, "abiItem", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.abiItem = abiItem; + } + }; + InvalidAbiEncodingTypeError = class extends BaseError2 { + constructor(type, { docsPath: docsPath6 }) { + super([ + `Type "${type}" is not a valid encoding type.`, + "Please provide a valid ABI type." + ].join("\n"), { docsPath: docsPath6, name: "InvalidAbiEncodingType" }); + } + }; + InvalidAbiDecodingTypeError = class extends BaseError2 { + constructor(type, { docsPath: docsPath6 }) { + super([ + `Type "${type}" is not a valid decoding type.`, + "Please provide a valid ABI type." + ].join("\n"), { docsPath: docsPath6, name: "InvalidAbiDecodingType" }); + } + }; + InvalidArrayError = class extends BaseError2 { + constructor(value) { + super([`Value "${value}" is not a valid array.`].join("\n"), { + name: "InvalidArrayError" + }); + } + }; + InvalidDefinitionTypeError = class extends BaseError2 { + constructor(type) { + super([ + `"${type}" is not a valid definition type.`, + 'Valid types: "function", "event", "error"' + ].join("\n"), { name: "InvalidDefinitionTypeError" }); + } + }; + } +}); + +// node_modules/viem/_esm/errors/data.js +var SliceOffsetOutOfBoundsError, SizeExceedsPaddingSizeError, InvalidBytesLengthError; +var init_data = __esm({ + "node_modules/viem/_esm/errors/data.js"() { + init_base(); + SliceOffsetOutOfBoundsError = class extends BaseError2 { + constructor({ offset, position, size: size5 }) { + super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size5}).`, { name: "SliceOffsetOutOfBoundsError" }); + } + }; + SizeExceedsPaddingSizeError = class extends BaseError2 { + constructor({ size: size5, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size5}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); + } + }; + InvalidBytesLengthError = class extends BaseError2 { + constructor({ size: size5, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size5} ${type} long.`, { name: "InvalidBytesLengthError" }); + } + }; + } +}); + +// node_modules/viem/_esm/utils/data/pad.js +function pad(hexOrBytes, { dir, size: size5 = 32 } = {}) { + if (typeof hexOrBytes === "string") + return padHex(hexOrBytes, { dir, size: size5 }); + return padBytes(hexOrBytes, { dir, size: size5 }); +} +function padHex(hex_, { dir, size: size5 = 32 } = {}) { + if (size5 === null) + return hex_; + const hex = hex_.replace("0x", ""); + if (hex.length > size5 * 2) + throw new SizeExceedsPaddingSizeError({ + size: Math.ceil(hex.length / 2), + targetSize: size5, + type: "hex" + }); + return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`; +} +function padBytes(bytes, { dir, size: size5 = 32 } = {}) { + if (size5 === null) + return bytes; + if (bytes.length > size5) + throw new SizeExceedsPaddingSizeError({ + size: bytes.length, + targetSize: size5, + type: "bytes" + }); + const paddedBytes = new Uint8Array(size5); + for (let i = 0; i < size5; i++) { + const padEnd = dir === "right"; + paddedBytes[padEnd ? i : size5 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; + } + return paddedBytes; +} +var init_pad = __esm({ + "node_modules/viem/_esm/utils/data/pad.js"() { + init_data(); + } +}); + +// node_modules/viem/_esm/errors/encoding.js +var IntegerOutOfRangeError, InvalidBytesBooleanError, InvalidHexBooleanError, SizeOverflowError; +var init_encoding = __esm({ + "node_modules/viem/_esm/errors/encoding.js"() { + init_base(); + IntegerOutOfRangeError = class extends BaseError2 { + constructor({ max, min, signed, size: size5, value }) { + super(`Number "${value}" is not in safe ${size5 ? `${size5 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" }); + } + }; + InvalidBytesBooleanError = class extends BaseError2 { + constructor(bytes) { + super(`Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, { + name: "InvalidBytesBooleanError" + }); + } + }; + InvalidHexBooleanError = class extends BaseError2 { + constructor(hex) { + super(`Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`, { name: "InvalidHexBooleanError" }); + } + }; + SizeOverflowError = class extends BaseError2 { + constructor({ givenSize, maxSize }) { + super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" }); + } + }; + } +}); + +// node_modules/viem/_esm/utils/data/trim.js +function trim2(hexOrBytes, { dir = "left" } = {}) { + let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes; + let sliceLength = 0; + for (let i = 0; i < data.length - 1; i++) { + if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") + sliceLength++; + else + break; + } + data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); + if (typeof hexOrBytes === "string") { + if (data.length === 1 && dir === "right") + data = `${data}0`; + return `0x${data.length % 2 === 1 ? `0${data}` : data}`; + } + return data; +} +var init_trim = __esm({ + "node_modules/viem/_esm/utils/data/trim.js"() { + } +}); + +// node_modules/viem/_esm/utils/encoding/fromHex.js +function assertSize(hexOrBytes, { size: size5 }) { + if (size(hexOrBytes) > size5) + throw new SizeOverflowError({ + givenSize: size(hexOrBytes), + maxSize: size5 + }); +} +function hexToBigInt(hex, opts = {}) { + const { signed } = opts; + if (opts.size) + assertSize(hex, { size: opts.size }); + const value = BigInt(hex); + if (!signed) + return value; + const size5 = (hex.length - 2) / 2; + const max = (1n << BigInt(size5) * 8n - 1n) - 1n; + if (value <= max) + return value; + return value - BigInt(`0x${"f".padStart(size5 * 2, "f")}`) - 1n; +} +function hexToBool(hex_, opts = {}) { + let hex = hex_; + if (opts.size) { + assertSize(hex, { size: opts.size }); + hex = trim2(hex); + } + if (trim2(hex) === "0x00") + return false; + if (trim2(hex) === "0x01") + return true; + throw new InvalidHexBooleanError(hex); +} +function hexToNumber(hex, opts = {}) { + return Number(hexToBigInt(hex, opts)); +} +var init_fromHex = __esm({ + "node_modules/viem/_esm/utils/encoding/fromHex.js"() { + init_encoding(); + init_size(); + init_trim(); + } +}); + +// node_modules/viem/_esm/utils/encoding/toHex.js +function toHex(value, opts = {}) { + if (typeof value === "number" || typeof value === "bigint") + return numberToHex(value, opts); + if (typeof value === "string") { + return stringToHex(value, opts); + } + if (typeof value === "boolean") + return boolToHex(value, opts); + return bytesToHex(value, opts); +} +function boolToHex(value, opts = {}) { + const hex = `0x${Number(value)}`; + if (typeof opts.size === "number") { + assertSize(hex, { size: opts.size }); + return pad(hex, { size: opts.size }); + } + return hex; +} +function bytesToHex(value, opts = {}) { + let string = ""; + for (let i = 0; i < value.length; i++) { + string += hexes[value[i]]; + } + const hex = `0x${string}`; + if (typeof opts.size === "number") { + assertSize(hex, { size: opts.size }); + return pad(hex, { dir: "right", size: opts.size }); + } + return hex; +} +function numberToHex(value_, opts = {}) { + const { signed, size: size5 } = opts; + const value = BigInt(value_); + let maxValue; + if (size5) { + if (signed) + maxValue = (1n << BigInt(size5) * 8n - 1n) - 1n; + else + maxValue = 2n ** (BigInt(size5) * 8n) - 1n; + } else if (typeof value_ === "number") { + maxValue = BigInt(Number.MAX_SAFE_INTEGER); + } + const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0; + if (maxValue && value > maxValue || value < minValue) { + const suffix = typeof value_ === "bigint" ? "n" : ""; + throw new IntegerOutOfRangeError({ + max: maxValue ? `${maxValue}${suffix}` : void 0, + min: `${minValue}${suffix}`, + signed, + size: size5, + value: `${value_}${suffix}` + }); + } + const hex = `0x${(signed && value < 0 ? (1n << BigInt(size5 * 8)) + BigInt(value) : value).toString(16)}`; + if (size5) + return pad(hex, { size: size5 }); + return hex; +} +function stringToHex(value_, opts = {}) { + const value = encoder.encode(value_); + return bytesToHex(value, opts); +} +var hexes, encoder; +var init_toHex = __esm({ + "node_modules/viem/_esm/utils/encoding/toHex.js"() { + init_encoding(); + init_pad(); + init_fromHex(); + hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); + encoder = /* @__PURE__ */ new TextEncoder(); + } +}); + +// node_modules/viem/_esm/utils/encoding/toBytes.js +function toBytes(value, opts = {}) { + if (typeof value === "number" || typeof value === "bigint") + return numberToBytes(value, opts); + if (typeof value === "boolean") + return boolToBytes(value, opts); + if (isHex(value)) + return hexToBytes(value, opts); + return stringToBytes(value, opts); +} +function boolToBytes(value, opts = {}) { + const bytes = new Uint8Array(1); + bytes[0] = Number(value); + if (typeof opts.size === "number") { + assertSize(bytes, { size: opts.size }); + return pad(bytes, { size: opts.size }); + } + return bytes; +} +function charCodeToBase16(char) { + if (char >= charCodeMap.zero && char <= charCodeMap.nine) + return char - charCodeMap.zero; + if (char >= charCodeMap.A && char <= charCodeMap.F) + return char - (charCodeMap.A - 10); + if (char >= charCodeMap.a && char <= charCodeMap.f) + return char - (charCodeMap.a - 10); + return void 0; +} +function hexToBytes(hex_, opts = {}) { + let hex = hex_; + if (opts.size) { + assertSize(hex, { size: opts.size }); + hex = pad(hex, { dir: "right", size: opts.size }); + } + let hexString = hex.slice(2); + if (hexString.length % 2) + hexString = `0${hexString}`; + const length = hexString.length / 2; + const bytes = new Uint8Array(length); + for (let index2 = 0, j2 = 0; index2 < length; index2++) { + const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j2++)); + const nibbleRight = charCodeToBase16(hexString.charCodeAt(j2++)); + if (nibbleLeft === void 0 || nibbleRight === void 0) { + throw new BaseError2(`Invalid byte sequence ("${hexString[j2 - 2]}${hexString[j2 - 1]}" in "${hexString}").`); + } + bytes[index2] = nibbleLeft * 16 + nibbleRight; + } + return bytes; +} +function numberToBytes(value, opts) { + const hex = numberToHex(value, opts); + return hexToBytes(hex); +} +function stringToBytes(value, opts = {}) { + const bytes = encoder2.encode(value); + if (typeof opts.size === "number") { + assertSize(bytes, { size: opts.size }); + return pad(bytes, { dir: "right", size: opts.size }); + } + return bytes; +} +var encoder2, charCodeMap; +var init_toBytes = __esm({ + "node_modules/viem/_esm/utils/encoding/toBytes.js"() { + init_base(); + init_isHex(); + init_pad(); + init_fromHex(); + init_toHex(); + encoder2 = /* @__PURE__ */ new TextEncoder(); + charCodeMap = { + zero: 48, + nine: 57, + A: 65, + F: 70, + a: 97, + f: 102 + }; + } +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/_assert.js +function anumber(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error("positive integer expected, got " + n); +} +function isBytes(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; +} +function abytes(b2, ...lengths) { + if (!isBytes(b2)) + throw new Error("Uint8Array expected"); + if (lengths.length > 0 && !lengths.includes(b2.length)) + throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b2.length); +} +function ahash(h) { + if (typeof h !== "function" || typeof h.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + anumber(h.outputLen); + anumber(h.blockLen); +} +function aexists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function aoutput(out, instance) { + abytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error("digestInto() expects output buffer of length at least " + min); + } +} +var init_assert = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/_assert.js"() { + } +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/_u64.js +function fromBig(n, le2 = false) { + if (le2) + return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; + return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le2 = false) { + let Ah = new Uint32Array(lst.length); + let Al2 = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le2); + [Ah[i], Al2[i]] = [h, l]; + } + return [Ah, Al2]; +} +var U32_MASK64, _32n, rotlSH, rotlSL, rotlBH, rotlBL; +var init_u64 = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/_u64.js"() { + U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); + _32n = /* @__PURE__ */ BigInt(32); + rotlSH = (h, l, s) => h << s | l >>> 32 - s; + rotlSL = (h, l, s) => l << s | h >>> 32 - s; + rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; + rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; + } +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/cryptoNode.js +import * as nc from "node:crypto"; +var crypto3; +var init_cryptoNode = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/cryptoNode.js"() { + crypto3 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0; + } +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/utils.js +function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +function rotr(word, shift) { + return word << 32 - shift | word >>> shift; +} +function byteSwap(word) { + return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; +} +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } +} +function utf8ToBytes(str) { + if (typeof str !== "string") + throw new Error("utf8ToBytes expected string, got " + typeof str); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes2(data) { + if (typeof data === "string") + data = utf8ToBytes(data); + abytes(data); + return data; +} +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad4 = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad4); + pad4 += a.length; + } + return res; +} +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +function randomBytes(bytesLength = 32) { + if (crypto3 && typeof crypto3.getRandomValues === "function") { + return crypto3.getRandomValues(new Uint8Array(bytesLength)); + } + if (crypto3 && typeof crypto3.randomBytes === "function") { + return crypto3.randomBytes(bytesLength); + } + throw new Error("crypto.getRandomValues must be defined"); +} +var isLE, Hash; +var init_utils2 = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/utils.js"() { + init_cryptoNode(); + init_assert(); + isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); + Hash = class { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } + }; + } +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/sha3.js +function keccakP(s, rounds = 24) { + const B2 = new Uint32Array(5 * 2); + for (let round = 24 - rounds; round < 24; round++) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s[x2] ^ s[x2 + 10] ^ s[x2 + 20] ^ s[x2 + 30] ^ s[x2 + 40]; + for (let x2 = 0; x2 < 10; x2 += 2) { + const idx1 = (x2 + 8) % 10; + const idx0 = (x2 + 2) % 10; + const B0 = B2[idx0]; + const B1 = B2[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B2[idx1]; + const Tl2 = rotlL(B0, B1, 1) ^ B2[idx1 + 1]; + for (let y2 = 0; y2 < 50; y2 += 10) { + s[x2 + y2] ^= Th; + s[x2 + y2 + 1] ^= Tl2; + } + } + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl2 = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl2; + } + for (let y2 = 0; y2 < 50; y2 += 10) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s[y2 + x2]; + for (let x2 = 0; x2 < 10; x2++) + s[y2 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10]; + } + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B2.fill(0); +} +var SHA3_PI, SHA3_ROTL, _SHA3_IOTA, _0n, _1n, _2n, _7n, _256n, _0x71n, SHA3_IOTA_H, SHA3_IOTA_L, rotlH, rotlL, Keccak, gen, sha3_224, sha3_256, sha3_384, sha3_512, keccak_224, keccak_256, keccak_384, keccak_512, genShake, shake128, shake256; +var init_sha3 = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/sha3.js"() { + init_assert(); + init_u64(); + init_utils2(); + SHA3_PI = []; + SHA3_ROTL = []; + _SHA3_IOTA = []; + _0n = /* @__PURE__ */ BigInt(0); + _1n = /* @__PURE__ */ BigInt(1); + _2n = /* @__PURE__ */ BigInt(2); + _7n = /* @__PURE__ */ BigInt(7); + _256n = /* @__PURE__ */ BigInt(256); + _0x71n = /* @__PURE__ */ BigInt(113); + for (let round = 0, R2 = _1n, x2 = 1, y2 = 0; round < 24; round++) { + [x2, y2] = [y2, (2 * x2 + 3 * y2) % 5]; + SHA3_PI.push(2 * (5 * y2 + x2)); + SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); + let t = _0n; + for (let j2 = 0; j2 < 7; j2++) { + R2 = (R2 << _1n ^ (R2 >> _7n) * _0x71n) % _256n; + if (R2 & _2n) + t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j2)) - _1n; + } + _SHA3_IOTA.push(t); + } + [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); + rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); + rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); + Keccak = class _Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + anumber(outputLen); + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error("Sha3 supports only keccak-f1600 function"); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + if (!isLE) + byteSwap32(this.state32); + keccakP(this.state32, this.rounds); + if (!isLE) + byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + aexists(this); + const { blockLen, state } = this; + data = toBytes2(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + state[pos] ^= suffix; + if ((suffix & 128) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 128; + this.keccak(); + } + writeInto(out) { + aexists(this, false); + abytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); + } + xof(bytes) { + anumber(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + aoutput(out, this); + if (this.finished) + throw new Error("digest() was already called"); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to2) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to2 || (to2 = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to2.state32.set(this.state32); + to2.pos = this.pos; + to2.posOut = this.posOut; + to2.finished = this.finished; + to2.rounds = rounds; + to2.suffix = suffix; + to2.outputLen = outputLen; + to2.enableXOF = enableXOF; + to2.destroyed = this.destroyed; + return to2; + } + }; + gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + sha3_224 = /* @__PURE__ */ gen(6, 144, 224 / 8); + sha3_256 = /* @__PURE__ */ gen(6, 136, 256 / 8); + sha3_384 = /* @__PURE__ */ gen(6, 104, 384 / 8); + sha3_512 = /* @__PURE__ */ gen(6, 72, 512 / 8); + keccak_224 = /* @__PURE__ */ gen(1, 144, 224 / 8); + keccak_256 = /* @__PURE__ */ gen(1, 136, 256 / 8); + keccak_384 = /* @__PURE__ */ gen(1, 104, 384 / 8); + keccak_512 = /* @__PURE__ */ gen(1, 72, 512 / 8); + genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true)); + shake128 = /* @__PURE__ */ genShake(31, 168, 128 / 8); + shake256 = /* @__PURE__ */ genShake(31, 136, 256 / 8); + } +}); + +// node_modules/viem/_esm/utils/hash/keccak256.js +function keccak256(value, to_) { + const to2 = to_ || "hex"; + const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value); + if (to2 === "bytes") + return bytes; + return toHex(bytes); +} +var init_keccak256 = __esm({ + "node_modules/viem/_esm/utils/hash/keccak256.js"() { + init_sha3(); + init_isHex(); + init_toBytes(); + init_toHex(); + } +}); + +// node_modules/viem/_esm/utils/hash/hashSignature.js +function hashSignature(sig) { + return hash(sig); +} +var hash; +var init_hashSignature = __esm({ + "node_modules/viem/_esm/utils/hash/hashSignature.js"() { + init_toBytes(); + init_keccak256(); + hash = (value) => keccak256(toBytes(value)); + } +}); + +// node_modules/viem/_esm/utils/hash/normalizeSignature.js +function normalizeSignature(signature) { + let active = true; + let current = ""; + let level = 0; + let result = ""; + let valid = false; + for (let i = 0; i < signature.length; i++) { + const char = signature[i]; + if (["(", ")", ","].includes(char)) + active = true; + if (char === "(") + level++; + if (char === ")") + level--; + if (!active) + continue; + if (level === 0) { + if (char === " " && ["event", "function", ""].includes(result)) + result = ""; + else { + result += char; + if (char === ")") { + valid = true; + break; + } + } + continue; + } + if (char === " ") { + if (signature[i - 1] !== "," && current !== "," && current !== ",(") { + current = ""; + active = false; + } + continue; + } + result += char; + current += char; + } + if (!valid) + throw new BaseError2("Unable to normalize signature."); + return result; +} +var init_normalizeSignature = __esm({ + "node_modules/viem/_esm/utils/hash/normalizeSignature.js"() { + init_base(); + } +}); + +// node_modules/viem/_esm/utils/hash/toSignature.js +var toSignature; +var init_toSignature = __esm({ + "node_modules/viem/_esm/utils/hash/toSignature.js"() { + init_exports(); + init_normalizeSignature(); + toSignature = (def) => { + const def_ = (() => { + if (typeof def === "string") + return def; + return formatAbiItem(def); + })(); + return normalizeSignature(def_); + }; + } +}); + +// node_modules/viem/_esm/utils/hash/toSignatureHash.js +function toSignatureHash(fn2) { + return hashSignature(toSignature(fn2)); +} +var init_toSignatureHash = __esm({ + "node_modules/viem/_esm/utils/hash/toSignatureHash.js"() { + init_hashSignature(); + init_toSignature(); + } +}); + +// node_modules/viem/_esm/utils/hash/toEventSelector.js +var toEventSelector; +var init_toEventSelector = __esm({ + "node_modules/viem/_esm/utils/hash/toEventSelector.js"() { + init_toSignatureHash(); + toEventSelector = toSignatureHash; + } +}); + +// node_modules/viem/_esm/errors/address.js +var InvalidAddressError; +var init_address = __esm({ + "node_modules/viem/_esm/errors/address.js"() { + init_base(); + InvalidAddressError = class extends BaseError2 { + constructor({ address }) { + super(`Address "${address}" is invalid.`, { + metaMessages: [ + "- Address must be a hex value of 20 bytes (40 hex characters).", + "- Address must match its checksum counterpart." + ], + name: "InvalidAddressError" + }); + } + }; + } +}); + +// node_modules/viem/_esm/utils/lru.js +var LruMap; +var init_lru = __esm({ + "node_modules/viem/_esm/utils/lru.js"() { + LruMap = class extends Map { + constructor(size5) { + super(); + Object.defineProperty(this, "maxSize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxSize = size5; + } + get(key) { + const value = super.get(key); + if (super.has(key) && value !== void 0) { + this.delete(key); + super.set(key, value); + } + return value; + } + set(key, value) { + super.set(key, value); + if (this.maxSize && this.size > this.maxSize) { + const firstKey = this.keys().next().value; + if (firstKey) + this.delete(firstKey); + } + return this; + } + }; + } +}); + +// node_modules/viem/_esm/utils/address/getAddress.js +function checksumAddress(address_, chainId) { + if (checksumAddressCache.has(`${address_}.${chainId}`)) + return checksumAddressCache.get(`${address_}.${chainId}`); + const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase(); + const hash2 = keccak256(stringToBytes(hexAddress), "bytes"); + const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split(""); + for (let i = 0; i < 40; i += 2) { + if (hash2[i >> 1] >> 4 >= 8 && address[i]) { + address[i] = address[i].toUpperCase(); + } + if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) { + address[i + 1] = address[i + 1].toUpperCase(); + } + } + const result = `0x${address.join("")}`; + checksumAddressCache.set(`${address_}.${chainId}`, result); + return result; +} +function getAddress(address, chainId) { + if (!isAddress(address, { strict: false })) + throw new InvalidAddressError({ address }); + return checksumAddress(address, chainId); +} +var checksumAddressCache; +var init_getAddress = __esm({ + "node_modules/viem/_esm/utils/address/getAddress.js"() { + init_address(); + init_toBytes(); + init_keccak256(); + init_lru(); + init_isAddress(); + checksumAddressCache = /* @__PURE__ */ new LruMap(8192); + } +}); + +// node_modules/viem/_esm/utils/address/isAddress.js +function isAddress(address, options) { + const { strict = true } = options ?? {}; + const cacheKey2 = `${address}.${strict}`; + if (isAddressCache.has(cacheKey2)) + return isAddressCache.get(cacheKey2); + const result = (() => { + if (!addressRegex.test(address)) + return false; + if (address.toLowerCase() === address) + return true; + if (strict) + return checksumAddress(address) === address; + return true; + })(); + isAddressCache.set(cacheKey2, result); + return result; +} +var addressRegex, isAddressCache; +var init_isAddress = __esm({ + "node_modules/viem/_esm/utils/address/isAddress.js"() { + init_lru(); + init_getAddress(); + addressRegex = /^0x[a-fA-F0-9]{40}$/; + isAddressCache = /* @__PURE__ */ new LruMap(8192); + } +}); + +// node_modules/viem/_esm/utils/data/concat.js +function concat(values) { + if (typeof values[0] === "string") + return concatHex(values); + return concatBytes2(values); +} +function concatBytes2(values) { + let length = 0; + for (const arr of values) { + length += arr.length; + } + const result = new Uint8Array(length); + let offset = 0; + for (const arr of values) { + result.set(arr, offset); + offset += arr.length; + } + return result; +} +function concatHex(values) { + return `0x${values.reduce((acc, x2) => acc + x2.replace("0x", ""), "")}`; +} +var init_concat = __esm({ + "node_modules/viem/_esm/utils/data/concat.js"() { + } +}); + +// node_modules/viem/_esm/utils/data/slice.js +function slice(value, start, end, { strict } = {}) { + if (isHex(value, { strict: false })) + return sliceHex(value, start, end, { + strict + }); + return sliceBytes(value, start, end, { + strict + }); +} +function assertStartOffset(value, start) { + if (typeof start === "number" && start > 0 && start > size(value) - 1) + throw new SliceOffsetOutOfBoundsError({ + offset: start, + position: "start", + size: size(value) + }); +} +function assertEndOffset(value, start, end) { + if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) { + throw new SliceOffsetOutOfBoundsError({ + offset: end, + position: "end", + size: size(value) + }); + } +} +function sliceBytes(value_, start, end, { strict } = {}) { + assertStartOffset(value_, start); + const value = value_.slice(start, end); + if (strict) + assertEndOffset(value, start, end); + return value; +} +function sliceHex(value_, start, end, { strict } = {}) { + assertStartOffset(value_, start); + const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`; + if (strict) + assertEndOffset(value, start, end); + return value; +} +var init_slice = __esm({ + "node_modules/viem/_esm/utils/data/slice.js"() { + init_data(); + init_isHex(); + init_size(); + } +}); + +// node_modules/viem/_esm/utils/regex.js +var bytesRegex2, integerRegex2; +var init_regex2 = __esm({ + "node_modules/viem/_esm/utils/regex.js"() { + bytesRegex2 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; + integerRegex2 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; + } +}); + +// node_modules/viem/_esm/utils/abi/encodeAbiParameters.js +function encodeAbiParameters(params, values) { + if (params.length !== values.length) + throw new AbiEncodingLengthMismatchError({ + expectedLength: params.length, + givenLength: values.length + }); + const preparedParams = prepareParams({ + params, + values + }); + const data = encodeParams(preparedParams); + if (data.length === 0) + return "0x"; + return data; +} +function prepareParams({ params, values }) { + const preparedParams = []; + for (let i = 0; i < params.length; i++) { + preparedParams.push(prepareParam({ param: params[i], value: values[i] })); + } + return preparedParams; +} +function prepareParam({ param, value }) { + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return encodeArray(value, { length, param: { ...param, type } }); + } + if (param.type === "tuple") { + return encodeTuple(value, { + param + }); + } + if (param.type === "address") { + return encodeAddress(value); + } + if (param.type === "bool") { + return encodeBool(value); + } + if (param.type.startsWith("uint") || param.type.startsWith("int")) { + const signed = param.type.startsWith("int"); + const [, , size5 = "256"] = integerRegex2.exec(param.type) ?? []; + return encodeNumber(value, { + signed, + size: Number(size5) + }); + } + if (param.type.startsWith("bytes")) { + return encodeBytes(value, { param }); + } + if (param.type === "string") { + return encodeString(value); + } + throw new InvalidAbiEncodingTypeError(param.type, { + docsPath: "/docs/contract/encodeAbiParameters" + }); +} +function encodeParams(preparedParams) { + let staticSize = 0; + for (let i = 0; i < preparedParams.length; i++) { + const { dynamic, encoded } = preparedParams[i]; + if (dynamic) + staticSize += 32; + else + staticSize += size(encoded); + } + const staticParams = []; + const dynamicParams = []; + let dynamicSize = 0; + for (let i = 0; i < preparedParams.length; i++) { + const { dynamic, encoded } = preparedParams[i]; + if (dynamic) { + staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 })); + dynamicParams.push(encoded); + dynamicSize += size(encoded); + } else { + staticParams.push(encoded); + } + } + return concat([...staticParams, ...dynamicParams]); +} +function encodeAddress(value) { + if (!isAddress(value)) + throw new InvalidAddressError({ address: value }); + return { dynamic: false, encoded: padHex(value.toLowerCase()) }; +} +function encodeArray(value, { length, param }) { + const dynamic = length === null; + if (!Array.isArray(value)) + throw new InvalidArrayError(value); + if (!dynamic && value.length !== length) + throw new AbiEncodingArrayLengthMismatchError({ + expectedLength: length, + givenLength: value.length, + type: `${param.type}[${length}]` + }); + let dynamicChild = false; + const preparedParams = []; + for (let i = 0; i < value.length; i++) { + const preparedParam = prepareParam({ param, value: value[i] }); + if (preparedParam.dynamic) + dynamicChild = true; + preparedParams.push(preparedParam); + } + if (dynamic || dynamicChild) { + const data = encodeParams(preparedParams); + if (dynamic) { + const length2 = numberToHex(preparedParams.length, { size: 32 }); + return { + dynamic: true, + encoded: preparedParams.length > 0 ? concat([length2, data]) : length2 + }; + } + if (dynamicChild) + return { dynamic: true, encoded: data }; + } + return { + dynamic: false, + encoded: concat(preparedParams.map(({ encoded }) => encoded)) + }; +} +function encodeBytes(value, { param }) { + const [, paramSize] = param.type.split("bytes"); + const bytesSize = size(value); + if (!paramSize) { + let value_ = value; + if (bytesSize % 32 !== 0) + value_ = padHex(value_, { + dir: "right", + size: Math.ceil((value.length - 2) / 2 / 32) * 32 + }); + return { + dynamic: true, + encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]) + }; + } + if (bytesSize !== Number.parseInt(paramSize)) + throw new AbiEncodingBytesSizeMismatchError({ + expectedSize: Number.parseInt(paramSize), + value + }); + return { dynamic: false, encoded: padHex(value, { dir: "right" }) }; +} +function encodeBool(value) { + if (typeof value !== "boolean") + throw new BaseError2(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); + return { dynamic: false, encoded: padHex(boolToHex(value)) }; +} +function encodeNumber(value, { signed, size: size5 = 256 }) { + if (typeof size5 === "number") { + const max = 2n ** (BigInt(size5) - (signed ? 1n : 0n)) - 1n; + const min = signed ? -max - 1n : 0n; + if (value > max || value < min) + throw new IntegerOutOfRangeError({ + max: max.toString(), + min: min.toString(), + signed, + size: size5 / 8, + value: value.toString() + }); + } + return { + dynamic: false, + encoded: numberToHex(value, { + size: 32, + signed + }) + }; +} +function encodeString(value) { + const hexValue = stringToHex(value); + const partsLength = Math.ceil(size(hexValue) / 32); + const parts = []; + for (let i = 0; i < partsLength; i++) { + parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), { + dir: "right" + })); + } + return { + dynamic: true, + encoded: concat([ + padHex(numberToHex(size(hexValue), { size: 32 })), + ...parts + ]) + }; +} +function encodeTuple(value, { param }) { + let dynamic = false; + const preparedParams = []; + for (let i = 0; i < param.components.length; i++) { + const param_ = param.components[i]; + const index2 = Array.isArray(value) ? i : param_.name; + const preparedParam = prepareParam({ + param: param_, + value: value[index2] + }); + preparedParams.push(preparedParam); + if (preparedParam.dynamic) + dynamic = true; + } + return { + dynamic, + encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded)) + }; +} +function getArrayComponents(type) { + const matches = type.match(/^(.*)\[(\d+)?\]$/); + return matches ? ( + // Return `null` if the array is dynamic. + [matches[2] ? Number(matches[2]) : null, matches[1]] + ) : void 0; +} +var init_encodeAbiParameters = __esm({ + "node_modules/viem/_esm/utils/abi/encodeAbiParameters.js"() { + init_abi(); + init_address(); + init_base(); + init_encoding(); + init_isAddress(); + init_concat(); + init_pad(); + init_size(); + init_slice(); + init_toHex(); + init_regex2(); + } +}); + +// node_modules/viem/_esm/utils/hash/toFunctionSelector.js +var toFunctionSelector; +var init_toFunctionSelector = __esm({ + "node_modules/viem/_esm/utils/hash/toFunctionSelector.js"() { + init_slice(); + init_toSignatureHash(); + toFunctionSelector = (fn2) => slice(toSignatureHash(fn2), 0, 4); + } +}); + +// node_modules/viem/_esm/utils/abi/getAbiItem.js +function getAbiItem(parameters) { + const { abi: abi4, args = [], name } = parameters; + const isSelector = isHex(name, { strict: false }); + const abiItems = abi4.filter((abiItem) => { + if (isSelector) { + if (abiItem.type === "function") + return toFunctionSelector(abiItem) === name; + if (abiItem.type === "event") + return toEventSelector(abiItem) === name; + return false; + } + return "name" in abiItem && abiItem.name === name; + }); + if (abiItems.length === 0) + return void 0; + if (abiItems.length === 1) + return abiItems[0]; + let matchedAbiItem = void 0; + for (const abiItem of abiItems) { + if (!("inputs" in abiItem)) + continue; + if (!args || args.length === 0) { + if (!abiItem.inputs || abiItem.inputs.length === 0) + return abiItem; + continue; + } + if (!abiItem.inputs) + continue; + if (abiItem.inputs.length === 0) + continue; + if (abiItem.inputs.length !== args.length) + continue; + const matched = args.every((arg, index2) => { + const abiParameter = "inputs" in abiItem && abiItem.inputs[index2]; + if (!abiParameter) + return false; + return isArgOfType(arg, abiParameter); + }); + if (matched) { + if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { + const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args); + if (ambiguousTypes) + throw new AbiItemAmbiguityError({ + abiItem, + type: ambiguousTypes[0] + }, { + abiItem: matchedAbiItem, + type: ambiguousTypes[1] + }); + } + matchedAbiItem = abiItem; + } + } + if (matchedAbiItem) + return matchedAbiItem; + return abiItems[0]; +} +function isArgOfType(arg, abiParameter) { + const argType = typeof arg; + const abiParameterType = abiParameter.type; + switch (abiParameterType) { + case "address": + return isAddress(arg, { strict: false }); + case "bool": + return argType === "boolean"; + case "function": + return argType === "string"; + case "string": + return argType === "string"; + default: { + if (abiParameterType === "tuple" && "components" in abiParameter) + return Object.values(abiParameter.components).every((component, index2) => { + return isArgOfType(Object.values(arg)[index2], component); + }); + if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) + return argType === "number" || argType === "bigint"; + if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) + return argType === "string" || arg instanceof Uint8Array; + if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { + return Array.isArray(arg) && arg.every((x2) => isArgOfType(x2, { + ...abiParameter, + // Pop off `[]` or `[M]` from end of type + type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") + })); + } + return false; + } + } +} +function getAmbiguousTypes(sourceParameters, targetParameters, args) { + for (const parameterIndex in sourceParameters) { + const sourceParameter = sourceParameters[parameterIndex]; + const targetParameter = targetParameters[parameterIndex]; + if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) + return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]); + const types = [sourceParameter.type, targetParameter.type]; + const ambiguous = (() => { + if (types.includes("address") && types.includes("bytes20")) + return true; + if (types.includes("address") && types.includes("string")) + return isAddress(args[parameterIndex], { strict: false }); + if (types.includes("address") && types.includes("bytes")) + return isAddress(args[parameterIndex], { strict: false }); + return false; + })(); + if (ambiguous) + return types; + } + return; +} +var init_getAbiItem = __esm({ + "node_modules/viem/_esm/utils/abi/getAbiItem.js"() { + init_abi(); + init_isHex(); + init_isAddress(); + init_toEventSelector(); + init_toFunctionSelector(); + } +}); + +// node_modules/viem/_esm/accounts/utils/parseAccount.js +function parseAccount(account) { + if (typeof account === "string") + return { address: account, type: "json-rpc" }; + return account; +} +var init_parseAccount = __esm({ + "node_modules/viem/_esm/accounts/utils/parseAccount.js"() { + } +}); + +// node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js +function prepareEncodeFunctionData(parameters) { + const { abi: abi4, args, functionName } = parameters; + let abiItem = abi4[0]; + if (functionName) { + const item = getAbiItem({ + abi: abi4, + args, + name: functionName + }); + if (!item) + throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath2 }); + abiItem = item; + } + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath2 }); + return { + abi: [abiItem], + functionName: toFunctionSelector(formatAbiItem2(abiItem)) + }; +} +var docsPath2; +var init_prepareEncodeFunctionData = __esm({ + "node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js"() { + init_abi(); + init_toFunctionSelector(); + init_formatAbiItem2(); + init_getAbiItem(); + docsPath2 = "/docs/contract/encodeFunctionData"; + } +}); + +// node_modules/viem/_esm/utils/abi/encodeFunctionData.js +function encodeFunctionData(parameters) { + const { args } = parameters; + const { abi: abi4, functionName } = (() => { + if (parameters.abi.length === 1 && parameters.functionName?.startsWith("0x")) + return parameters; + return prepareEncodeFunctionData(parameters); + })(); + const abiItem = abi4[0]; + const signature = functionName; + const data = "inputs" in abiItem && abiItem.inputs ? encodeAbiParameters(abiItem.inputs, args ?? []) : void 0; + return concatHex([signature, data ?? "0x"]); +} +var init_encodeFunctionData = __esm({ + "node_modules/viem/_esm/utils/abi/encodeFunctionData.js"() { + init_concat(); + init_encodeAbiParameters(); + init_prepareEncodeFunctionData(); + } +}); + +// node_modules/viem/_esm/constants/solidity.js +var panicReasons, solidityError, solidityPanic; +var init_solidity = __esm({ + "node_modules/viem/_esm/constants/solidity.js"() { + panicReasons = { + 1: "An `assert` condition failed.", + 17: "Arithmetic operation resulted in underflow or overflow.", + 18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).", + 33: "Attempted to convert to an invalid type.", + 34: "Attempted to access a storage byte array that is incorrectly encoded.", + 49: "Performed `.pop()` on an empty array", + 50: "Array index is out of bounds.", + 65: "Allocated too much memory or created an array which is too large.", + 81: "Attempted to call a zero-initialized variable of internal function type." + }; + solidityError = { + inputs: [ + { + name: "message", + type: "string" + } + ], + name: "Error", + type: "error" + }; + solidityPanic = { + inputs: [ + { + name: "reason", + type: "uint256" + } + ], + name: "Panic", + type: "error" + }; + } +}); + +// node_modules/viem/_esm/errors/cursor.js +var NegativeOffsetError, PositionOutOfBoundsError, RecursiveReadLimitExceededError; +var init_cursor = __esm({ + "node_modules/viem/_esm/errors/cursor.js"() { + init_base(); + NegativeOffsetError = class extends BaseError2 { + constructor({ offset }) { + super(`Offset \`${offset}\` cannot be negative.`, { + name: "NegativeOffsetError" + }); + } + }; + PositionOutOfBoundsError = class extends BaseError2 { + constructor({ length, position }) { + super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" }); + } + }; + RecursiveReadLimitExceededError = class extends BaseError2 { + constructor({ count, limit }) { + super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: "RecursiveReadLimitExceededError" }); + } + }; + } +}); + +// node_modules/viem/_esm/utils/cursor.js +function createCursor(bytes, { recursiveReadLimit = 8192 } = {}) { + const cursor = Object.create(staticCursor); + cursor.bytes = bytes; + cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + cursor.positionReadCount = /* @__PURE__ */ new Map(); + cursor.recursiveReadLimit = recursiveReadLimit; + return cursor; +} +var staticCursor; +var init_cursor2 = __esm({ + "node_modules/viem/_esm/utils/cursor.js"() { + init_cursor(); + staticCursor = { + bytes: new Uint8Array(), + dataView: new DataView(new ArrayBuffer(0)), + position: 0, + positionReadCount: /* @__PURE__ */ new Map(), + recursiveReadCount: 0, + recursiveReadLimit: Number.POSITIVE_INFINITY, + assertReadLimit() { + if (this.recursiveReadCount >= this.recursiveReadLimit) + throw new RecursiveReadLimitExceededError({ + count: this.recursiveReadCount + 1, + limit: this.recursiveReadLimit + }); + }, + assertPosition(position) { + if (position < 0 || position > this.bytes.length - 1) + throw new PositionOutOfBoundsError({ + length: this.bytes.length, + position + }); + }, + decrementPosition(offset) { + if (offset < 0) + throw new NegativeOffsetError({ offset }); + const position = this.position - offset; + this.assertPosition(position); + this.position = position; + }, + getReadCount(position) { + return this.positionReadCount.get(position || this.position) || 0; + }, + incrementPosition(offset) { + if (offset < 0) + throw new NegativeOffsetError({ offset }); + const position = this.position + offset; + this.assertPosition(position); + this.position = position; + }, + inspectByte(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectBytes(length, position_) { + const position = position_ ?? this.position; + this.assertPosition(position + length - 1); + return this.bytes.subarray(position, position + length); + }, + inspectUint8(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectUint16(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 1); + return this.dataView.getUint16(position); + }, + inspectUint24(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 2); + return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); + }, + inspectUint32(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 3); + return this.dataView.getUint32(position); + }, + pushByte(byte) { + this.assertPosition(this.position); + this.bytes[this.position] = byte; + this.position++; + }, + pushBytes(bytes) { + this.assertPosition(this.position + bytes.length - 1); + this.bytes.set(bytes, this.position); + this.position += bytes.length; + }, + pushUint8(value) { + this.assertPosition(this.position); + this.bytes[this.position] = value; + this.position++; + }, + pushUint16(value) { + this.assertPosition(this.position + 1); + this.dataView.setUint16(this.position, value); + this.position += 2; + }, + pushUint24(value) { + this.assertPosition(this.position + 2); + this.dataView.setUint16(this.position, value >> 8); + this.dataView.setUint8(this.position + 2, value & ~4294967040); + this.position += 3; + }, + pushUint32(value) { + this.assertPosition(this.position + 3); + this.dataView.setUint32(this.position, value); + this.position += 4; + }, + readByte() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectByte(); + this.position++; + return value; + }, + readBytes(length, size5) { + this.assertReadLimit(); + this._touch(); + const value = this.inspectBytes(length); + this.position += size5 ?? length; + return value; + }, + readUint8() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint8(); + this.position += 1; + return value; + }, + readUint16() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint16(); + this.position += 2; + return value; + }, + readUint24() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint24(); + this.position += 3; + return value; + }, + readUint32() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint32(); + this.position += 4; + return value; + }, + get remaining() { + return this.bytes.length - this.position; + }, + setPosition(position) { + const oldPosition = this.position; + this.assertPosition(position); + this.position = position; + return () => this.position = oldPosition; + }, + _touch() { + if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) + return; + const count = this.getReadCount(); + this.positionReadCount.set(this.position, count + 1); + if (count > 0) + this.recursiveReadCount++; + } + }; + } +}); + +// node_modules/viem/_esm/utils/encoding/fromBytes.js +function bytesToBigInt(bytes, opts = {}) { + if (typeof opts.size !== "undefined") + assertSize(bytes, { size: opts.size }); + const hex = bytesToHex(bytes, opts); + return hexToBigInt(hex, opts); +} +function bytesToBool(bytes_, opts = {}) { + let bytes = bytes_; + if (typeof opts.size !== "undefined") { + assertSize(bytes, { size: opts.size }); + bytes = trim2(bytes); + } + if (bytes.length > 1 || bytes[0] > 1) + throw new InvalidBytesBooleanError(bytes); + return Boolean(bytes[0]); +} +function bytesToNumber(bytes, opts = {}) { + if (typeof opts.size !== "undefined") + assertSize(bytes, { size: opts.size }); + const hex = bytesToHex(bytes, opts); + return hexToNumber(hex, opts); +} +function bytesToString(bytes_, opts = {}) { + let bytes = bytes_; + if (typeof opts.size !== "undefined") { + assertSize(bytes, { size: opts.size }); + bytes = trim2(bytes, { dir: "right" }); + } + return new TextDecoder().decode(bytes); +} +var init_fromBytes = __esm({ + "node_modules/viem/_esm/utils/encoding/fromBytes.js"() { + init_encoding(); + init_trim(); + init_fromHex(); + init_toHex(); + } +}); + +// node_modules/viem/_esm/utils/abi/decodeAbiParameters.js +function decodeAbiParameters(params, data) { + const bytes = typeof data === "string" ? hexToBytes(data) : data; + const cursor = createCursor(bytes); + if (size(bytes) === 0 && params.length > 0) + throw new AbiDecodingZeroDataError(); + if (size(data) && size(data) < 32) + throw new AbiDecodingDataSizeTooSmallError({ + data: typeof data === "string" ? data : bytesToHex(data), + params, + size: size(data) + }); + let consumed = 0; + const values = []; + for (let i = 0; i < params.length; ++i) { + const param = params[i]; + cursor.setPosition(consumed); + const [data2, consumed_] = decodeParameter(cursor, param, { + staticPosition: 0 + }); + consumed += consumed_; + values.push(data2); + } + return values; +} +function decodeParameter(cursor, param, { staticPosition }) { + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return decodeArray(cursor, { ...param, type }, { length, staticPosition }); + } + if (param.type === "tuple") + return decodeTuple(cursor, param, { staticPosition }); + if (param.type === "address") + return decodeAddress(cursor); + if (param.type === "bool") + return decodeBool(cursor); + if (param.type.startsWith("bytes")) + return decodeBytes(cursor, param, { staticPosition }); + if (param.type.startsWith("uint") || param.type.startsWith("int")) + return decodeNumber(cursor, param); + if (param.type === "string") + return decodeString(cursor, { staticPosition }); + throw new InvalidAbiDecodingTypeError(param.type, { + docsPath: "/docs/contract/decodeAbiParameters" + }); +} +function decodeAddress(cursor) { + const value = cursor.readBytes(32); + return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]; +} +function decodeArray(cursor, param, { length, staticPosition }) { + if (!length) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + const startOfData = start + sizeOfLength; + cursor.setPosition(start); + const length2 = bytesToNumber(cursor.readBytes(sizeOfLength)); + const dynamicChild = hasDynamicChild(param); + let consumed2 = 0; + const value2 = []; + for (let i = 0; i < length2; ++i) { + cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); + const [data, consumed_] = decodeParameter(cursor, param, { + staticPosition: startOfData + }); + consumed2 += consumed_; + value2.push(data); + } + cursor.setPosition(staticPosition + 32); + return [value2, 32]; + } + if (hasDynamicChild(param)) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + const value2 = []; + for (let i = 0; i < length; ++i) { + cursor.setPosition(start + i * 32); + const [data] = decodeParameter(cursor, param, { + staticPosition: start + }); + value2.push(data); + } + cursor.setPosition(staticPosition + 32); + return [value2, 32]; + } + let consumed = 0; + const value = []; + for (let i = 0; i < length; ++i) { + const [data, consumed_] = decodeParameter(cursor, param, { + staticPosition: staticPosition + consumed + }); + consumed += consumed_; + value.push(data); + } + return [value, consumed]; +} +function decodeBool(cursor) { + return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]; +} +function decodeBytes(cursor, param, { staticPosition }) { + const [_, size5] = param.type.split("bytes"); + if (!size5) { + const offset = bytesToNumber(cursor.readBytes(32)); + cursor.setPosition(staticPosition + offset); + const length = bytesToNumber(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["0x", 32]; + } + const data = cursor.readBytes(length); + cursor.setPosition(staticPosition + 32); + return [bytesToHex(data), 32]; + } + const value = bytesToHex(cursor.readBytes(Number.parseInt(size5), 32)); + return [value, 32]; +} +function decodeNumber(cursor, param) { + const signed = param.type.startsWith("int"); + const size5 = Number.parseInt(param.type.split("int")[1] || "256"); + const value = cursor.readBytes(32); + return [ + size5 > 48 ? bytesToBigInt(value, { signed }) : bytesToNumber(value, { signed }), + 32 + ]; +} +function decodeTuple(cursor, param, { staticPosition }) { + const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name); + const value = hasUnnamedChild ? [] : {}; + let consumed = 0; + if (hasDynamicChild(param)) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + for (let i = 0; i < param.components.length; ++i) { + const component = param.components[i]; + cursor.setPosition(start + consumed); + const [data, consumed_] = decodeParameter(cursor, component, { + staticPosition: start + }); + consumed += consumed_; + value[hasUnnamedChild ? i : component?.name] = data; + } + cursor.setPosition(staticPosition + 32); + return [value, 32]; + } + for (let i = 0; i < param.components.length; ++i) { + const component = param.components[i]; + const [data, consumed_] = decodeParameter(cursor, component, { + staticPosition + }); + value[hasUnnamedChild ? i : component?.name] = data; + consumed += consumed_; + } + return [value, consumed]; +} +function decodeString(cursor, { staticPosition }) { + const offset = bytesToNumber(cursor.readBytes(32)); + const start = staticPosition + offset; + cursor.setPosition(start); + const length = bytesToNumber(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["", 32]; + } + const data = cursor.readBytes(length, 32); + const value = bytesToString(trim2(data)); + cursor.setPosition(staticPosition + 32); + return [value, 32]; +} +function hasDynamicChild(param) { + const { type } = param; + if (type === "string") + return true; + if (type === "bytes") + return true; + if (type.endsWith("[]")) + return true; + if (type === "tuple") + return param.components?.some(hasDynamicChild); + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] })) + return true; + return false; +} +var sizeOfLength, sizeOfOffset; +var init_decodeAbiParameters = __esm({ + "node_modules/viem/_esm/utils/abi/decodeAbiParameters.js"() { + init_abi(); + init_getAddress(); + init_cursor2(); + init_size(); + init_slice(); + init_trim(); + init_fromBytes(); + init_toBytes(); + init_toHex(); + init_encodeAbiParameters(); + sizeOfLength = 32; + sizeOfOffset = 32; + } +}); + +// node_modules/viem/_esm/utils/abi/decodeErrorResult.js +function decodeErrorResult(parameters) { + const { abi: abi4, data } = parameters; + const signature = slice(data, 0, 4); + if (signature === "0x") + throw new AbiDecodingZeroDataError(); + const abi_ = [...abi4 || [], solidityError, solidityPanic]; + const abiItem = abi_.find((x2) => x2.type === "error" && signature === toFunctionSelector(formatAbiItem2(x2))); + if (!abiItem) + throw new AbiErrorSignatureNotFoundError(signature, { + docsPath: "/docs/contract/decodeErrorResult" + }); + return { + abiItem, + args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : void 0, + errorName: abiItem.name + }; +} +var init_decodeErrorResult = __esm({ + "node_modules/viem/_esm/utils/abi/decodeErrorResult.js"() { + init_solidity(); + init_abi(); + init_slice(); + init_toFunctionSelector(); + init_decodeAbiParameters(); + init_formatAbiItem2(); + } +}); + +// node_modules/viem/_esm/utils/stringify.js +var stringify; +var init_stringify = __esm({ + "node_modules/viem/_esm/utils/stringify.js"() { + stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => { + const value2 = typeof value_ === "bigint" ? value_.toString() : value_; + return typeof replacer === "function" ? replacer(key, value2) : value2; + }, space); + } +}); + +// node_modules/viem/_esm/utils/abi/formatAbiItemWithArgs.js +function formatAbiItemWithArgs({ abiItem, args, includeFunctionName = true, includeName = false }) { + if (!("name" in abiItem)) + return; + if (!("inputs" in abiItem)) + return; + if (!abiItem.inputs) + return; + return `${includeFunctionName ? abiItem.name : ""}(${abiItem.inputs.map((input, i) => `${includeName && input.name ? `${input.name}: ` : ""}${typeof args[i] === "object" ? stringify(args[i]) : args[i]}`).join(", ")})`; +} +var init_formatAbiItemWithArgs = __esm({ + "node_modules/viem/_esm/utils/abi/formatAbiItemWithArgs.js"() { + init_stringify(); + } +}); + +// node_modules/viem/_esm/constants/unit.js +var etherUnits, gweiUnits; +var init_unit = __esm({ + "node_modules/viem/_esm/constants/unit.js"() { + etherUnits = { + gwei: 9, + wei: 18 + }; + gweiUnits = { + ether: -9, + wei: 9 + }; + } +}); + +// node_modules/viem/_esm/utils/unit/formatUnits.js +function formatUnits(value, decimals) { + let display = value.toString(); + const negative = display.startsWith("-"); + if (negative) + display = display.slice(1); + display = display.padStart(decimals, "0"); + let [integer, fraction] = [ + display.slice(0, display.length - decimals), + display.slice(display.length - decimals) + ]; + fraction = fraction.replace(/(0+)$/, ""); + return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`; +} +var init_formatUnits = __esm({ + "node_modules/viem/_esm/utils/unit/formatUnits.js"() { + } +}); + +// node_modules/viem/_esm/utils/unit/formatEther.js +function formatEther(wei, unit = "wei") { + return formatUnits(wei, etherUnits[unit]); +} +var init_formatEther = __esm({ + "node_modules/viem/_esm/utils/unit/formatEther.js"() { + init_unit(); + init_formatUnits(); + } +}); + +// node_modules/viem/_esm/utils/unit/formatGwei.js +function formatGwei(wei, unit = "wei") { + return formatUnits(wei, gweiUnits[unit]); +} +var init_formatGwei = __esm({ + "node_modules/viem/_esm/utils/unit/formatGwei.js"() { + init_unit(); + init_formatUnits(); + } +}); + +// node_modules/viem/_esm/errors/stateOverride.js +function prettyStateMapping(stateMapping) { + return stateMapping.reduce((pretty, { slot, value }) => { + return `${pretty} ${slot}: ${value} +`; + }, ""); +} +function prettyStateOverride(stateOverride) { + return stateOverride.reduce((pretty, { address, ...state }) => { + let val = `${pretty} ${address}: +`; + if (state.nonce) + val += ` nonce: ${state.nonce} +`; + if (state.balance) + val += ` balance: ${state.balance} +`; + if (state.code) + val += ` code: ${state.code} +`; + if (state.state) { + val += " state:\n"; + val += prettyStateMapping(state.state); + } + if (state.stateDiff) { + val += " stateDiff:\n"; + val += prettyStateMapping(state.stateDiff); + } + return val; + }, " State Override:\n").slice(0, -1); +} +var AccountStateConflictError, StateAssignmentConflictError; +var init_stateOverride = __esm({ + "node_modules/viem/_esm/errors/stateOverride.js"() { + init_base(); + AccountStateConflictError = class extends BaseError2 { + constructor({ address }) { + super(`State for account "${address}" is set multiple times.`, { + name: "AccountStateConflictError" + }); + } + }; + StateAssignmentConflictError = class extends BaseError2 { + constructor() { + super("state and stateDiff are set on the same account.", { + name: "StateAssignmentConflictError" + }); + } + }; + } +}); + +// node_modules/viem/_esm/errors/transaction.js +function prettyPrint(args) { + const entries = Object.entries(args).map(([key, value]) => { + if (value === void 0 || value === false) + return null; + return [key, value]; + }).filter(Boolean); + const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0); + return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n"); +} +var FeeConflictError, InvalidLegacyVError, InvalidSerializableTransactionError, InvalidStorageKeySizeError, TransactionExecutionError, TransactionNotFoundError, TransactionReceiptNotFoundError, WaitForTransactionReceiptTimeoutError; +var init_transaction = __esm({ + "node_modules/viem/_esm/errors/transaction.js"() { + init_formatEther(); + init_formatGwei(); + init_base(); + FeeConflictError = class extends BaseError2 { + constructor() { + super([ + "Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.", + "Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others." + ].join("\n"), { name: "FeeConflictError" }); + } + }; + InvalidLegacyVError = class extends BaseError2 { + constructor({ v }) { + super(`Invalid \`v\` value "${v}". Expected 27 or 28.`, { + name: "InvalidLegacyVError" + }); + } + }; + InvalidSerializableTransactionError = class extends BaseError2 { + constructor({ transaction }) { + super("Cannot infer a transaction type from provided transaction.", { + metaMessages: [ + "Provided Transaction:", + "{", + prettyPrint(transaction), + "}", + "", + "To infer the type, either provide:", + "- a `type` to the Transaction, or", + "- an EIP-1559 Transaction with `maxFeePerGas`, or", + "- an EIP-2930 Transaction with `gasPrice` & `accessList`, or", + "- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or", + "- an EIP-7702 Transaction with `authorizationList`, or", + "- a Legacy Transaction with `gasPrice`" + ], + name: "InvalidSerializableTransactionError" + }); + } + }; + InvalidStorageKeySizeError = class extends BaseError2 { + constructor({ storageKey }) { + super(`Size for storage key "${storageKey}" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: "InvalidStorageKeySizeError" }); + } + }; + TransactionExecutionError = class extends BaseError2 { + constructor(cause, { account, docsPath: docsPath6, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value }) { + const prettyArgs = prettyPrint({ + chain: chain && `${chain?.name} (id: ${chain?.id})`, + from: account?.address, + to: to2, + value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, + data, + gas, + gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, + maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, + maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, + nonce + }); + super(cause.shortMessage, { + cause, + docsPath: docsPath6, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Request Arguments:", + prettyArgs + ].filter(Boolean), + name: "TransactionExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cause = cause; + } + }; + TransactionNotFoundError = class extends BaseError2 { + constructor({ blockHash, blockNumber, blockTag, hash: hash2, index: index2 }) { + let identifier = "Transaction"; + if (blockTag && index2 !== void 0) + identifier = `Transaction at block time "${blockTag}" at index "${index2}"`; + if (blockHash && index2 !== void 0) + identifier = `Transaction at block hash "${blockHash}" at index "${index2}"`; + if (blockNumber && index2 !== void 0) + identifier = `Transaction at block number "${blockNumber}" at index "${index2}"`; + if (hash2) + identifier = `Transaction with hash "${hash2}"`; + super(`${identifier} could not be found.`, { + name: "TransactionNotFoundError" + }); + } + }; + TransactionReceiptNotFoundError = class extends BaseError2 { + constructor({ hash: hash2 }) { + super(`Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`, { + name: "TransactionReceiptNotFoundError" + }); + } + }; + WaitForTransactionReceiptTimeoutError = class extends BaseError2 { + constructor({ hash: hash2 }) { + super(`Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`, { name: "WaitForTransactionReceiptTimeoutError" }); + } + }; + } +}); + +// node_modules/viem/_esm/errors/utils.js +var getContractAddress, getUrl; +var init_utils3 = __esm({ + "node_modules/viem/_esm/errors/utils.js"() { + getContractAddress = (address) => address; + getUrl = (url2) => url2; + } +}); + +// node_modules/viem/_esm/errors/contract.js +var CallExecutionError, ContractFunctionExecutionError, ContractFunctionRevertedError, ContractFunctionZeroDataError, CounterfactualDeploymentFailedError, RawContractError; +var init_contract = __esm({ + "node_modules/viem/_esm/errors/contract.js"() { + init_parseAccount(); + init_solidity(); + init_decodeErrorResult(); + init_formatAbiItem2(); + init_formatAbiItemWithArgs(); + init_getAbiItem(); + init_formatEther(); + init_formatGwei(); + init_abi(); + init_base(); + init_stateOverride(); + init_transaction(); + init_utils3(); + CallExecutionError = class extends BaseError2 { + constructor(cause, { account: account_, docsPath: docsPath6, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value, stateOverride }) { + const account = account_ ? parseAccount(account_) : void 0; + let prettyArgs = prettyPrint({ + from: account?.address, + to: to2, + value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, + data, + gas, + gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, + maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, + maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, + nonce + }); + if (stateOverride) { + prettyArgs += ` +${prettyStateOverride(stateOverride)}`; + } + super(cause.shortMessage, { + cause, + docsPath: docsPath6, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Raw Call Arguments:", + prettyArgs + ].filter(Boolean), + name: "CallExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cause = cause; + } + }; + ContractFunctionExecutionError = class extends BaseError2 { + constructor(cause, { abi: abi4, args, contractAddress, docsPath: docsPath6, functionName, sender }) { + const abiItem = getAbiItem({ abi: abi4, args, name: functionName }); + const formattedArgs = abiItem ? formatAbiItemWithArgs({ + abiItem, + args, + includeFunctionName: false, + includeName: false + }) : void 0; + const functionWithParams = abiItem ? formatAbiItem2(abiItem, { includeName: true }) : void 0; + const prettyArgs = prettyPrint({ + address: contractAddress && getContractAddress(contractAddress), + function: functionWithParams, + args: formattedArgs && formattedArgs !== "()" && `${[...Array(functionName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`, + sender + }); + super(cause.shortMessage || `An unknown error occurred while executing the contract function "${functionName}".`, { + cause, + docsPath: docsPath6, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + prettyArgs && "Contract Call:", + prettyArgs + ].filter(Boolean), + name: "ContractFunctionExecutionError" + }); + Object.defineProperty(this, "abi", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "args", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "contractAddress", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "formattedArgs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "functionName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sender", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.abi = abi4; + this.args = args; + this.cause = cause; + this.contractAddress = contractAddress; + this.functionName = functionName; + this.sender = sender; + } + }; + ContractFunctionRevertedError = class extends BaseError2 { + constructor({ abi: abi4, data, functionName, message }) { + let cause; + let decodedData = void 0; + let metaMessages; + let reason; + if (data && data !== "0x") { + try { + decodedData = decodeErrorResult({ abi: abi4, data }); + const { abiItem, errorName, args: errorArgs } = decodedData; + if (errorName === "Error") { + reason = errorArgs[0]; + } else if (errorName === "Panic") { + const [firstArg] = errorArgs; + reason = panicReasons[firstArg]; + } else { + const errorWithParams = abiItem ? formatAbiItem2(abiItem, { includeName: true }) : void 0; + const formattedArgs = abiItem && errorArgs ? formatAbiItemWithArgs({ + abiItem, + args: errorArgs, + includeFunctionName: false, + includeName: false + }) : void 0; + metaMessages = [ + errorWithParams ? `Error: ${errorWithParams}` : "", + formattedArgs && formattedArgs !== "()" ? ` ${[...Array(errorName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : "" + ]; + } + } catch (err) { + cause = err; + } + } else if (message) + reason = message; + let signature; + if (cause instanceof AbiErrorSignatureNotFoundError) { + signature = cause.signature; + metaMessages = [ + `Unable to decode signature "${signature}" as it was not found on the provided ABI.`, + "Make sure you are using the correct ABI and that the error exists on it.", + `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.` + ]; + } + super(reason && reason !== "execution reverted" || signature ? [ + `The contract function "${functionName}" reverted with the following ${signature ? "signature" : "reason"}:`, + reason || signature + ].join("\n") : `The contract function "${functionName}" reverted.`, { + cause, + metaMessages, + name: "ContractFunctionRevertedError" + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "raw", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "reason", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "signature", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = decodedData; + this.raw = data; + this.reason = reason; + this.signature = signature; + } + }; + ContractFunctionZeroDataError = class extends BaseError2 { + constructor({ functionName }) { + super(`The contract function "${functionName}" returned no data ("0x").`, { + metaMessages: [ + "This could be due to any of the following:", + ` - The contract does not have the function "${functionName}",`, + " - The parameters passed to the contract function may be invalid, or", + " - The address is not a contract." + ], + name: "ContractFunctionZeroDataError" + }); + } + }; + CounterfactualDeploymentFailedError = class extends BaseError2 { + constructor({ factory }) { + super(`Deployment for counterfactual contract call failed${factory ? ` for factory "${factory}".` : ""}`, { + metaMessages: [ + "Please ensure:", + "- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).", + "- The `factoryData` is a valid encoded function call for contract deployment function on the factory." + ], + name: "CounterfactualDeploymentFailedError" + }); + } + }; + RawContractError = class extends BaseError2 { + constructor({ data, message }) { + super(message || "", { name: "RawContractError" }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 3 + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = data; + } + }; + } +}); + +// node_modules/viem/_esm/errors/request.js +var HttpRequestError, RpcRequestError, TimeoutError; +var init_request = __esm({ + "node_modules/viem/_esm/errors/request.js"() { + init_stringify(); + init_base(); + init_utils3(); + HttpRequestError = class extends BaseError2 { + constructor({ body, cause, details, headers, status, url: url2 }) { + super("HTTP request failed.", { + cause, + details, + metaMessages: [ + status && `Status: ${status}`, + `URL: ${getUrl(url2)}`, + body && `Request body: ${stringify(body)}` + ].filter(Boolean), + name: "HttpRequestError" + }); + Object.defineProperty(this, "body", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "url", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.body = body; + this.headers = headers; + this.status = status; + this.url = url2; + } + }; + RpcRequestError = class extends BaseError2 { + constructor({ body, error, url: url2 }) { + super("RPC Request failed.", { + cause: error, + details: error.message, + metaMessages: [`URL: ${getUrl(url2)}`, `Request body: ${stringify(body)}`], + name: "RpcRequestError" + }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.code = error.code; + this.data = error.data; + } + }; + TimeoutError = class extends BaseError2 { + constructor({ body, url: url2 }) { + super("The request took too long to respond.", { + details: "The request timed out.", + metaMessages: [`URL: ${getUrl(url2)}`, `Request body: ${stringify(body)}`], + name: "TimeoutError" + }); + } + }; + } +}); + +// node_modules/viem/_esm/errors/rpc.js +var unknownErrorCode, RpcError, ProviderRpcError, ParseRpcError, InvalidRequestRpcError, MethodNotFoundRpcError, InvalidParamsRpcError, InternalRpcError, InvalidInputRpcError, ResourceNotFoundRpcError, ResourceUnavailableRpcError, TransactionRejectedRpcError, MethodNotSupportedRpcError, LimitExceededRpcError, JsonRpcVersionUnsupportedError, UserRejectedRequestError, UnauthorizedProviderError, UnsupportedProviderMethodError, ProviderDisconnectedError, ChainDisconnectedError, SwitchChainError, UnknownRpcError; +var init_rpc = __esm({ + "node_modules/viem/_esm/errors/rpc.js"() { + init_base(); + init_request(); + unknownErrorCode = -1; + RpcError = class extends BaseError2 { + constructor(cause, { code, docsPath: docsPath6, metaMessages, name, shortMessage }) { + super(shortMessage, { + cause, + docsPath: docsPath6, + metaMessages: metaMessages || cause?.metaMessages, + name: name || "RpcError" + }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = name || cause.name; + this.code = cause instanceof RpcRequestError ? cause.code : code ?? unknownErrorCode; + } + }; + ProviderRpcError = class extends RpcError { + constructor(cause, options) { + super(cause, options); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = options.data; + } + }; + ParseRpcError = class _ParseRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _ParseRpcError.code, + name: "ParseRpcError", + shortMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text." + }); + } + }; + Object.defineProperty(ParseRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32700 + }); + InvalidRequestRpcError = class _InvalidRequestRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _InvalidRequestRpcError.code, + name: "InvalidRequestRpcError", + shortMessage: "JSON is not a valid request object." + }); + } + }; + Object.defineProperty(InvalidRequestRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32600 + }); + MethodNotFoundRpcError = class _MethodNotFoundRpcError extends RpcError { + constructor(cause, { method } = {}) { + super(cause, { + code: _MethodNotFoundRpcError.code, + name: "MethodNotFoundRpcError", + shortMessage: `The method${method ? ` "${method}"` : ""} does not exist / is not available.` + }); + } + }; + Object.defineProperty(MethodNotFoundRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32601 + }); + InvalidParamsRpcError = class _InvalidParamsRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _InvalidParamsRpcError.code, + name: "InvalidParamsRpcError", + shortMessage: [ + "Invalid parameters were provided to the RPC method.", + "Double check you have provided the correct parameters." + ].join("\n") + }); + } + }; + Object.defineProperty(InvalidParamsRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32602 + }); + InternalRpcError = class _InternalRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _InternalRpcError.code, + name: "InternalRpcError", + shortMessage: "An internal error was received." + }); + } + }; + Object.defineProperty(InternalRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32603 + }); + InvalidInputRpcError = class _InvalidInputRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _InvalidInputRpcError.code, + name: "InvalidInputRpcError", + shortMessage: [ + "Missing or invalid parameters.", + "Double check you have provided the correct parameters." + ].join("\n") + }); + } + }; + Object.defineProperty(InvalidInputRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32e3 + }); + ResourceNotFoundRpcError = class _ResourceNotFoundRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _ResourceNotFoundRpcError.code, + name: "ResourceNotFoundRpcError", + shortMessage: "Requested resource not found." + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "ResourceNotFoundRpcError" + }); + } + }; + Object.defineProperty(ResourceNotFoundRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32001 + }); + ResourceUnavailableRpcError = class _ResourceUnavailableRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _ResourceUnavailableRpcError.code, + name: "ResourceUnavailableRpcError", + shortMessage: "Requested resource not available." + }); + } + }; + Object.defineProperty(ResourceUnavailableRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32002 + }); + TransactionRejectedRpcError = class _TransactionRejectedRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _TransactionRejectedRpcError.code, + name: "TransactionRejectedRpcError", + shortMessage: "Transaction creation failed." + }); + } + }; + Object.defineProperty(TransactionRejectedRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32003 + }); + MethodNotSupportedRpcError = class _MethodNotSupportedRpcError extends RpcError { + constructor(cause, { method } = {}) { + super(cause, { + code: _MethodNotSupportedRpcError.code, + name: "MethodNotSupportedRpcError", + shortMessage: `Method${method ? ` "${method}"` : ""} is not supported.` + }); + } + }; + Object.defineProperty(MethodNotSupportedRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32004 + }); + LimitExceededRpcError = class _LimitExceededRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _LimitExceededRpcError.code, + name: "LimitExceededRpcError", + shortMessage: "Request exceeds defined limit." + }); + } + }; + Object.defineProperty(LimitExceededRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32005 + }); + JsonRpcVersionUnsupportedError = class _JsonRpcVersionUnsupportedError extends RpcError { + constructor(cause) { + super(cause, { + code: _JsonRpcVersionUnsupportedError.code, + name: "JsonRpcVersionUnsupportedError", + shortMessage: "Version of JSON-RPC protocol is not supported." + }); + } + }; + Object.defineProperty(JsonRpcVersionUnsupportedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32006 + }); + UserRejectedRequestError = class _UserRejectedRequestError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: _UserRejectedRequestError.code, + name: "UserRejectedRequestError", + shortMessage: "User rejected the request." + }); + } + }; + Object.defineProperty(UserRejectedRequestError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4001 + }); + UnauthorizedProviderError = class _UnauthorizedProviderError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: _UnauthorizedProviderError.code, + name: "UnauthorizedProviderError", + shortMessage: "The requested method and/or account has not been authorized by the user." + }); + } + }; + Object.defineProperty(UnauthorizedProviderError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4100 + }); + UnsupportedProviderMethodError = class _UnsupportedProviderMethodError extends ProviderRpcError { + constructor(cause, { method } = {}) { + super(cause, { + code: _UnsupportedProviderMethodError.code, + name: "UnsupportedProviderMethodError", + shortMessage: `The Provider does not support the requested method${method ? ` " ${method}"` : ""}.` + }); + } + }; + Object.defineProperty(UnsupportedProviderMethodError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4200 + }); + ProviderDisconnectedError = class _ProviderDisconnectedError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: _ProviderDisconnectedError.code, + name: "ProviderDisconnectedError", + shortMessage: "The Provider is disconnected from all chains." + }); + } + }; + Object.defineProperty(ProviderDisconnectedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4900 + }); + ChainDisconnectedError = class _ChainDisconnectedError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: _ChainDisconnectedError.code, + name: "ChainDisconnectedError", + shortMessage: "The Provider is not connected to the requested chain." + }); + } + }; + Object.defineProperty(ChainDisconnectedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4901 + }); + SwitchChainError = class _SwitchChainError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: _SwitchChainError.code, + name: "SwitchChainError", + shortMessage: "An error occurred when attempting to switch chain." + }); + } + }; + Object.defineProperty(SwitchChainError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4902 + }); + UnknownRpcError = class extends RpcError { + constructor(cause) { + super(cause, { + name: "UnknownRpcError", + shortMessage: "An unknown RPC error occurred." + }); + } + }; + } +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/_md.js +function setBigUint64(view, byteOffset, value, isLE3) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE3); + const _32n3 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n3 & _u32_max); + const wl2 = Number(value & _u32_max); + const h = isLE3 ? 4 : 0; + const l = isLE3 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE3); + view.setUint32(byteOffset + l, wl2, isLE3); +} +function Chi(a, b2, c) { + return a & b2 ^ ~a & c; +} +function Maj(a, b2, c) { + return a & b2 ^ a & c ^ b2 & c; +} +var HashMD; +var init_md = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/_md.js"() { + init_assert(); + init_utils2(); + HashMD = class extends Hash { + constructor(blockLen, outputLen, padOffset, isLE3) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE3; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + const { view, buffer: buffer2, blockLen } = this; + data = toBytes2(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer2.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE3 } = this; + let { pos } = this; + buffer2[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer2[i] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE3); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to2) { + to2 || (to2 = new this.constructor()); + to2.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to2.length = length; + to2.pos = pos; + to2.finished = finished; + to2.destroyed = destroyed; + if (length % blockLen) + to2.buffer.set(buffer2); + return to2; + } + }; + } +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/sha256.js +var SHA256_K, SHA256_IV, SHA256_W, SHA256, sha256; +var init_sha256 = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/sha256.js"() { + init_md(); + init_utils2(); + SHA256_K = /* @__PURE__ */ new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]); + SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 + ]); + SHA256_W = /* @__PURE__ */ new Uint32Array(64); + SHA256 = class extends HashMD { + constructor() { + super(64, 32, 8, false); + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A: A2, B: B2, C, D, E, F: F2, G: G2, H: H2 } = this; + return [A2, B2, C, D, E, F2, G2, H2]; + } + // prettier-ignore + set(A2, B2, C, D, E, F2, G2, H2) { + this.A = A2 | 0; + this.B = B2 | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F2 | 0; + this.G = G2 | 0; + this.H = H2 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A: A2, B: B2, C, D, E, F: F2, G: G2, H: H2 } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H2 + sigma1 + Chi(E, F2, G2) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A2, 2) ^ rotr(A2, 13) ^ rotr(A2, 22); + const T2 = sigma0 + Maj(A2, B2, C) | 0; + H2 = G2; + G2 = F2; + F2 = E; + E = D + T1 | 0; + D = C; + C = B2; + B2 = A2; + A2 = T1 + T2 | 0; + } + A2 = A2 + this.A | 0; + B2 = B2 + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F2 = F2 + this.F | 0; + G2 = G2 + this.G | 0; + H2 = H2 + this.H | 0; + this.set(A2, B2, C, D, E, F2, G2, H2); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } + }; + sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); + } +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/hmac.js +var HMAC, hmac; +var init_hmac = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/hmac.js"() { + init_assert(); + init_utils2(); + HMAC = class extends Hash { + constructor(hash2, _key) { + super(); + this.finished = false; + this.destroyed = false; + ahash(hash2); + const key = toBytes2(_key); + this.iHash = hash2.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad4 = new Uint8Array(blockLen); + pad4.set(key.length > blockLen ? hash2.create().update(key).digest() : key); + for (let i = 0; i < pad4.length; i++) + pad4[i] ^= 54; + this.iHash.update(pad4); + this.oHash = hash2.create(); + for (let i = 0; i < pad4.length; i++) + pad4[i] ^= 54 ^ 92; + this.oHash.update(pad4); + pad4.fill(0); + } + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + aexists(this); + abytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to2) { + to2 || (to2 = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to2 = to2; + to2.finished = finished; + to2.destroyed = destroyed; + to2.blockLen = blockLen; + to2.outputLen = outputLen; + to2.oHash = oHash._cloneInto(to2.oHash); + to2.iHash = iHash._cloneInto(to2.iHash); + return to2; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } + }; + hmac = (hash2, key, message) => new HMAC(hash2, key).update(message).digest(); + hmac.create = (hash2, key) => new HMAC(hash2, key); + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/abstract/utils.js +var utils_exports2 = {}; +__export(utils_exports2, { + aInRange: () => aInRange, + abool: () => abool, + abytes: () => abytes2, + bitGet: () => bitGet, + bitLen: () => bitLen, + bitMask: () => bitMask, + bitSet: () => bitSet, + bytesToHex: () => bytesToHex2, + bytesToNumberBE: () => bytesToNumberBE, + bytesToNumberLE: () => bytesToNumberLE, + concatBytes: () => concatBytes3, + createHmacDrbg: () => createHmacDrbg, + ensureBytes: () => ensureBytes, + equalBytes: () => equalBytes, + hexToBytes: () => hexToBytes2, + hexToNumber: () => hexToNumber2, + inRange: () => inRange, + isBytes: () => isBytes2, + memoized: () => memoized, + notImplemented: () => notImplemented, + numberToBytesBE: () => numberToBytesBE, + numberToBytesLE: () => numberToBytesLE, + numberToHexUnpadded: () => numberToHexUnpadded, + numberToVarBytesBE: () => numberToVarBytesBE, + utf8ToBytes: () => utf8ToBytes2, + validateObject: () => validateObject +}); +function isBytes2(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; +} +function abytes2(item) { + if (!isBytes2(item)) + throw new Error("Uint8Array expected"); +} +function abool(title, value) { + if (typeof value !== "boolean") + throw new Error(title + " boolean expected, got " + value); +} +function bytesToHex2(bytes) { + abytes2(bytes); + let hex = ""; + for (let i = 0; i < bytes.length; i++) { + hex += hexes2[bytes[i]]; + } + return hex; +} +function numberToHexUnpadded(num2) { + const hex = num2.toString(16); + return hex.length & 1 ? "0" + hex : hex; +} +function hexToNumber2(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + return hex === "" ? _0n2 : BigInt("0x" + hex); +} +function asciiToBase16(ch) { + if (ch >= asciis._0 && ch <= asciis._9) + return ch - asciis._0; + if (ch >= asciis.A && ch <= asciis.F) + return ch - (asciis.A - 10); + if (ch >= asciis.a && ch <= asciis.f) + return ch - (asciis.a - 10); + return; +} +function hexToBytes2(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + const hl2 = hex.length; + const al2 = hl2 / 2; + if (hl2 % 2) + throw new Error("hex string expected, got unpadded hex of length " + hl2); + const array = new Uint8Array(al2); + for (let ai2 = 0, hi2 = 0; ai2 < al2; ai2++, hi2 += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi2)); + const n2 = asciiToBase16(hex.charCodeAt(hi2 + 1)); + if (n1 === void 0 || n2 === void 0) { + const char = hex[hi2] + hex[hi2 + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi2); + } + array[ai2] = n1 * 16 + n2; + } + return array; +} +function bytesToNumberBE(bytes) { + return hexToNumber2(bytesToHex2(bytes)); +} +function bytesToNumberLE(bytes) { + abytes2(bytes); + return hexToNumber2(bytesToHex2(Uint8Array.from(bytes).reverse())); +} +function numberToBytesBE(n, len) { + return hexToBytes2(n.toString(16).padStart(len * 2, "0")); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +function numberToVarBytesBE(n) { + return hexToBytes2(numberToHexUnpadded(n)); +} +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === "string") { + try { + res = hexToBytes2(hex); + } catch (e) { + throw new Error(title + " must be hex string or Uint8Array, cause: " + e); + } + } else if (isBytes2(hex)) { + res = Uint8Array.from(hex); + } else { + throw new Error(title + " must be hex string or Uint8Array"); + } + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) + throw new Error(title + " of length " + expectedLength + " expected, got " + len); + return res; +} +function concatBytes3(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes2(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad4 = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad4); + pad4 += a.length; + } + return res; +} +function equalBytes(a, b2) { + if (a.length !== b2.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b2[i]; + return diff === 0; +} +function utf8ToBytes2(str) { + if (typeof str !== "string") + throw new Error("string expected"); + return new Uint8Array(new TextEncoder().encode(str)); +} +function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +function aInRange(title, n, min, max) { + if (!inRange(n, min, max)) + throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); +} +function bitLen(n) { + let len; + for (len = 0; n > _0n2; n >>= _1n2, len += 1) + ; + return len; +} +function bitGet(n, pos) { + return n >> BigInt(pos) & _1n2; +} +function bitSet(n, pos, value) { + return n | (value ? _1n2 : _0n2) << BigInt(pos); +} +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) + throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) + throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") + throw new Error("hmacFn must be a function"); + let v = u8n(hashLen); + let k2 = u8n(hashLen); + let i = 0; + const reset = () => { + v.fill(1); + k2.fill(0); + i = 0; + }; + const h = (...b2) => hmacFn(k2, v, ...b2); + const reseed = (seed = u8n()) => { + k2 = h(u8fr([0]), seed); + v = h(); + if (seed.length === 0) + return; + k2 = h(u8fr([1]), seed); + v = h(); + }; + const gen3 = () => { + if (i++ >= 1e3) + throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl2 = v.slice(); + out.push(sl2); + len += v.length; + } + return concatBytes3(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = void 0; + while (!(res = pred(gen3()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +function validateObject(object, validators3, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== "function") + throw new Error("invalid validator function"); + const val = object[fieldName]; + if (isOptional && val === void 0) + return; + if (!checkVal(val, object)) { + throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val); + } + }; + for (const [fieldName, type] of Object.entries(validators3)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +function memoized(fn2) { + const map = /* @__PURE__ */ new WeakMap(); + return (arg, ...args) => { + const val = map.get(arg); + if (val !== void 0) + return val; + const computed = fn2(arg, ...args); + map.set(arg, computed); + return computed; + }; +} +var _0n2, _1n2, _2n2, hexes2, asciis, isPosBig, bitMask, u8n, u8fr, validatorFns, notImplemented; +var init_utils4 = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/abstract/utils.js"() { + _0n2 = /* @__PURE__ */ BigInt(0); + _1n2 = /* @__PURE__ */ BigInt(1); + _2n2 = /* @__PURE__ */ BigInt(2); + hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); + asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; + isPosBig = (n) => typeof n === "bigint" && _0n2 <= n; + bitMask = (n) => (_2n2 << BigInt(n - 1)) - _1n2; + u8n = (data) => new Uint8Array(data); + u8fr = (arr) => Uint8Array.from(arr); + validatorFns = { + bigint: (val) => typeof val === "bigint", + function: (val) => typeof val === "function", + boolean: (val) => typeof val === "boolean", + string: (val) => typeof val === "string", + stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val), + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) + }; + notImplemented = () => { + throw new Error("not implemented"); + }; + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/abstract/modular.js +function mod(a, b2) { + const result = a % b2; + return result >= _0n3 ? result : b2 + result; +} +function pow(num2, power, modulo) { + if (power < _0n3) + throw new Error("invalid exponent, negatives unsupported"); + if (modulo <= _0n3) + throw new Error("invalid modulus"); + if (modulo === _1n3) + return _0n3; + let res = _1n3; + while (power > _0n3) { + if (power & _1n3) + res = res * num2 % modulo; + num2 = num2 * num2 % modulo; + power >>= _1n3; + } + return res; +} +function pow2(x2, power, modulo) { + let res = x2; + while (power-- > _0n3) { + res *= res; + res %= modulo; + } + return res; +} +function invert(number, modulo) { + if (number === _0n3) + throw new Error("invert: expected non-zero number"); + if (modulo <= _0n3) + throw new Error("invert: expected positive modulus, got " + modulo); + let a = mod(number, modulo); + let b2 = modulo; + let x2 = _0n3, y2 = _1n3, u = _1n3, v = _0n3; + while (a !== _0n3) { + const q2 = b2 / a; + const r = b2 % a; + const m2 = x2 - u * q2; + const n = y2 - v * q2; + b2 = a, a = r, x2 = u, y2 = v, u = m2, v = n; + } + const gcd = b2; + if (gcd !== _1n3) + throw new Error("invert: does not exist"); + return mod(x2, modulo); +} +function tonelliShanks(P2) { + const legendreC = (P2 - _1n3) / _2n3; + let Q, S, Z2; + for (Q = P2 - _1n3, S = 0; Q % _2n3 === _0n3; Q /= _2n3, S++) + ; + for (Z2 = _2n3; Z2 < P2 && pow(Z2, legendreC, P2) !== P2 - _1n3; Z2++) { + if (Z2 > 1e3) + throw new Error("Cannot find square root: likely non-prime P"); + } + if (S === 1) { + const p1div4 = (P2 + _1n3) / _4n; + return function tonelliFast(Fp2, n) { + const root = Fp2.pow(n, p1div4); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + const Q1div2 = (Q + _1n3) / _2n3; + return function tonelliSlow(Fp2, n) { + if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) + throw new Error("Cannot find square root"); + let r = S; + let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z2), Q); + let x2 = Fp2.pow(n, Q1div2); + let b2 = Fp2.pow(n, Q); + while (!Fp2.eql(b2, Fp2.ONE)) { + if (Fp2.eql(b2, Fp2.ZERO)) + return Fp2.ZERO; + let m2 = 1; + for (let t2 = Fp2.sqr(b2); m2 < r; m2++) { + if (Fp2.eql(t2, Fp2.ONE)) + break; + t2 = Fp2.sqr(t2); + } + const ge2 = Fp2.pow(g, _1n3 << BigInt(r - m2 - 1)); + g = Fp2.sqr(ge2); + x2 = Fp2.mul(x2, ge2); + b2 = Fp2.mul(b2, g); + r = m2; + } + return x2; + }; +} +function FpSqrt(P2) { + if (P2 % _4n === _3n) { + const p1div4 = (P2 + _1n3) / _4n; + return function sqrt3mod4(Fp2, n) { + const root = Fp2.pow(n, p1div4); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + if (P2 % _8n === _5n) { + const c1 = (P2 - _5n) / _8n; + return function sqrt5mod8(Fp2, n) { + const n2 = Fp2.mul(n, _2n3); + const v = Fp2.pow(n2, c1); + const nv = Fp2.mul(n, v); + const i = Fp2.mul(Fp2.mul(nv, _2n3), v); + const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + if (P2 % _16n === _9n) { + } + return tonelliShanks(P2); +} +function validateField(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "isSafeInteger", + BITS: "isSafeInteger" + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + return validateObject(field, opts); +} +function FpPow(f, num2, power) { + if (power < _0n3) + throw new Error("invalid exponent, negatives unsupported"); + if (power === _0n3) + return f.ONE; + if (power === _1n3) + return num2; + let p = f.ONE; + let d = num2; + while (power > _0n3) { + if (power & _1n3) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n3; + } + return p; +} +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num2, i) => { + if (f.is0(num2)) + return acc; + tmp[i] = acc; + return f.mul(acc, num2); + }, f.ONE); + const inverted = f.inv(lastMultiplied); + nums.reduceRight((acc, num2, i) => { + if (f.is0(num2)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num2); + }, inverted); + return tmp; +} +function nLength(n, nBitLength) { + const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +function Field(ORDER, bitLen2, isLE3 = false, redef = {}) { + if (ORDER <= _0n3) + throw new Error("invalid field: expected ORDER > 0, got " + ORDER); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); + if (BYTES > 2048) + throw new Error("invalid field: expected ORDER of <= 2048 bytes"); + let sqrtP; + const f = Object.freeze({ + ORDER, + isLE: isLE3, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n3, + ONE: _1n3, + create: (num2) => mod(num2, ORDER), + isValid: (num2) => { + if (typeof num2 !== "bigint") + throw new Error("invalid field element: expected bigint, got " + typeof num2); + return _0n3 <= num2 && num2 < ORDER; + }, + is0: (num2) => num2 === _0n3, + isOdd: (num2) => (num2 & _1n3) === _1n3, + neg: (num2) => mod(-num2, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num2) => mod(num2 * num2, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num2, power) => FpPow(f, num2, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num2) => num2 * num2, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num2) => invert(num2, ORDER), + sqrt: redef.sqrt || ((n) => { + if (!sqrtP) + sqrtP = FpSqrt(ORDER); + return sqrtP(f, n); + }), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b2, c) => c ? b2 : a, + toBytes: (num2) => isLE3 ? numberToBytesLE(num2, BYTES) : numberToBytesBE(num2, BYTES), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); + return isLE3 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + } + }); + return Object.freeze(f); +} +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== "bigint") + throw new Error("field order must be bigint"); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +function mapHashToField(key, fieldOrder, isLE3 = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + if (len < 16 || len < minLen || len > 1024) + throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); + const num2 = isLE3 ? bytesToNumberLE(key) : bytesToNumberBE(key); + const reduced = mod(num2, fieldOrder - _1n3) + _1n3; + return isLE3 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} +var _0n3, _1n3, _2n3, _3n, _4n, _5n, _8n, _9n, _16n, FIELD_FIELDS; +var init_modular = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/abstract/modular.js"() { + init_utils4(); + _0n3 = BigInt(0); + _1n3 = BigInt(1); + _2n3 = /* @__PURE__ */ BigInt(2); + _3n = /* @__PURE__ */ BigInt(3); + _4n = /* @__PURE__ */ BigInt(4); + _5n = /* @__PURE__ */ BigInt(5); + _8n = /* @__PURE__ */ BigInt(8); + _9n = /* @__PURE__ */ BigInt(9); + _16n = /* @__PURE__ */ BigInt(16); + FIELD_FIELDS = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" + ]; + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/abstract/curve.js +function constTimeNegate(condition, item) { + const neg = item.negate(); + return condition ? neg : item; +} +function validateW(W2, bits) { + if (!Number.isSafeInteger(W2) || W2 <= 0 || W2 > bits) + throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W2); +} +function calcWOpts(W2, bits) { + validateW(W2, bits); + const windows = Math.ceil(bits / W2) + 1; + const windowSize = 2 ** (W2 - 1); + return { windows, windowSize }; +} +function validateMSMPoints(points, c) { + if (!Array.isArray(points)) + throw new Error("array expected"); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error("invalid point at index " + i); + }); +} +function validateMSMScalars(scalars, field) { + if (!Array.isArray(scalars)) + throw new Error("array of scalars expected"); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error("invalid scalar at index " + i); + }); +} +function getW(P2) { + return pointWindowSizes.get(P2) || 1; +} +function wNAF(c, bits) { + return { + constTimeNegate, + hasPrecomputes(elm) { + return getW(elm) !== 1; + }, + // non-const time multiplication ladder + unsafeLadder(elm, n, p = c.ZERO) { + let d = elm; + while (n > _0n4) { + if (n & _1n4) + p = p.add(d); + d = d.double(); + n >>= _1n4; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @param elm Point instance + * @param W window size + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W2) { + const { windows, windowSize } = calcWOpts(W2, bits); + const points = []; + let p = elm; + let base = p; + for (let window2 = 0; window2 < windows; window2++) { + base = p; + points.push(base); + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W2, precomputes, n) { + const { windows, windowSize } = calcWOpts(W2, bits); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W2 - 1); + const maxNumber = 2 ** W2; + const shiftBy = BigInt(W2); + for (let window2 = 0; window2 < windows; window2++) { + const offset = window2 * windowSize; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n4; + } + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; + const cond1 = window2 % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + return { p, f }; + }, + /** + * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @param acc accumulator point to add result of multiplication + * @returns point + */ + wNAFUnsafe(W2, precomputes, n, acc = c.ZERO) { + const { windows, windowSize } = calcWOpts(W2, bits); + const mask = BigInt(2 ** W2 - 1); + const maxNumber = 2 ** W2; + const shiftBy = BigInt(W2); + for (let window2 = 0; window2 < windows; window2++) { + const offset = window2 * windowSize; + if (n === _0n4) + break; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n4; + } + if (wbits === 0) + continue; + let curr = precomputes[offset + Math.abs(wbits) - 1]; + if (wbits < 0) + curr = curr.negate(); + acc = acc.add(curr); + } + return acc; + }, + getPrecomputes(W2, P2, transform) { + let comp = pointPrecomputes.get(P2); + if (!comp) { + comp = this.precomputeWindow(P2, W2); + if (W2 !== 1) + pointPrecomputes.set(P2, transform(comp)); + } + return comp; + }, + wNAFCached(P2, n, transform) { + const W2 = getW(P2); + return this.wNAF(W2, this.getPrecomputes(W2, P2, transform), n); + }, + wNAFCachedUnsafe(P2, n, transform, prev) { + const W2 = getW(P2); + if (W2 === 1) + return this.unsafeLadder(P2, n, prev); + return this.wNAFUnsafe(W2, this.getPrecomputes(W2, P2, transform), n, prev); + }, + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + setWindowSize(P2, W2) { + validateW(W2, bits); + pointWindowSizes.set(P2, W2); + pointPrecomputes.delete(P2); + } + }; +} +function pippenger(c, fieldN, points, scalars) { + validateMSMPoints(points, c); + validateMSMScalars(scalars, fieldN); + if (points.length !== scalars.length) + throw new Error("arrays of points and scalars must have equal length"); + const zero = c.ZERO; + const wbits = bitLen(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(zero); + const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; + let sum = zero; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(zero); + for (let j2 = 0; j2 < scalars.length; j2++) { + const scalar = scalars[j2]; + const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK)); + buckets[wbits2] = buckets[wbits2].add(points[j2]); + } + let resI = zero; + for (let j2 = buckets.length - 1, sumI = zero; j2 > 0; j2--) { + sumI = sumI.add(buckets[j2]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) + for (let j2 = 0; j2 < windowSize; j2++) + sum = sum.double(); + } + return sum; +} +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: "bigint", + h: "bigint", + Gx: "field", + Gy: "field" + }, { + nBitLength: "isSafeInteger", + nByteLength: "isSafeInteger" + }); + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER } + }); +} +var _0n4, _1n4, pointPrecomputes, pointWindowSizes; +var init_curve = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/abstract/curve.js"() { + init_modular(); + init_utils4(); + _0n4 = BigInt(0); + _1n4 = BigInt(1); + pointPrecomputes = /* @__PURE__ */ new WeakMap(); + pointWindowSizes = /* @__PURE__ */ new WeakMap(); + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/abstract/weierstrass.js +function validateSigVerOpts(opts) { + if (opts.lowS !== void 0) + abool("lowS", opts.lowS); + if (opts.prehash !== void 0) + abool("prehash", opts.prehash); +} +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: "field", + b: "field" + }, { + allowedPrivateKeyLengths: "array", + wrapPrivateKey: "boolean", + isTorsionFree: "function", + clearCofactor: "function", + allowInfinityPoint: "boolean", + fromBytes: "function", + toBytes: "function" + }); + const { endo, Fp: Fp2, a } = opts; + if (endo) { + if (!Fp2.eql(a, Fp2.ZERO)) { + throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0"); + } + if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { + throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function"); + } + } + return Object.freeze({ ...opts }); +} +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp: Fp2 } = CURVE; + const Fn2 = Field(CURVE.n, CURVE.nBitLength); + const toBytes4 = CURVE.toBytes || ((_c2, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes3(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); + }); + const fromBytes2 = CURVE.fromBytes || ((bytes) => { + const tail = bytes.subarray(1); + const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x: x2, y: y2 }; + }); + function weierstrassEquation(x2) { + const { a, b: b2 } = CURVE; + const x22 = Fp2.sqr(x2); + const x3 = Fp2.mul(x22, x2); + return Fp2.add(Fp2.add(x3, Fp2.mul(x2, a)), b2); + } + if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error("bad generator point: equation left != right"); + function isWithinCurveOrder(num2) { + return inRange(num2, _1n5, CURVE.n); + } + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N2 } = CURVE; + if (lengths && typeof key !== "bigint") { + if (isBytes2(key)) + key = bytesToHex2(key); + if (typeof key !== "string" || !lengths.includes(key.length)) + throw new Error("invalid private key"); + key = key.padStart(nByteLength * 2, "0"); + } + let num2; + try { + num2 = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); + } catch (error) { + throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key); + } + if (wrapPrivateKey) + num2 = mod(num2, N2); + aInRange("private key", num2, _1n5, N2); + return num2; + } + function assertPrjPoint(other) { + if (!(other instanceof Point2)) + throw new Error("ProjectivePoint expected"); + } + const toAffineMemo = memoized((p, iz) => { + const { px: x2, py: y2, pz: z } = p; + if (Fp2.eql(z, Fp2.ONE)) + return { x: x2, y: y2 }; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? Fp2.ONE : Fp2.inv(z); + const ax = Fp2.mul(x2, iz); + const ay = Fp2.mul(y2, iz); + const zz = Fp2.mul(z, iz); + if (is0) + return { x: Fp2.ZERO, y: Fp2.ZERO }; + if (!Fp2.eql(zz, Fp2.ONE)) + throw new Error("invZ was invalid"); + return { x: ax, y: ay }; + }); + const assertValidMemo = memoized((p) => { + if (p.is0()) { + if (CURVE.allowInfinityPoint && !Fp2.is0(p.py)) + return; + throw new Error("bad point: ZERO"); + } + const { x: x2, y: y2 } = p.toAffine(); + if (!Fp2.isValid(x2) || !Fp2.isValid(y2)) + throw new Error("bad point: x or y not FE"); + const left = Fp2.sqr(y2); + const right = weierstrassEquation(x2); + if (!Fp2.eql(left, right)) + throw new Error("bad point: equation left != right"); + if (!p.isTorsionFree()) + throw new Error("bad point: not in prime-order subgroup"); + return true; + }); + class Point2 { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp2.isValid(px)) + throw new Error("x required"); + if (py == null || !Fp2.isValid(py)) + throw new Error("y required"); + if (pz == null || !Fp2.isValid(pz)) + throw new Error("z required"); + Object.freeze(this); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x: x2, y: y2 } = p || {}; + if (!p || !Fp2.isValid(x2) || !Fp2.isValid(y2)) + throw new Error("invalid affine point"); + if (p instanceof Point2) + throw new Error("projective point not allowed"); + const is0 = (i) => Fp2.eql(i, Fp2.ZERO); + if (is0(x2) && is0(y2)) + return Point2.ZERO; + return new Point2(x2, y2, Fp2.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp2.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P2 = Point2.fromAffine(fromBytes2(ensureBytes("pointHex", hex))); + P2.assertValidity(); + return P2; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point2, Fn2, points, scalars); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y: y2 } = this.toAffine(); + if (Fp2.isOdd) + return !Fp2.isOdd(y2); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); + const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point2(this.px, Fp2.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b: b2 } = CURVE; + const b3 = Fp2.mul(b2, _3n2); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + let t0 = Fp2.mul(X1, X1); + let t1 = Fp2.mul(Y1, Y1); + let t2 = Fp2.mul(Z1, Z1); + let t3 = Fp2.mul(X1, Y1); + t3 = Fp2.add(t3, t3); + Z3 = Fp2.mul(X1, Z1); + Z3 = Fp2.add(Z3, Z3); + X3 = Fp2.mul(a, Z3); + Y3 = Fp2.mul(b3, t2); + Y3 = Fp2.add(X3, Y3); + X3 = Fp2.sub(t1, Y3); + Y3 = Fp2.add(t1, Y3); + Y3 = Fp2.mul(X3, Y3); + X3 = Fp2.mul(t3, X3); + Z3 = Fp2.mul(b3, Z3); + t2 = Fp2.mul(a, t2); + t3 = Fp2.sub(t0, t2); + t3 = Fp2.mul(a, t3); + t3 = Fp2.add(t3, Z3); + Z3 = Fp2.add(t0, t0); + t0 = Fp2.add(Z3, t0); + t0 = Fp2.add(t0, t2); + t0 = Fp2.mul(t0, t3); + Y3 = Fp2.add(Y3, t0); + t2 = Fp2.mul(Y1, Z1); + t2 = Fp2.add(t2, t2); + t0 = Fp2.mul(t2, t3); + X3 = Fp2.sub(X3, t0); + Z3 = Fp2.mul(t2, t1); + Z3 = Fp2.add(Z3, Z3); + Z3 = Fp2.add(Z3, Z3); + return new Point2(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + const a = CURVE.a; + const b3 = Fp2.mul(CURVE.b, _3n2); + let t0 = Fp2.mul(X1, X2); + let t1 = Fp2.mul(Y1, Y2); + let t2 = Fp2.mul(Z1, Z2); + let t3 = Fp2.add(X1, Y1); + let t4 = Fp2.add(X2, Y2); + t3 = Fp2.mul(t3, t4); + t4 = Fp2.add(t0, t1); + t3 = Fp2.sub(t3, t4); + t4 = Fp2.add(X1, Z1); + let t5 = Fp2.add(X2, Z2); + t4 = Fp2.mul(t4, t5); + t5 = Fp2.add(t0, t2); + t4 = Fp2.sub(t4, t5); + t5 = Fp2.add(Y1, Z1); + X3 = Fp2.add(Y2, Z2); + t5 = Fp2.mul(t5, X3); + X3 = Fp2.add(t1, t2); + t5 = Fp2.sub(t5, X3); + Z3 = Fp2.mul(a, t4); + X3 = Fp2.mul(b3, t2); + Z3 = Fp2.add(X3, Z3); + X3 = Fp2.sub(t1, Z3); + Z3 = Fp2.add(t1, Z3); + Y3 = Fp2.mul(X3, Z3); + t1 = Fp2.add(t0, t0); + t1 = Fp2.add(t1, t0); + t2 = Fp2.mul(a, t2); + t4 = Fp2.mul(b3, t4); + t1 = Fp2.add(t1, t2); + t2 = Fp2.sub(t0, t2); + t2 = Fp2.mul(a, t2); + t4 = Fp2.add(t4, t2); + t0 = Fp2.mul(t1, t4); + Y3 = Fp2.add(Y3, t0); + t0 = Fp2.mul(t5, t4); + X3 = Fp2.mul(t3, X3); + X3 = Fp2.sub(X3, t0); + t0 = Fp2.mul(t3, t1); + Z3 = Fp2.mul(t5, Z3); + Z3 = Fp2.add(Z3, t0); + return new Point2(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point2.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point2.normalizeZ); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc2) { + const { endo, n: N2 } = CURVE; + aInRange("scalar", sc2, _0n5, N2); + const I2 = Point2.ZERO; + if (sc2 === _0n5) + return I2; + if (this.is0() || sc2 === _1n5) + return this; + if (!endo || wnaf.hasPrecomputes(this)) + return wnaf.wNAFCachedUnsafe(this, sc2, Point2.normalizeZ); + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc2); + let k1p = I2; + let k2p = I2; + let d = this; + while (k1 > _0n5 || k2 > _0n5) { + if (k1 & _1n5) + k1p = k1p.add(d); + if (k2 & _1n5) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n5; + k2 >>= _1n5; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + const { endo, n: N2 } = CURVE; + aInRange("scalar", scalar, _1n5, N2); + let point, fake; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; + } + return Point2.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b2) { + const G2 = Point2.BASE; + const mul = (P2, a2) => a2 === _0n5 || a2 === _1n5 || !P2.equals(G2) ? P2.multiplyUnsafe(a2) : P2.multiply(a2); + const sum = mul(this, a).add(mul(Q, b2)); + return sum.is0() ? void 0 : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + return toAffineMemo(this, iz); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n5) + return true; + if (isTorsionFree) + return isTorsionFree(Point2, this); + throw new Error("isTorsionFree() has not been declared for the elliptic curve"); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n5) + return this; + if (clearCofactor) + return clearCofactor(Point2, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + abool("isCompressed", isCompressed); + this.assertValidity(); + return toBytes4(Point2, this, isCompressed); + } + toHex(isCompressed = true) { + abool("isCompressed", isCompressed); + return bytesToHex2(this.toRawBytes(isCompressed)); + } + } + Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE); + Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + return { + CURVE, + ProjectivePoint: Point2, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder + }; +} +function validateOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: "hash", + hmac: "function", + randomBytes: "function" + }, { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean" + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp: Fp2, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp2.BYTES + 1; + const uncompressedLen = 2 * Fp2.BYTES + 1; + function modN2(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ + ...CURVE, + toBytes(_c2, point, isCompressed) { + const a = point.toAffine(); + const x2 = Fp2.toBytes(a.x); + const cat = concatBytes3; + abool("isCompressed", isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x2); + } else { + return cat(Uint8Array.from([4]), x2, Fp2.toBytes(a.y)); + } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + if (len === compressedLen && (head === 2 || head === 3)) { + const x2 = bytesToNumberBE(tail); + if (!inRange(x2, _1n5, Fp2.ORDER)) + throw new Error("Point is not on curve"); + const y2 = weierstrassEquation(x2); + let y3; + try { + y3 = Fp2.sqrt(y2); + } catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : ""; + throw new Error("Point is not on curve" + suffix); + } + const isYOdd = (y3 & _1n5) === _1n5; + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y3 = Fp2.neg(y3); + return { x: x2, y: y3 }; + } else if (len === uncompressedLen && head === 4) { + const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x: x2, y: y2 }; + } else { + const cl2 = compressedLen; + const ul2 = uncompressedLen; + throw new Error("invalid Point, expected length of " + cl2 + ", or uncompressed " + ul2 + ", got " + len); + } + } + }); + const numToNByteStr = (num2) => bytesToHex2(numberToBytesBE(num2, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n5; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN2(-s) : s; + } + const slcNum = (b2, from5, to2) => bytesToNumberBE(b2.slice(from5, to2)); + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes("compactSignature", hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes("DER", hex)); + return new Signature(r, s); + } + assertValidity() { + aInRange("r", this.r, _1n5, CURVE_ORDER); + aInRange("s", this.s, _1n5, CURVE_ORDER); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes("msgHash", msgHash)); + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error("recovery id invalid"); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp2.ORDER) + throw new Error("recovery id 2 or 3 invalid"); + const prefix = (rec & 1) === 0 ? "02" : "03"; + const R2 = Point2.fromHex(prefix + numToNByteStr(radj)); + const ir2 = invN(radj); + const u1 = modN2(-h * ir2); + const u2 = modN2(s * ir2); + const Q = Point2.BASE.multiplyAndAddUnsafe(R2, u1, u2); + if (!Q) + throw new Error("point at infinify"); + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return hexToBytes2(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes2(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } + }, + normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point2.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + } + }; + function getPublicKey(privateKey, isCompressed = true) { + return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + function isProbPub(item) { + const arr = isBytes2(item); + const str = typeof item === "string"; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point2) + return true; + return false; + } + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error("first arg must be private key"); + if (!isProbPub(publicB)) + throw new Error("second arg must be public key"); + const b2 = Point2.fromHex(publicB); + return b2.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + const bits2int = CURVE.bits2int || function(bytes) { + if (bytes.length > 8192) + throw new Error("input is too large"); + const num2 = bytesToNumberBE(bytes); + const delta = bytes.length * 8 - CURVE.nBitLength; + return delta > 0 ? num2 >> BigInt(delta) : num2; + }; + const bits2int_modN = CURVE.bits2int_modN || function(bytes) { + return modN2(bits2int(bytes)); + }; + const ORDER_MASK = bitMask(CURVE.nBitLength); + function int2octets(num2) { + aInRange("num < 2^" + CURVE.nBitLength, num2, _0n5, ORDER_MASK); + return numberToBytesBE(num2, CURVE.nByteLength); + } + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (["recovered", "canonical"].some((k2) => k2 in opts)) + throw new Error("sign() legacy options not supported"); + const { hash: hash2, randomBytes: randomBytes2 } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; + if (lowS == null) + lowS = true; + msgHash = ensureBytes("msgHash", msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); + const seedArgs = [int2octets(d), int2octets(h1int)]; + if (ent != null && ent !== false) { + const e = ent === true ? randomBytes2(Fp2.BYTES) : ent; + seedArgs.push(ensureBytes("extraEntropy", e)); + } + const seed = concatBytes3(...seedArgs); + const m2 = h1int; + function k2sig(kBytes) { + const k2 = bits2int(kBytes); + if (!isWithinCurveOrder(k2)) + return; + const ik = invN(k2); + const q2 = Point2.BASE.multiply(k2).toAffine(); + const r = modN2(q2.x); + if (r === _0n5) + return; + const s = modN2(ik * modN2(m2 + r * d)); + if (s === _0n5) + return; + let recovery = (q2.x === r ? 0 : 2) | Number(q2.y & _1n5); + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); + recovery ^= 1; + } + return new Signature(r, normS, recovery); + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + function sign2(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); + } + Point2.BASE._setWindowSize(8); + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes("msgHash", msgHash); + publicKey = ensureBytes("publicKey", publicKey); + const { lowS, prehash, format } = opts; + validateSigVerOpts(opts); + if ("strict" in opts) + throw new Error("options.strict was renamed to lowS"); + if (format !== void 0 && format !== "compact" && format !== "der") + throw new Error("format must be compact or der"); + const isHex2 = typeof sg === "string" || isBytes2(sg); + const isObj = !isHex2 && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint"; + if (!isHex2 && !isObj) + throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance"); + let _sig = void 0; + let P2; + try { + if (isObj) + _sig = new Signature(sg.r, sg.s); + if (isHex2) { + try { + if (format !== "compact") + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + } + if (!_sig && format !== "der") + _sig = Signature.fromCompact(sg); + } + P2 = Point2.fromHex(publicKey); + } catch (error) { + return false; + } + if (!_sig) + return false; + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); + const is2 = invN(s); + const u1 = modN2(h * is2); + const u2 = modN2(r * is2); + const R2 = Point2.BASE.multiplyAndAddUnsafe(P2, u1, u2)?.toAffine(); + if (!R2) + return false; + const v = modN2(R2.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign: sign2, + verify, + ProjectivePoint: Point2, + Signature, + utils + }; +} +function SWUFpSqrtRatio(Fp2, Z2) { + const q2 = Fp2.ORDER; + let l = _0n5; + for (let o = q2 - _1n5; o % _2n4 === _0n5; o /= _2n4) + l += _1n5; + const c1 = l; + const _2n_pow_c1_1 = _2n4 << c1 - _1n5 - _1n5; + const _2n_pow_c1 = _2n_pow_c1_1 * _2n4; + const c2 = (q2 - _1n5) / _2n_pow_c1; + const c3 = (c2 - _1n5) / _2n4; + const c4 = _2n_pow_c1 - _1n5; + const c5 = _2n_pow_c1_1; + const c6 = Fp2.pow(Z2, c2); + const c7 = Fp2.pow(Z2, (c2 + _1n5) / _2n4); + let sqrtRatio = (u, v) => { + let tv1 = c6; + let tv2 = Fp2.pow(v, c4); + let tv3 = Fp2.sqr(tv2); + tv3 = Fp2.mul(tv3, v); + let tv5 = Fp2.mul(u, tv3); + tv5 = Fp2.pow(tv5, c3); + tv5 = Fp2.mul(tv5, tv2); + tv2 = Fp2.mul(tv5, v); + tv3 = Fp2.mul(tv5, u); + let tv4 = Fp2.mul(tv3, tv2); + tv5 = Fp2.pow(tv4, c5); + let isQR = Fp2.eql(tv5, Fp2.ONE); + tv2 = Fp2.mul(tv3, c7); + tv5 = Fp2.mul(tv4, tv1); + tv3 = Fp2.cmov(tv2, tv3, isQR); + tv4 = Fp2.cmov(tv5, tv4, isQR); + for (let i = c1; i > _1n5; i--) { + let tv52 = i - _2n4; + tv52 = _2n4 << tv52 - _1n5; + let tvv5 = Fp2.pow(tv4, tv52); + const e1 = Fp2.eql(tvv5, Fp2.ONE); + tv2 = Fp2.mul(tv3, tv1); + tv1 = Fp2.mul(tv1, tv1); + tvv5 = Fp2.mul(tv4, tv1); + tv3 = Fp2.cmov(tv2, tv3, e1); + tv4 = Fp2.cmov(tvv5, tv4, e1); + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp2.ORDER % _4n2 === _3n2) { + const c12 = (Fp2.ORDER - _3n2) / _4n2; + const c22 = Fp2.sqrt(Fp2.neg(Z2)); + sqrtRatio = (u, v) => { + let tv1 = Fp2.sqr(v); + const tv2 = Fp2.mul(u, v); + tv1 = Fp2.mul(tv1, tv2); + let y1 = Fp2.pow(tv1, c12); + y1 = Fp2.mul(y1, tv2); + const y2 = Fp2.mul(y1, c22); + const tv3 = Fp2.mul(Fp2.sqr(y1), v); + const isQR = Fp2.eql(tv3, u); + let y3 = Fp2.cmov(y2, y1, isQR); + return { isValid: isQR, value: y3 }; + }; + } + return sqrtRatio; +} +function mapToCurveSimpleSWU(Fp2, opts) { + validateField(Fp2); + if (!Fp2.isValid(opts.A) || !Fp2.isValid(opts.B) || !Fp2.isValid(opts.Z)) + throw new Error("mapToCurveSimpleSWU: invalid opts"); + const sqrtRatio = SWUFpSqrtRatio(Fp2, opts.Z); + if (!Fp2.isOdd) + throw new Error("Fp.isOdd is not implemented!"); + return (u) => { + let tv1, tv2, tv3, tv4, tv5, tv6, x2, y2; + tv1 = Fp2.sqr(u); + tv1 = Fp2.mul(tv1, opts.Z); + tv2 = Fp2.sqr(tv1); + tv2 = Fp2.add(tv2, tv1); + tv3 = Fp2.add(tv2, Fp2.ONE); + tv3 = Fp2.mul(tv3, opts.B); + tv4 = Fp2.cmov(opts.Z, Fp2.neg(tv2), !Fp2.eql(tv2, Fp2.ZERO)); + tv4 = Fp2.mul(tv4, opts.A); + tv2 = Fp2.sqr(tv3); + tv6 = Fp2.sqr(tv4); + tv5 = Fp2.mul(tv6, opts.A); + tv2 = Fp2.add(tv2, tv5); + tv2 = Fp2.mul(tv2, tv3); + tv6 = Fp2.mul(tv6, tv4); + tv5 = Fp2.mul(tv6, opts.B); + tv2 = Fp2.add(tv2, tv5); + x2 = Fp2.mul(tv1, tv3); + const { isValid, value } = sqrtRatio(tv2, tv6); + y2 = Fp2.mul(tv1, u); + y2 = Fp2.mul(y2, value); + x2 = Fp2.cmov(x2, tv3, isValid); + y2 = Fp2.cmov(y2, value, isValid); + const e1 = Fp2.isOdd(u) === Fp2.isOdd(y2); + y2 = Fp2.cmov(Fp2.neg(y2), y2, e1); + x2 = Fp2.div(x2, tv4); + return { x: x2, y: y2 }; + }; +} +var b2n, h2b, DERErr, DER, _0n5, _1n5, _2n4, _3n2, _4n2; +var init_weierstrass = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/abstract/weierstrass.js"() { + init_curve(); + init_modular(); + init_utils4(); + init_utils4(); + ({ bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports2); + DERErr = class extends Error { + constructor(m2 = "") { + super(m2); + } + }; + DER = { + // asn.1 DER encoding utils + Err: DERErr, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + if (tag < 0 || tag > 256) + throw new E("tlv.encode: wrong tag"); + if (data.length & 1) + throw new E("tlv.encode: unpadded data"); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if (len.length / 2 & 128) + throw new E("tlv.encode: long form length too big"); + const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; + const t = numberToHexUnpadded(tag); + return t + lenLen + len + data; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER; + let pos = 0; + if (tag < 0 || tag > 256) + throw new E("tlv.encode: wrong tag"); + if (data.length < 2 || data[pos++] !== tag) + throw new E("tlv.decode: wrong tlv"); + const first = data[pos++]; + const isLong = !!(first & 128); + let length = 0; + if (!isLong) + length = first; + else { + const lenLen = first & 127; + if (!lenLen) + throw new E("tlv.decode(long): indefinite length not supported"); + if (lenLen > 4) + throw new E("tlv.decode(long): byte length is too big"); + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E("tlv.decode: length bytes not complete"); + if (lengthBytes[0] === 0) + throw new E("tlv.decode(long): zero leftmost byte"); + for (const b2 of lengthBytes) + length = length << 8 | b2; + pos += lenLen; + if (length < 128) + throw new E("tlv.decode(long): not minimal encoding"); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E("tlv.decode: wrong value length"); + return { v, l: data.subarray(pos + length) }; + } + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num2) { + const { Err: E } = DER; + if (num2 < _0n5) + throw new E("integer: negative integers are not allowed"); + let hex = numberToHexUnpadded(num2); + if (Number.parseInt(hex[0], 16) & 8) + hex = "00" + hex; + if (hex.length & 1) + throw new E("unexpected DER parsing assertion: unpadded hex"); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data[0] & 128) + throw new E("invalid signature integer: negative"); + if (data[0] === 0 && !(data[1] & 128)) + throw new E("invalid signature integer: unnecessary leading zero"); + return b2n(data); + } + }, + toSig(hex) { + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = typeof hex === "string" ? h2b(hex) : hex; + abytes2(data); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); + if (seqLeftBytes.length) + throw new E("invalid signature: left bytes after parsing"); + const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); + if (sLeftBytes.length) + throw new E("invalid signature: left bytes after parsing"); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const rs2 = tlv.encode(2, int.encode(sig.r)); + const ss = tlv.encode(2, int.encode(sig.s)); + const seq = rs2 + ss; + return tlv.encode(48, seq); + } + }; + _0n5 = BigInt(0); + _1n5 = BigInt(1); + _2n4 = BigInt(2); + _3n2 = BigInt(3); + _4n2 = BigInt(4); + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/_shortw_utils.js +function getHash(hash2) { + return { + hash: hash2, + hmac: (key, ...msgs) => hmac(hash2, key, concatBytes(...msgs)), + randomBytes + }; +} +function createCurve(curveDef, defHash) { + const create = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) }); + return { ...create(defHash), create }; +} +var init_shortw_utils = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/_shortw_utils.js"() { + init_hmac(); + init_utils2(); + init_weierstrass(); + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/abstract/hash-to-curve.js +function i2osp(value, length) { + anum(value); + anum(length); + if (value < 0 || value >= 1 << 8 * length) + throw new Error("invalid I2OSP input: " + value); + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 255; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b2) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b2[i]; + } + return arr; +} +function anum(item) { + if (!Number.isSafeInteger(item)) + throw new Error("number expected"); +} +function expand_message_xmd(msg, DST, lenInBytes, H2) { + abytes2(msg); + abytes2(DST); + anum(lenInBytes); + if (DST.length > 255) + DST = H2(concatBytes3(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H2; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (lenInBytes > 65535 || ell > 255) + throw new Error("expand_message_xmd: invalid lenInBytes"); + const DST_prime = concatBytes3(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); + const b2 = new Array(ell); + const b_0 = H2(concatBytes3(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b2[0] = H2(concatBytes3(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b2[i - 1]), i2osp(i + 1, 1), DST_prime]; + b2[i] = H2(concatBytes3(...args)); + } + const pseudo_random_bytes = concatBytes3(...b2); + return pseudo_random_bytes.slice(0, lenInBytes); +} +function expand_message_xof(msg, DST, lenInBytes, k2, H2) { + abytes2(msg); + abytes2(DST); + anum(lenInBytes); + if (DST.length > 255) { + const dkLen = Math.ceil(2 * k2 / 8); + DST = H2.create({ dkLen }).update(utf8ToBytes2("H2C-OVERSIZE-DST-")).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error("expand_message_xof: invalid lenInBytes"); + return H2.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); +} +function hash_to_field(msg, count, options) { + validateObject(options, { + DST: "stringOrUint8Array", + p: "bigint", + m: "isSafeInteger", + k: "isSafeInteger", + hash: "hash" + }); + const { p, k: k2, m: m2, hash: hash2, expand, DST: _DST } = options; + abytes2(msg); + anum(count); + const DST = typeof _DST === "string" ? utf8ToBytes2(_DST) : _DST; + const log2p = p.toString(2).length; + const L2 = Math.ceil((log2p + k2) / 8); + const len_in_bytes = count * m2 * L2; + let prb; + if (expand === "xmd") { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash2); + } else if (expand === "xof") { + prb = expand_message_xof(msg, DST, len_in_bytes, k2, hash2); + } else if (expand === "_internal_pass") { + prb = msg; + } else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m2); + for (let j2 = 0; j2 < m2; j2++) { + const elm_offset = L2 * (j2 + i * m2); + const tv = prb.subarray(elm_offset, elm_offset + L2); + e[j2] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +function isogenyMap(field, map) { + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x2, y2) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x2), i))); + x2 = field.div(xNum, xDen); + y2 = field.mul(y2, field.div(yNum, yDen)); + return { x: x2, y: y2 }; + }; +} +function createHasher(Point2, mapToCurve, def) { + if (typeof mapToCurve !== "function") + throw new Error("mapToCurve() must be defined"); + return { + // Encodes byte string to elliptic curve. + // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point2.fromAffine(mapToCurve(u[0])); + const u1 = Point2.fromAffine(mapToCurve(u[1])); + const P2 = u0.add(u1).clearCofactor(); + P2.assertValidity(); + return P2; + }, + // Encodes byte string to elliptic curve. + // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P2 = Point2.fromAffine(mapToCurve(u[0])).clearCofactor(); + P2.assertValidity(); + return P2; + }, + // Same as encodeToCurve, but without hash + mapToCurve(scalars) { + if (!Array.isArray(scalars)) + throw new Error("mapToCurve: expected array of bigints"); + for (const i of scalars) + if (typeof i !== "bigint") + throw new Error("mapToCurve: expected array of bigints"); + const P2 = Point2.fromAffine(mapToCurve(scalars)).clearCofactor(); + P2.assertValidity(); + return P2; + } + }; +} +var os2ip; +var init_hash_to_curve = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/abstract/hash-to-curve.js"() { + init_modular(); + init_utils4(); + os2ip = bytesToNumberBE; + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/secp256k1.js +var secp256k1_exports = {}; +__export(secp256k1_exports, { + encodeToCurve: () => encodeToCurve, + hashToCurve: () => hashToCurve, + schnorr: () => schnorr, + secp256k1: () => secp256k1 +}); +function sqrtMod(y2) { + const P2 = secp256k1P; + const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = y2 * y2 * y2 % P2; + const b3 = b2 * b2 * y2 % P2; + const b6 = pow2(b3, _3n3, P2) * b3 % P2; + const b9 = pow2(b6, _3n3, P2) * b3 % P2; + const b11 = pow2(b9, _2n5, P2) * b2 % P2; + const b22 = pow2(b11, _11n, P2) * b11 % P2; + const b44 = pow2(b22, _22n, P2) * b22 % P2; + const b88 = pow2(b44, _44n, P2) * b44 % P2; + const b176 = pow2(b88, _88n, P2) * b88 % P2; + const b220 = pow2(b176, _44n, P2) * b44 % P2; + const b223 = pow2(b220, _3n3, P2) * b3 % P2; + const t1 = pow2(b223, _23n, P2) * b22 % P2; + const t2 = pow2(t1, _6n, P2) * b2 % P2; + const root = pow2(t2, _2n5, P2); + if (!Fpk1.eql(Fpk1.sqr(root), y2)) + throw new Error("Cannot find square root"); + return root; +} +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === void 0) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes3(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes3(tagP, ...messages)); +} +function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); + let p = Point.fromPrivateKey(d_); + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar, bytes: pointToBytes(p) }; +} +function lift_x(x2) { + aInRange("x", x2, _1n6, secp256k1P); + const xx = modP(x2 * x2); + const c = modP(xx * x2 + BigInt(7)); + let y2 = sqrtMod(c); + if (y2 % _2n5 !== _0n6) + y2 = modP(-y2); + const p = new Point(x2, y2, _1n6); + p.assertValidity(); + return p; +} +function challenge(...args) { + return modN(num(taggedHash("BIP0340/challenge", ...args))); +} +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; +} +function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m2 = ensureBytes("message", message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); + const a = ensureBytes("auxRand", auxRand, 32); + const t = numTo32b(d ^ num(taggedHash("BIP0340/aux", a))); + const rand = taggedHash("BIP0340/nonce", t, px, m2); + const k_ = modN(num(rand)); + if (k_ === _0n6) + throw new Error("sign failed: k is zero"); + const { bytes: rx, scalar: k2 } = schnorrGetExtPubKey(k_); + const e = challenge(rx, px, m2); + const sig = new Uint8Array(64); + sig.set(rx, 0); + sig.set(numTo32b(modN(k2 + e * d)), 32); + if (!schnorrVerify(sig, m2, px)) + throw new Error("sign: Invalid signature produced"); + return sig; +} +function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes("signature", signature, 64); + const m2 = ensureBytes("message", message); + const pub = ensureBytes("publicKey", publicKey, 32); + try { + const P2 = lift_x(num(pub)); + const r = num(sig.subarray(0, 32)); + if (!inRange(r, _1n6, secp256k1P)) + return false; + const s = num(sig.subarray(32, 64)); + if (!inRange(s, _1n6, secp256k1N)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P2), m2); + const R2 = GmulAdd(P2, s, modN(-e)); + if (!R2 || !R2.hasEvenY() || R2.toAffine().x !== r) + return false; + return true; + } catch (error) { + return false; + } +} +var secp256k1P, secp256k1N, _1n6, _2n5, divNearest, Fpk1, secp256k1, _0n6, TAGGED_HASH_PREFIXES, pointToBytes, numTo32b, modP, modN, Point, GmulAdd, num, schnorr, isoMap, mapSWU, htf, hashToCurve, encodeToCurve; +var init_secp256k1 = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/secp256k1.js"() { + init_sha256(); + init_utils2(); + init_shortw_utils(); + init_hash_to_curve(); + init_modular(); + init_utils4(); + init_weierstrass(); + secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); + secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); + _1n6 = BigInt(1); + _2n5 = BigInt(2); + divNearest = (a, b2) => (a + b2 / _2n5) / b2; + Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); + secp256k1 = createCurve({ + a: BigInt(0), + // equation params: a, b + b: BigInt(7), + Fp: Fpk1, + // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, + // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), + Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), + h: BigInt(1), + // Cofactor + lowS: true, + // Allow only low-S signatures by default in sign() and verify() + endo: { + // Endomorphism, see above + beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), + splitScalar: (k2) => { + const n = secp256k1N; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n6 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest(b2 * k2, n); + const c2 = divNearest(-b1 * k2, n); + let k1 = mod(k2 - c1 * a1 - c2 * a2, n); + let k22 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k22 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k22 = n - k22; + if (k1 > POW_2_128 || k22 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k2); + } + return { k1neg, k1, k2neg, k2: k22 }; + } + } + }, sha256); + _0n6 = BigInt(0); + TAGGED_HASH_PREFIXES = {}; + pointToBytes = (point) => point.toRawBytes(true).slice(1); + numTo32b = (n) => numberToBytesBE(n, 32); + modP = (x2) => mod(x2, secp256k1P); + modN = (x2) => mod(x2, secp256k1N); + Point = secp256k1.ProjectivePoint; + GmulAdd = (Q, a, b2) => Point.BASE.multiplyAndAddUnsafe(Q, a, b2); + num = bytesToNumberBE; + schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod + } + }))(); + isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [ + // xNum + [ + "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", + "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", + "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", + "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" + ], + // xDen + [ + "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", + "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", + "0x0000000000000000000000000000000000000000000000000000000000000001" + // LAST 1 + ], + // yNum + [ + "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", + "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", + "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", + "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" + ], + // yDen + [ + "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", + "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", + "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", + "0x0000000000000000000000000000000000000000000000000000000000000001" + // LAST 1 + ] + ].map((i) => i.map((j2) => BigInt(j2)))))(); + mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, { + A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), + B: BigInt("1771"), + Z: Fpk1.create(BigInt("-11")) + }))(); + htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { + const { x: x2, y: y2 } = mapSWU(Fpk1.create(scalars[0])); + return isoMap(x2, y2); + }, { + DST: "secp256k1_XMD:SHA-256_SSWU_RO_", + encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", + p: Fpk1.ORDER, + m: 1, + k: 128, + expand: "xmd", + hash: sha256 + }))(); + hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); + encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); + } +}); + +// node_modules/viem/_esm/errors/node.js +var ExecutionRevertedError, FeeCapTooHighError, FeeCapTooLowError, NonceTooHighError, NonceTooLowError, NonceMaxValueError, InsufficientFundsError, IntrinsicGasTooHighError, IntrinsicGasTooLowError, TransactionTypeNotSupportedError, TipAboveFeeCapError, UnknownNodeError; +var init_node = __esm({ + "node_modules/viem/_esm/errors/node.js"() { + init_formatGwei(); + init_base(); + ExecutionRevertedError = class extends BaseError2 { + constructor({ cause, message } = {}) { + const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", ""); + super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, { + cause, + name: "ExecutionRevertedError" + }); + } + }; + Object.defineProperty(ExecutionRevertedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 3 + }); + Object.defineProperty(ExecutionRevertedError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /execution reverted/ + }); + FeeCapTooHighError = class extends BaseError2 { + constructor({ cause, maxFeePerGas } = {}) { + super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, { + cause, + name: "FeeCapTooHighError" + }); + } + }; + Object.defineProperty(FeeCapTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/ + }); + FeeCapTooLowError = class extends BaseError2 { + constructor({ cause, maxFeePerGas } = {}) { + super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, { + cause, + name: "FeeCapTooLowError" + }); + } + }; + Object.defineProperty(FeeCapTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/ + }); + NonceTooHighError = class extends BaseError2 { + constructor({ cause, nonce } = {}) { + super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" }); + } + }; + Object.defineProperty(NonceTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce too high/ + }); + NonceTooLowError = class extends BaseError2 { + constructor({ cause, nonce } = {}) { + super([ + `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`, + "Try increasing the nonce or find the latest nonce with `getTransactionCount`." + ].join("\n"), { cause, name: "NonceTooLowError" }); + } + }; + Object.defineProperty(NonceTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce too low|transaction already imported|already known/ + }); + NonceMaxValueError = class extends BaseError2 { + constructor({ cause, nonce } = {}) { + super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" }); + } + }; + Object.defineProperty(NonceMaxValueError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce has max value/ + }); + InsufficientFundsError = class extends BaseError2 { + constructor({ cause } = {}) { + super([ + "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account." + ].join("\n"), { + cause, + metaMessages: [ + "This error could arise when the account does not have enough funds to:", + " - pay for the total gas fee,", + " - pay for the value to send.", + " ", + "The cost of the transaction is calculated as `gas * gas fee + value`, where:", + " - `gas` is the amount of gas needed for transaction to execute,", + " - `gas fee` is the gas fee,", + " - `value` is the amount of ether to send to the recipient." + ], + name: "InsufficientFundsError" + }); + } + }; + Object.defineProperty(InsufficientFundsError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /insufficient funds|exceeds transaction sender account balance/ + }); + IntrinsicGasTooHighError = class extends BaseError2 { + constructor({ cause, gas } = {}) { + super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, { + cause, + name: "IntrinsicGasTooHighError" + }); + } + }; + Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /intrinsic gas too high|gas limit reached/ + }); + IntrinsicGasTooLowError = class extends BaseError2 { + constructor({ cause, gas } = {}) { + super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, { + cause, + name: "IntrinsicGasTooLowError" + }); + } + }; + Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /intrinsic gas too low/ + }); + TransactionTypeNotSupportedError = class extends BaseError2 { + constructor({ cause }) { + super("The transaction type is not supported for this chain.", { + cause, + name: "TransactionTypeNotSupportedError" + }); + } + }; + Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /transaction type not valid/ + }); + TipAboveFeeCapError = class extends BaseError2 { + constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) { + super([ + `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).` + ].join("\n"), { + cause, + name: "TipAboveFeeCapError" + }); + } + }; + Object.defineProperty(TipAboveFeeCapError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/ + }); + UnknownNodeError = class extends BaseError2 { + constructor({ cause }) { + super(`An error occurred while executing: ${cause?.shortMessage}`, { + cause, + name: "UnknownNodeError" + }); + } + }; + } +}); + +// node_modules/viem/_esm/utils/errors/getNodeError.js +function getNodeError(err, args) { + const message = (err.details || "").toLowerCase(); + const executionRevertedError = err instanceof BaseError2 ? err.walk((e) => e?.code === ExecutionRevertedError.code) : err; + if (executionRevertedError instanceof BaseError2) + return new ExecutionRevertedError({ + cause: err, + message: executionRevertedError.details + }); + if (ExecutionRevertedError.nodeMessage.test(message)) + return new ExecutionRevertedError({ + cause: err, + message: err.details + }); + if (FeeCapTooHighError.nodeMessage.test(message)) + return new FeeCapTooHighError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas + }); + if (FeeCapTooLowError.nodeMessage.test(message)) + return new FeeCapTooLowError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas + }); + if (NonceTooHighError.nodeMessage.test(message)) + return new NonceTooHighError({ cause: err, nonce: args?.nonce }); + if (NonceTooLowError.nodeMessage.test(message)) + return new NonceTooLowError({ cause: err, nonce: args?.nonce }); + if (NonceMaxValueError.nodeMessage.test(message)) + return new NonceMaxValueError({ cause: err, nonce: args?.nonce }); + if (InsufficientFundsError.nodeMessage.test(message)) + return new InsufficientFundsError({ cause: err }); + if (IntrinsicGasTooHighError.nodeMessage.test(message)) + return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas }); + if (IntrinsicGasTooLowError.nodeMessage.test(message)) + return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas }); + if (TransactionTypeNotSupportedError.nodeMessage.test(message)) + return new TransactionTypeNotSupportedError({ cause: err }); + if (TipAboveFeeCapError.nodeMessage.test(message)) + return new TipAboveFeeCapError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas, + maxPriorityFeePerGas: args?.maxPriorityFeePerGas + }); + return new UnknownNodeError({ + cause: err + }); +} +var init_getNodeError = __esm({ + "node_modules/viem/_esm/utils/errors/getNodeError.js"() { + init_base(); + init_node(); + } +}); + +// node_modules/viem/_esm/utils/formatters/extract.js +function extract(value_, { format }) { + if (!format) + return {}; + const value = {}; + function extract_(formatted2) { + const keys = Object.keys(formatted2); + for (const key of keys) { + if (key in value_) + value[key] = value_[key]; + if (formatted2[key] && typeof formatted2[key] === "object" && !Array.isArray(formatted2[key])) + extract_(formatted2[key]); + } + } + const formatted = format(value_ || {}); + extract_(formatted); + return value; +} +var init_extract = __esm({ + "node_modules/viem/_esm/utils/formatters/extract.js"() { + } +}); + +// node_modules/viem/_esm/utils/formatters/transactionRequest.js +function formatTransactionRequest(request) { + const rpcRequest = {}; + if (typeof request.authorizationList !== "undefined") + rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList); + if (typeof request.accessList !== "undefined") + rpcRequest.accessList = request.accessList; + if (typeof request.blobVersionedHashes !== "undefined") + rpcRequest.blobVersionedHashes = request.blobVersionedHashes; + if (typeof request.blobs !== "undefined") { + if (typeof request.blobs[0] !== "string") + rpcRequest.blobs = request.blobs.map((x2) => bytesToHex(x2)); + else + rpcRequest.blobs = request.blobs; + } + if (typeof request.data !== "undefined") + rpcRequest.data = request.data; + if (typeof request.from !== "undefined") + rpcRequest.from = request.from; + if (typeof request.gas !== "undefined") + rpcRequest.gas = numberToHex(request.gas); + if (typeof request.gasPrice !== "undefined") + rpcRequest.gasPrice = numberToHex(request.gasPrice); + if (typeof request.maxFeePerBlobGas !== "undefined") + rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas); + if (typeof request.maxFeePerGas !== "undefined") + rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas); + if (typeof request.maxPriorityFeePerGas !== "undefined") + rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas); + if (typeof request.nonce !== "undefined") + rpcRequest.nonce = numberToHex(request.nonce); + if (typeof request.to !== "undefined") + rpcRequest.to = request.to; + if (typeof request.type !== "undefined") + rpcRequest.type = rpcTransactionType[request.type]; + if (typeof request.value !== "undefined") + rpcRequest.value = numberToHex(request.value); + return rpcRequest; +} +function formatAuthorizationList(authorizationList) { + return authorizationList.map((authorization) => ({ + address: authorization.address, + r: authorization.r ? numberToHex(BigInt(authorization.r)) : authorization.r, + s: authorization.s ? numberToHex(BigInt(authorization.s)) : authorization.s, + chainId: numberToHex(authorization.chainId), + nonce: numberToHex(authorization.nonce), + ...typeof authorization.yParity !== "undefined" ? { yParity: numberToHex(authorization.yParity) } : {}, + ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: numberToHex(authorization.v) } : {} + })); +} +var rpcTransactionType; +var init_transactionRequest = __esm({ + "node_modules/viem/_esm/utils/formatters/transactionRequest.js"() { + init_toHex(); + rpcTransactionType = { + legacy: "0x0", + eip2930: "0x1", + eip1559: "0x2", + eip4844: "0x3", + eip7702: "0x4" + }; + } +}); + +// node_modules/viem/_esm/utils/stateOverride.js +function serializeStateMapping(stateMapping) { + if (!stateMapping || stateMapping.length === 0) + return void 0; + return stateMapping.reduce((acc, { slot, value }) => { + if (slot.length !== 66) + throw new InvalidBytesLengthError({ + size: slot.length, + targetSize: 66, + type: "hex" + }); + if (value.length !== 66) + throw new InvalidBytesLengthError({ + size: value.length, + targetSize: 66, + type: "hex" + }); + acc[slot] = value; + return acc; + }, {}); +} +function serializeAccountStateOverride(parameters) { + const { balance, nonce, state, stateDiff, code } = parameters; + const rpcAccountStateOverride = {}; + if (code !== void 0) + rpcAccountStateOverride.code = code; + if (balance !== void 0) + rpcAccountStateOverride.balance = numberToHex(balance); + if (nonce !== void 0) + rpcAccountStateOverride.nonce = numberToHex(nonce); + if (state !== void 0) + rpcAccountStateOverride.state = serializeStateMapping(state); + if (stateDiff !== void 0) { + if (rpcAccountStateOverride.state) + throw new StateAssignmentConflictError(); + rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff); + } + return rpcAccountStateOverride; +} +function serializeStateOverride(parameters) { + if (!parameters) + return void 0; + const rpcStateOverride = {}; + for (const { address, ...accountState } of parameters) { + if (!isAddress(address, { strict: false })) + throw new InvalidAddressError({ address }); + if (rpcStateOverride[address]) + throw new AccountStateConflictError({ address }); + rpcStateOverride[address] = serializeAccountStateOverride(accountState); + } + return rpcStateOverride; +} +var init_stateOverride2 = __esm({ + "node_modules/viem/_esm/utils/stateOverride.js"() { + init_address(); + init_data(); + init_stateOverride(); + init_isAddress(); + init_toHex(); + } +}); + +// node_modules/viem/_esm/constants/number.js +var maxInt8, maxInt16, maxInt24, maxInt32, maxInt40, maxInt48, maxInt56, maxInt64, maxInt72, maxInt80, maxInt88, maxInt96, maxInt104, maxInt112, maxInt120, maxInt128, maxInt136, maxInt144, maxInt152, maxInt160, maxInt168, maxInt176, maxInt184, maxInt192, maxInt200, maxInt208, maxInt216, maxInt224, maxInt232, maxInt240, maxInt248, maxInt256, minInt8, minInt16, minInt24, minInt32, minInt40, minInt48, minInt56, minInt64, minInt72, minInt80, minInt88, minInt96, minInt104, minInt112, minInt120, minInt128, minInt136, minInt144, minInt152, minInt160, minInt168, minInt176, minInt184, minInt192, minInt200, minInt208, minInt216, minInt224, minInt232, minInt240, minInt248, minInt256, maxUint8, maxUint16, maxUint24, maxUint32, maxUint40, maxUint48, maxUint56, maxUint64, maxUint72, maxUint80, maxUint88, maxUint96, maxUint104, maxUint112, maxUint120, maxUint128, maxUint136, maxUint144, maxUint152, maxUint160, maxUint168, maxUint176, maxUint184, maxUint192, maxUint200, maxUint208, maxUint216, maxUint224, maxUint232, maxUint240, maxUint248, maxUint256; +var init_number = __esm({ + "node_modules/viem/_esm/constants/number.js"() { + maxInt8 = 2n ** (8n - 1n) - 1n; + maxInt16 = 2n ** (16n - 1n) - 1n; + maxInt24 = 2n ** (24n - 1n) - 1n; + maxInt32 = 2n ** (32n - 1n) - 1n; + maxInt40 = 2n ** (40n - 1n) - 1n; + maxInt48 = 2n ** (48n - 1n) - 1n; + maxInt56 = 2n ** (56n - 1n) - 1n; + maxInt64 = 2n ** (64n - 1n) - 1n; + maxInt72 = 2n ** (72n - 1n) - 1n; + maxInt80 = 2n ** (80n - 1n) - 1n; + maxInt88 = 2n ** (88n - 1n) - 1n; + maxInt96 = 2n ** (96n - 1n) - 1n; + maxInt104 = 2n ** (104n - 1n) - 1n; + maxInt112 = 2n ** (112n - 1n) - 1n; + maxInt120 = 2n ** (120n - 1n) - 1n; + maxInt128 = 2n ** (128n - 1n) - 1n; + maxInt136 = 2n ** (136n - 1n) - 1n; + maxInt144 = 2n ** (144n - 1n) - 1n; + maxInt152 = 2n ** (152n - 1n) - 1n; + maxInt160 = 2n ** (160n - 1n) - 1n; + maxInt168 = 2n ** (168n - 1n) - 1n; + maxInt176 = 2n ** (176n - 1n) - 1n; + maxInt184 = 2n ** (184n - 1n) - 1n; + maxInt192 = 2n ** (192n - 1n) - 1n; + maxInt200 = 2n ** (200n - 1n) - 1n; + maxInt208 = 2n ** (208n - 1n) - 1n; + maxInt216 = 2n ** (216n - 1n) - 1n; + maxInt224 = 2n ** (224n - 1n) - 1n; + maxInt232 = 2n ** (232n - 1n) - 1n; + maxInt240 = 2n ** (240n - 1n) - 1n; + maxInt248 = 2n ** (248n - 1n) - 1n; + maxInt256 = 2n ** (256n - 1n) - 1n; + minInt8 = -(2n ** (8n - 1n)); + minInt16 = -(2n ** (16n - 1n)); + minInt24 = -(2n ** (24n - 1n)); + minInt32 = -(2n ** (32n - 1n)); + minInt40 = -(2n ** (40n - 1n)); + minInt48 = -(2n ** (48n - 1n)); + minInt56 = -(2n ** (56n - 1n)); + minInt64 = -(2n ** (64n - 1n)); + minInt72 = -(2n ** (72n - 1n)); + minInt80 = -(2n ** (80n - 1n)); + minInt88 = -(2n ** (88n - 1n)); + minInt96 = -(2n ** (96n - 1n)); + minInt104 = -(2n ** (104n - 1n)); + minInt112 = -(2n ** (112n - 1n)); + minInt120 = -(2n ** (120n - 1n)); + minInt128 = -(2n ** (128n - 1n)); + minInt136 = -(2n ** (136n - 1n)); + minInt144 = -(2n ** (144n - 1n)); + minInt152 = -(2n ** (152n - 1n)); + minInt160 = -(2n ** (160n - 1n)); + minInt168 = -(2n ** (168n - 1n)); + minInt176 = -(2n ** (176n - 1n)); + minInt184 = -(2n ** (184n - 1n)); + minInt192 = -(2n ** (192n - 1n)); + minInt200 = -(2n ** (200n - 1n)); + minInt208 = -(2n ** (208n - 1n)); + minInt216 = -(2n ** (216n - 1n)); + minInt224 = -(2n ** (224n - 1n)); + minInt232 = -(2n ** (232n - 1n)); + minInt240 = -(2n ** (240n - 1n)); + minInt248 = -(2n ** (248n - 1n)); + minInt256 = -(2n ** (256n - 1n)); + maxUint8 = 2n ** 8n - 1n; + maxUint16 = 2n ** 16n - 1n; + maxUint24 = 2n ** 24n - 1n; + maxUint32 = 2n ** 32n - 1n; + maxUint40 = 2n ** 40n - 1n; + maxUint48 = 2n ** 48n - 1n; + maxUint56 = 2n ** 56n - 1n; + maxUint64 = 2n ** 64n - 1n; + maxUint72 = 2n ** 72n - 1n; + maxUint80 = 2n ** 80n - 1n; + maxUint88 = 2n ** 88n - 1n; + maxUint96 = 2n ** 96n - 1n; + maxUint104 = 2n ** 104n - 1n; + maxUint112 = 2n ** 112n - 1n; + maxUint120 = 2n ** 120n - 1n; + maxUint128 = 2n ** 128n - 1n; + maxUint136 = 2n ** 136n - 1n; + maxUint144 = 2n ** 144n - 1n; + maxUint152 = 2n ** 152n - 1n; + maxUint160 = 2n ** 160n - 1n; + maxUint168 = 2n ** 168n - 1n; + maxUint176 = 2n ** 176n - 1n; + maxUint184 = 2n ** 184n - 1n; + maxUint192 = 2n ** 192n - 1n; + maxUint200 = 2n ** 200n - 1n; + maxUint208 = 2n ** 208n - 1n; + maxUint216 = 2n ** 216n - 1n; + maxUint224 = 2n ** 224n - 1n; + maxUint232 = 2n ** 232n - 1n; + maxUint240 = 2n ** 240n - 1n; + maxUint248 = 2n ** 248n - 1n; + maxUint256 = 2n ** 256n - 1n; + } +}); + +// node_modules/viem/_esm/utils/transaction/assertRequest.js +function assertRequest(args) { + const { account: account_, gasPrice, maxFeePerGas, maxPriorityFeePerGas, to: to2 } = args; + const account = account_ ? parseAccount(account_) : void 0; + if (account && !isAddress(account.address)) + throw new InvalidAddressError({ address: account.address }); + if (to2 && !isAddress(to2)) + throw new InvalidAddressError({ address: to2 }); + if (typeof gasPrice !== "undefined" && (typeof maxFeePerGas !== "undefined" || typeof maxPriorityFeePerGas !== "undefined")) + throw new FeeConflictError(); + if (maxFeePerGas && maxFeePerGas > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas }); + if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) + throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); +} +var init_assertRequest = __esm({ + "node_modules/viem/_esm/utils/transaction/assertRequest.js"() { + init_parseAccount(); + init_number(); + init_address(); + init_node(); + init_transaction(); + init_isAddress(); + } +}); + +// node_modules/viem/_esm/utils/address/isAddressEqual.js +function isAddressEqual(a, b2) { + if (!isAddress(a, { strict: false })) + throw new InvalidAddressError({ address: a }); + if (!isAddress(b2, { strict: false })) + throw new InvalidAddressError({ address: b2 }); + return a.toLowerCase() === b2.toLowerCase(); +} +var init_isAddressEqual = __esm({ + "node_modules/viem/_esm/utils/address/isAddressEqual.js"() { + init_address(); + init_isAddress(); + } +}); + +// node_modules/viem/_esm/utils/abi/decodeFunctionResult.js +function decodeFunctionResult(parameters) { + const { abi: abi4, args, functionName, data } = parameters; + let abiItem = abi4[0]; + if (functionName) { + const item = getAbiItem({ abi: abi4, args, name: functionName }); + if (!item) + throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath4 }); + abiItem = item; + } + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath4 }); + if (!abiItem.outputs) + throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath4 }); + const values = decodeAbiParameters(abiItem.outputs, data); + if (values && values.length > 1) + return values; + if (values && values.length === 1) + return values[0]; + return void 0; +} +var docsPath4; +var init_decodeFunctionResult = __esm({ + "node_modules/viem/_esm/utils/abi/decodeFunctionResult.js"() { + init_abi(); + init_decodeAbiParameters(); + init_getAbiItem(); + docsPath4 = "/docs/contract/decodeFunctionResult"; + } +}); + +// node_modules/viem/_esm/constants/abis.js +var multicall3Abi, universalResolverErrors, universalResolverResolveAbi, universalResolverReverseAbi, textResolverAbi, addressResolverAbi, universalSignatureValidatorAbi; +var init_abis = __esm({ + "node_modules/viem/_esm/constants/abis.js"() { + multicall3Abi = [ + { + inputs: [ + { + components: [ + { + name: "target", + type: "address" + }, + { + name: "allowFailure", + type: "bool" + }, + { + name: "callData", + type: "bytes" + } + ], + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate3", + outputs: [ + { + components: [ + { + name: "success", + type: "bool" + }, + { + name: "returnData", + type: "bytes" + } + ], + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "view", + type: "function" + } + ]; + universalResolverErrors = [ + { + inputs: [], + name: "ResolverNotFound", + type: "error" + }, + { + inputs: [], + name: "ResolverWildcardNotSupported", + type: "error" + }, + { + inputs: [], + name: "ResolverNotContract", + type: "error" + }, + { + inputs: [ + { + name: "returnData", + type: "bytes" + } + ], + name: "ResolverError", + type: "error" + }, + { + inputs: [ + { + components: [ + { + name: "status", + type: "uint16" + }, + { + name: "message", + type: "string" + } + ], + name: "errors", + type: "tuple[]" + } + ], + name: "HttpError", + type: "error" + } + ]; + universalResolverResolveAbi = [ + ...universalResolverErrors, + { + name: "resolve", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes" }, + { name: "data", type: "bytes" } + ], + outputs: [ + { name: "", type: "bytes" }, + { name: "address", type: "address" } + ] + }, + { + name: "resolve", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes" }, + { name: "data", type: "bytes" }, + { name: "gateways", type: "string[]" } + ], + outputs: [ + { name: "", type: "bytes" }, + { name: "address", type: "address" } + ] + } + ]; + universalResolverReverseAbi = [ + ...universalResolverErrors, + { + name: "reverse", + type: "function", + stateMutability: "view", + inputs: [{ type: "bytes", name: "reverseName" }], + outputs: [ + { type: "string", name: "resolvedName" }, + { type: "address", name: "resolvedAddress" }, + { type: "address", name: "reverseResolver" }, + { type: "address", name: "resolver" } + ] + }, + { + name: "reverse", + type: "function", + stateMutability: "view", + inputs: [ + { type: "bytes", name: "reverseName" }, + { type: "string[]", name: "gateways" } + ], + outputs: [ + { type: "string", name: "resolvedName" }, + { type: "address", name: "resolvedAddress" }, + { type: "address", name: "reverseResolver" }, + { type: "address", name: "resolver" } + ] + } + ]; + textResolverAbi = [ + { + name: "text", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes32" }, + { name: "key", type: "string" } + ], + outputs: [{ name: "", type: "string" }] + } + ]; + addressResolverAbi = [ + { + name: "addr", + type: "function", + stateMutability: "view", + inputs: [{ name: "name", type: "bytes32" }], + outputs: [{ name: "", type: "address" }] + }, + { + name: "addr", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes32" }, + { name: "coinType", type: "uint256" } + ], + outputs: [{ name: "", type: "bytes" }] + } + ]; + universalSignatureValidatorAbi = [ + { + inputs: [ + { + name: "_signer", + type: "address" + }, + { + name: "_hash", + type: "bytes32" + }, + { + name: "_signature", + type: "bytes" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [ + { + name: "_signer", + type: "address" + }, + { + name: "_hash", + type: "bytes32" + }, + { + name: "_signature", + type: "bytes" + } + ], + outputs: [ + { + type: "bool" + } + ], + stateMutability: "nonpayable", + type: "function", + name: "isValidSig" + } + ]; + } +}); + +// node_modules/viem/_esm/constants/contract.js +var aggregate3Signature; +var init_contract2 = __esm({ + "node_modules/viem/_esm/constants/contract.js"() { + aggregate3Signature = "0x82ad56cb"; + } +}); + +// node_modules/viem/_esm/constants/contracts.js +var deploylessCallViaBytecodeBytecode, deploylessCallViaFactoryBytecode, universalSignatureValidatorByteCode; +var init_contracts = __esm({ + "node_modules/viem/_esm/constants/contracts.js"() { + deploylessCallViaBytecodeBytecode = "0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe"; + deploylessCallViaFactoryBytecode = "0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe"; + universalSignatureValidatorByteCode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572"; + } +}); + +// node_modules/viem/_esm/errors/chain.js +var ChainDoesNotSupportContract, ChainMismatchError, ChainNotFoundError, ClientChainNotConfiguredError, InvalidChainIdError; +var init_chain = __esm({ + "node_modules/viem/_esm/errors/chain.js"() { + init_base(); + ChainDoesNotSupportContract = class extends BaseError2 { + constructor({ blockNumber, chain, contract }) { + super(`Chain "${chain.name}" does not support contract "${contract.name}".`, { + metaMessages: [ + "This could be due to any of the following:", + ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [ + `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).` + ] : [ + `- The chain does not have the contract "${contract.name}" configured.` + ] + ], + name: "ChainDoesNotSupportContract" + }); + } + }; + ChainMismatchError = class extends BaseError2 { + constructor({ chain, currentChainId }) { + super(`The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} \u2013 ${chain.name}).`, { + metaMessages: [ + `Current Chain ID: ${currentChainId}`, + `Expected Chain ID: ${chain.id} \u2013 ${chain.name}` + ], + name: "ChainMismatchError" + }); + } + }; + ChainNotFoundError = class extends BaseError2 { + constructor() { + super([ + "No chain was provided to the request.", + "Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient." + ].join("\n"), { + name: "ChainNotFoundError" + }); + } + }; + ClientChainNotConfiguredError = class extends BaseError2 { + constructor() { + super("No chain was provided to the Client.", { + name: "ClientChainNotConfiguredError" + }); + } + }; + InvalidChainIdError = class extends BaseError2 { + constructor({ chainId }) { + super(typeof chainId === "number" ? `Chain ID "${chainId}" is invalid.` : "Chain ID is invalid.", { name: "InvalidChainIdError" }); + } + }; + } +}); + +// node_modules/viem/_esm/utils/abi/encodeDeployData.js +function encodeDeployData(parameters) { + const { abi: abi4, args, bytecode } = parameters; + if (!args || args.length === 0) + return bytecode; + const description = abi4.find((x2) => "type" in x2 && x2.type === "constructor"); + if (!description) + throw new AbiConstructorNotFoundError({ docsPath: docsPath5 }); + if (!("inputs" in description)) + throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 }); + if (!description.inputs || description.inputs.length === 0) + throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 }); + const data = encodeAbiParameters(description.inputs, args); + return concatHex([bytecode, data]); +} +var docsPath5; +var init_encodeDeployData = __esm({ + "node_modules/viem/_esm/utils/abi/encodeDeployData.js"() { + init_abi(); + init_concat(); + init_encodeAbiParameters(); + docsPath5 = "/docs/contract/encodeDeployData"; + } +}); + +// node_modules/viem/_esm/utils/chain/getChainContractAddress.js +function getChainContractAddress({ blockNumber, chain, contract: name }) { + const contract = chain?.contracts?.[name]; + if (!contract) + throw new ChainDoesNotSupportContract({ + chain, + contract: { name } + }); + if (blockNumber && contract.blockCreated && contract.blockCreated > blockNumber) + throw new ChainDoesNotSupportContract({ + blockNumber, + chain, + contract: { + name, + blockCreated: contract.blockCreated + } + }); + return contract.address; +} +var init_getChainContractAddress = __esm({ + "node_modules/viem/_esm/utils/chain/getChainContractAddress.js"() { + init_chain(); + } +}); + +// node_modules/viem/_esm/utils/errors/getCallError.js +function getCallError(err, { docsPath: docsPath6, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new CallExecutionError(cause, { + docsPath: docsPath6, + ...args + }); +} +var init_getCallError = __esm({ + "node_modules/viem/_esm/utils/errors/getCallError.js"() { + init_contract(); + init_node(); + init_getNodeError(); + } +}); + +// node_modules/viem/_esm/utils/promise/withResolvers.js +function withResolvers() { + let resolve = () => void 0; + let reject = () => void 0; + const promise = new Promise((resolve_, reject_) => { + resolve = resolve_; + reject = reject_; + }); + return { promise, resolve, reject }; +} +var init_withResolvers = __esm({ + "node_modules/viem/_esm/utils/promise/withResolvers.js"() { + } +}); + +// node_modules/viem/_esm/utils/promise/createBatchScheduler.js +function createBatchScheduler({ fn: fn2, id: id2, shouldSplitBatch, wait: wait2 = 0, sort }) { + const exec = async () => { + const scheduler = getScheduler(); + flush(); + const args = scheduler.map(({ args: args2 }) => args2); + if (args.length === 0) + return; + fn2(args).then((data) => { + if (sort && Array.isArray(data)) + data.sort(sort); + for (let i = 0; i < scheduler.length; i++) { + const { resolve } = scheduler[i]; + resolve?.([data[i], data]); + } + }).catch((err) => { + for (let i = 0; i < scheduler.length; i++) { + const { reject } = scheduler[i]; + reject?.(err); + } + }); + }; + const flush = () => schedulerCache.delete(id2); + const getBatchedArgs = () => getScheduler().map(({ args }) => args); + const getScheduler = () => schedulerCache.get(id2) || []; + const setScheduler = (item) => schedulerCache.set(id2, [...getScheduler(), item]); + return { + flush, + async schedule(args) { + const { promise, resolve, reject } = withResolvers(); + const split3 = shouldSplitBatch?.([...getBatchedArgs(), args]); + if (split3) + exec(); + const hasActiveScheduler = getScheduler().length > 0; + if (hasActiveScheduler) { + setScheduler({ args, resolve, reject }); + return promise; + } + setScheduler({ args, resolve, reject }); + setTimeout(exec, wait2); + return promise; + } + }; +} +var schedulerCache; +var init_createBatchScheduler = __esm({ + "node_modules/viem/_esm/utils/promise/createBatchScheduler.js"() { + init_withResolvers(); + schedulerCache = /* @__PURE__ */ new Map(); + } +}); + +// node_modules/viem/_esm/errors/ccip.js +var OffchainLookupError, OffchainLookupResponseMalformedError, OffchainLookupSenderMismatchError; +var init_ccip = __esm({ + "node_modules/viem/_esm/errors/ccip.js"() { + init_stringify(); + init_base(); + init_utils3(); + OffchainLookupError = class extends BaseError2 { + constructor({ callbackSelector, cause, data, extraData, sender, urls }) { + super(cause.shortMessage || "An error occurred while fetching for an offchain result.", { + cause, + metaMessages: [ + ...cause.metaMessages || [], + cause.metaMessages?.length ? "" : [], + "Offchain Gateway Call:", + urls && [ + " Gateway URL(s):", + ...urls.map((url2) => ` ${getUrl(url2)}`) + ], + ` Sender: ${sender}`, + ` Data: ${data}`, + ` Callback selector: ${callbackSelector}`, + ` Extra data: ${extraData}` + ].flat(), + name: "OffchainLookupError" + }); + } + }; + OffchainLookupResponseMalformedError = class extends BaseError2 { + constructor({ result, url: url2 }) { + super("Offchain gateway response is malformed. Response data must be a hex value.", { + metaMessages: [ + `Gateway URL: ${getUrl(url2)}`, + `Response: ${stringify(result)}` + ], + name: "OffchainLookupResponseMalformedError" + }); + } + }; + OffchainLookupSenderMismatchError = class extends BaseError2 { + constructor({ sender, to: to2 }) { + super("Reverted sender address does not match target contract address (`to`).", { + metaMessages: [ + `Contract address: ${to2}`, + `OffchainLookup sender address: ${sender}` + ], + name: "OffchainLookupSenderMismatchError" + }); + } + }; + } +}); + +// node_modules/viem/_esm/utils/ccip.js +var ccip_exports = {}; +__export(ccip_exports, { + ccipRequest: () => ccipRequest, + offchainLookup: () => offchainLookup, + offchainLookupAbiItem: () => offchainLookupAbiItem, + offchainLookupSignature: () => offchainLookupSignature +}); +async function offchainLookup(client, { blockNumber, blockTag, data, to: to2 }) { + const { args } = decodeErrorResult({ + data, + abi: [offchainLookupAbiItem] + }); + const [sender, urls, callData, callbackSelector, extraData] = args; + const { ccipRead } = client; + const ccipRequest_ = ccipRead && typeof ccipRead?.request === "function" ? ccipRead.request : ccipRequest; + try { + if (!isAddressEqual(to2, sender)) + throw new OffchainLookupSenderMismatchError({ sender, to: to2 }); + const result = await ccipRequest_({ data: callData, sender, urls }); + const { data: data_ } = await call(client, { + blockNumber, + blockTag, + data: concat([ + callbackSelector, + encodeAbiParameters([{ type: "bytes" }, { type: "bytes" }], [result, extraData]) + ]), + to: to2 + }); + return data_; + } catch (err) { + throw new OffchainLookupError({ + callbackSelector, + cause: err, + data, + extraData, + sender, + urls + }); + } +} +async function ccipRequest({ data, sender, urls }) { + let error = new Error("An unknown error occurred."); + for (let i = 0; i < urls.length; i++) { + const url2 = urls[i]; + const method = url2.includes("{data}") ? "GET" : "POST"; + const body = method === "POST" ? { data, sender } : void 0; + const headers = method === "POST" ? { "Content-Type": "application/json" } : {}; + try { + const response = await fetch(url2.replace("{sender}", sender.toLowerCase()).replace("{data}", data), { + body: JSON.stringify(body), + headers, + method + }); + let result; + if (response.headers.get("Content-Type")?.startsWith("application/json")) { + result = (await response.json()).data; + } else { + result = await response.text(); + } + if (!response.ok) { + error = new HttpRequestError({ + body, + details: result?.error ? stringify(result.error) : response.statusText, + headers: response.headers, + status: response.status, + url: url2 + }); + continue; + } + if (!isHex(result)) { + error = new OffchainLookupResponseMalformedError({ + result, + url: url2 + }); + continue; + } + return result; + } catch (err) { + error = new HttpRequestError({ + body, + details: err.message, + url: url2 + }); + } + } + throw error; +} +var offchainLookupSignature, offchainLookupAbiItem; +var init_ccip2 = __esm({ + "node_modules/viem/_esm/utils/ccip.js"() { + init_call(); + init_ccip(); + init_request(); + init_decodeErrorResult(); + init_encodeAbiParameters(); + init_isAddressEqual(); + init_concat(); + init_isHex(); + init_stringify(); + offchainLookupSignature = "0x556f1830"; + offchainLookupAbiItem = { + name: "OffchainLookup", + type: "error", + inputs: [ + { + name: "sender", + type: "address" + }, + { + name: "urls", + type: "string[]" + }, + { + name: "callData", + type: "bytes" + }, + { + name: "callbackFunction", + type: "bytes4" + }, + { + name: "extraData", + type: "bytes" + } + ] + }; + } +}); + +// node_modules/viem/_esm/actions/public/call.js +async function call(client, args) { + const { account: account_ = client.account, batch = Boolean(client.batch?.multicall), blockNumber, blockTag = "latest", accessList, blobs, code, data: data_, factory, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value, stateOverride, ...rest } = args; + const account = account_ ? parseAccount(account_) : void 0; + if (code && (factory || factoryData)) + throw new BaseError2("Cannot provide both `code` & `factory`/`factoryData` as parameters."); + if (code && to2) + throw new BaseError2("Cannot provide both `code` & `to` as parameters."); + const deploylessCallViaBytecode = code && data_; + const deploylessCallViaFactory = factory && factoryData && to2 && data_; + const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory; + const data = (() => { + if (deploylessCallViaBytecode) + return toDeploylessCallViaBytecodeData({ + code, + data: data_ + }); + if (deploylessCallViaFactory) + return toDeploylessCallViaFactoryData({ + data: data_, + factory, + factoryData, + to: to2 + }); + return data_; + })(); + try { + assertRequest(args); + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const rpcStateOverride = serializeStateOverride(stateOverride); + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format = chainFormat || formatTransactionRequest; + const request = format({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + from: account?.address, + accessList, + blobs, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to: deploylessCall ? void 0 : to2, + value + }); + if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) { + try { + return await scheduleMulticall(client, { + ...request, + blockNumber, + blockTag + }); + } catch (err) { + if (!(err instanceof ClientChainNotConfiguredError) && !(err instanceof ChainDoesNotSupportContract)) + throw err; + } + } + const response = await client.request({ + method: "eth_call", + params: rpcStateOverride ? [ + request, + block, + rpcStateOverride + ] : [request, block] + }); + if (response === "0x") + return { data: void 0 }; + return { data: response }; + } catch (err) { + const data2 = getRevertErrorData(err); + const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await Promise.resolve().then(() => (init_ccip2(), ccip_exports)); + if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to2) + return { data: await offchainLookup2(client, { data: data2, to: to2 }) }; + if (deploylessCall && data2?.slice(0, 10) === "0x101bb98d") + throw new CounterfactualDeploymentFailedError({ factory }); + throw getCallError(err, { + ...args, + account, + chain: client.chain + }); + } +} +function shouldPerformMulticall({ request }) { + const { data, to: to2, ...request_ } = request; + if (!data) + return false; + if (data.startsWith(aggregate3Signature)) + return false; + if (!to2) + return false; + if (Object.values(request_).filter((x2) => typeof x2 !== "undefined").length > 0) + return false; + return true; +} +async function scheduleMulticall(client, args) { + const { batchSize = 1024, wait: wait2 = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; + const { blockNumber, blockTag = "latest", data, multicallAddress: multicallAddress_, to: to2 } = args; + let multicallAddress = multicallAddress_; + if (!multicallAddress) { + if (!client.chain) + throw new ClientChainNotConfiguredError(); + multicallAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "multicall3" + }); + } + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const { schedule } = createBatchScheduler({ + id: `${client.uid}.${block}`, + wait: wait2, + shouldSplitBatch(args2) { + const size5 = args2.reduce((size6, { data: data2 }) => size6 + (data2.length - 2), 0); + return size5 > batchSize * 2; + }, + fn: async (requests) => { + const calls = requests.map((request) => ({ + allowFailure: true, + callData: request.data, + target: request.to + })); + const calldata = encodeFunctionData({ + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3" + }); + const data2 = await client.request({ + method: "eth_call", + params: [ + { + data: calldata, + to: multicallAddress + }, + block + ] + }); + return decodeFunctionResult({ + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3", + data: data2 || "0x" + }); + } + }); + const [{ returnData, success }] = await schedule({ data, to: to2 }); + if (!success) + throw new RawContractError({ data: returnData }); + if (returnData === "0x") + return { data: void 0 }; + return { data: returnData }; +} +function toDeploylessCallViaBytecodeData(parameters) { + const { code, data } = parameters; + return encodeDeployData({ + abi: parseAbi(["constructor(bytes, bytes)"]), + bytecode: deploylessCallViaBytecodeBytecode, + args: [code, data] + }); +} +function toDeploylessCallViaFactoryData(parameters) { + const { data, factory, factoryData, to: to2 } = parameters; + return encodeDeployData({ + abi: parseAbi(["constructor(address, bytes, address, bytes)"]), + bytecode: deploylessCallViaFactoryBytecode, + args: [to2, data, factory, factoryData] + }); +} +function getRevertErrorData(err) { + if (!(err instanceof BaseError2)) + return void 0; + const error = err.walk(); + return typeof error?.data === "object" ? error.data?.data : error.data; +} +var init_call = __esm({ + "node_modules/viem/_esm/actions/public/call.js"() { + init_exports(); + init_parseAccount(); + init_abis(); + init_contract2(); + init_contracts(); + init_base(); + init_chain(); + init_contract(); + init_decodeFunctionResult(); + init_encodeDeployData(); + init_encodeFunctionData(); + init_getChainContractAddress(); + init_toHex(); + init_getCallError(); + init_extract(); + init_transactionRequest(); + init_createBatchScheduler(); + init_stateOverride2(); + init_assertRequest(); + } +}); + +// node_modules/axios/dist/node/axios.cjs +var require_axios = __commonJS({ + "node_modules/axios/dist/node/axios.cjs"(exports2, module2) { + "use strict"; + var FormData$1 = require_form_data(); + var crypto4 = __require("crypto"); + var url2 = __require("url"); + var proxyFromEnv2 = require_proxy_from_env(); + var http3 = __require("http"); + var https2 = __require("https"); + var util3 = __require("util"); + var followRedirects2 = require_follow_redirects(); + var zlib2 = __require("zlib"); + var stream4 = __require("stream"); + var events = __require("events"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; + } + var FormData__default = /* @__PURE__ */ _interopDefaultLegacy(FormData$1); + var crypto__default = /* @__PURE__ */ _interopDefaultLegacy(crypto4); + var url__default = /* @__PURE__ */ _interopDefaultLegacy(url2); + var proxyFromEnv__default = /* @__PURE__ */ _interopDefaultLegacy(proxyFromEnv2); + var http__default = /* @__PURE__ */ _interopDefaultLegacy(http3); + var https__default = /* @__PURE__ */ _interopDefaultLegacy(https2); + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util3); + var followRedirects__default = /* @__PURE__ */ _interopDefaultLegacy(followRedirects2); + var zlib__default = /* @__PURE__ */ _interopDefaultLegacy(zlib2); + var stream__default = /* @__PURE__ */ _interopDefaultLegacy(stream4); + function bind2(fn2, thisArg) { + return function wrap() { + return fn2.apply(thisArg, arguments); + }; + } + var { toString: toString3 } = Object.prototype; + var { getPrototypeOf: getPrototypeOf2 } = Object; + var { iterator: iterator2, toStringTag: toStringTag2 } = Symbol; + var kindOf2 = /* @__PURE__ */ ((cache) => (thing) => { + const str = toString3.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + })(/* @__PURE__ */ Object.create(null)); + var kindOfTest2 = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf2(thing) === type; + }; + var typeOfTest2 = (type) => (thing) => typeof thing === type; + var { isArray: isArray2 } = Array; + var isUndefined2 = typeOfTest2("undefined"); + function isBuffer2(val) { + return val !== null && !isUndefined2(val) && val.constructor !== null && !isUndefined2(val.constructor) && isFunction2(val.constructor.isBuffer) && val.constructor.isBuffer(val); + } + var isArrayBuffer2 = kindOfTest2("ArrayBuffer"); + function isArrayBufferView2(val) { + let result; + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + result = ArrayBuffer.isView(val); + } else { + result = val && val.buffer && isArrayBuffer2(val.buffer); + } + return result; + } + var isString2 = typeOfTest2("string"); + var isFunction2 = typeOfTest2("function"); + var isNumber2 = typeOfTest2("number"); + var isObject2 = (thing) => thing !== null && typeof thing === "object"; + var isBoolean2 = (thing) => thing === true || thing === false; + var isPlainObject2 = (val) => { + if (kindOf2(val) !== "object") { + return false; + } + const prototype4 = getPrototypeOf2(val); + return (prototype4 === null || prototype4 === Object.prototype || Object.getPrototypeOf(prototype4) === null) && !(toStringTag2 in val) && !(iterator2 in val); + }; + var isDate2 = kindOfTest2("Date"); + var isFile2 = kindOfTest2("File"); + var isBlob2 = kindOfTest2("Blob"); + var isFileList2 = kindOfTest2("FileList"); + var isStream2 = (val) => isObject2(val) && isFunction2(val.pipe); + var isFormData2 = (thing) => { + let kind; + return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction2(thing.append) && ((kind = kindOf2(thing)) === "formdata" || // detect form-data instance + kind === "object" && isFunction2(thing.toString) && thing.toString() === "[object FormData]")); + }; + var isURLSearchParams2 = kindOfTest2("URLSearchParams"); + var [isReadableStream2, isRequest2, isResponse2, isHeaders2] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest2); + var trim5 = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); + function forEach2(obj, fn2, { allOwnKeys = false } = {}) { + if (obj === null || typeof obj === "undefined") { + return; + } + let i; + let l; + if (typeof obj !== "object") { + obj = [obj]; + } + if (isArray2(obj)) { + for (i = 0, l = obj.length; i < l; i++) { + fn2.call(null, obj[i], i, obj); + } + } else { + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + fn2.call(null, obj[key], key, obj); + } + } + } + function findKey2(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; + } + var _global2 = (() => { + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; + })(); + var isContextDefined2 = (context) => !isUndefined2(context) && context !== _global2; + function merge2() { + const { caseless } = isContextDefined2(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey2(result, key) || key; + if (isPlainObject2(result[targetKey]) && isPlainObject2(val)) { + result[targetKey] = merge2(result[targetKey], val); + } else if (isPlainObject2(val)) { + result[targetKey] = merge2({}, val); + } else if (isArray2(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach2(arguments[i], assignValue); + } + return result; + } + var extend2 = (a, b2, thisArg, { allOwnKeys } = {}) => { + forEach2(b2, (val, key) => { + if (thisArg && isFunction2(val)) { + a[key] = bind2(val, thisArg); + } else { + a[key] = val; + } + }, { allOwnKeys }); + return a; + }; + var stripBOM2 = (content) => { + if (content.charCodeAt(0) === 65279) { + content = content.slice(1); + } + return content; + }; + var inherits2 = (constructor, superConstructor, props, descriptors3) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors3); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, "super", { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); + }; + var toFlatObject2 = (sourceObj, destObj, filter2, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + destObj = destObj || {}; + if (sourceObj == null) return destObj; + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter2 !== false && getPrototypeOf2(sourceObj); + } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype); + return destObj; + }; + var endsWith2 = (str, searchString, position) => { + str = String(str); + if (position === void 0 || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; + }; + var toArray2 = (thing) => { + if (!thing) return null; + if (isArray2(thing)) return thing; + let i = thing.length; + if (!isNumber2(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; + }; + var isTypedArray2 = /* @__PURE__ */ ((TypedArray) => { + return (thing) => { + return TypedArray && thing instanceof TypedArray; + }; + })(typeof Uint8Array !== "undefined" && getPrototypeOf2(Uint8Array)); + var forEachEntry2 = (obj, fn2) => { + const generator = obj && obj[iterator2]; + const _iterator = generator.call(obj); + let result; + while ((result = _iterator.next()) && !result.done) { + const pair = result.value; + fn2.call(obj, pair[0], pair[1]); + } + }; + var matchAll2 = (regExp, str) => { + let matches; + const arr = []; + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + return arr; + }; + var isHTMLForm2 = kindOfTest2("HTMLFormElement"); + var toCamelCase2 = (str) => { + return str.toLowerCase().replace( + /[-_\s]([a-z\d])(\w*)/g, + function replacer(m2, p1, p2) { + return p1.toUpperCase() + p2; + } + ); + }; + var hasOwnProperty2 = (({ hasOwnProperty: hasOwnProperty3 }) => (obj, prop) => hasOwnProperty3.call(obj, prop))(Object.prototype); + var isRegExp2 = kindOfTest2("RegExp"); + var reduceDescriptors2 = (obj, reducer) => { + const descriptors3 = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + forEach2(descriptors3, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + Object.defineProperties(obj, reducedDescriptors); + }; + var freezeMethods2 = (obj) => { + reduceDescriptors2(obj, (descriptor, name) => { + if (isFunction2(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) { + return false; + } + const value = obj[name]; + if (!isFunction2(value)) return; + descriptor.enumerable = false; + if ("writable" in descriptor) { + descriptor.writable = false; + return; + } + if (!descriptor.set) { + descriptor.set = () => { + throw Error("Can not rewrite read-only method '" + name + "'"); + }; + } + }); + }; + var toObjectSet2 = (arrayOrString, delimiter) => { + const obj = {}; + const define2 = (arr) => { + arr.forEach((value) => { + obj[value] = true; + }); + }; + isArray2(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); + return obj; + }; + var noop2 = () => { + }; + var toFiniteNumber2 = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; + }; + function isSpecCompliantForm2(thing) { + return !!(thing && isFunction2(thing.append) && thing[toStringTag2] === "FormData" && thing[iterator2]); + } + var toJSONObject2 = (obj) => { + const stack = new Array(10); + const visit = (source, i) => { + if (isObject2(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + if (!("toJSON" in source)) { + stack[i] = source; + const target = isArray2(source) ? [] : {}; + forEach2(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined2(reducedValue) && (target[key] = reducedValue); + }); + stack[i] = void 0; + return target; + } + } + return source; + }; + return visit(obj, 0); + }; + var isAsyncFn2 = kindOfTest2("AsyncFunction"); + var isThenable2 = (thing) => thing && (isObject2(thing) || isFunction2(thing)) && isFunction2(thing.then) && isFunction2(thing.catch); + var _setImmediate2 = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + return postMessageSupported ? ((token, callbacks) => { + _global2.addEventListener("message", ({ source, data }) => { + if (source === _global2 && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + return (cb) => { + callbacks.push(cb); + _global2.postMessage(token, "*"); + }; + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); + })( + typeof setImmediate === "function", + isFunction2(_global2.postMessage) + ); + var asap2 = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global2) : typeof process !== "undefined" && process.nextTick || _setImmediate2; + var isIterable2 = (thing) => thing != null && isFunction2(thing[iterator2]); + var utils$1 = { + isArray: isArray2, + isArrayBuffer: isArrayBuffer2, + isBuffer: isBuffer2, + isFormData: isFormData2, + isArrayBufferView: isArrayBufferView2, + isString: isString2, + isNumber: isNumber2, + isBoolean: isBoolean2, + isObject: isObject2, + isPlainObject: isPlainObject2, + isReadableStream: isReadableStream2, + isRequest: isRequest2, + isResponse: isResponse2, + isHeaders: isHeaders2, + isUndefined: isUndefined2, + isDate: isDate2, + isFile: isFile2, + isBlob: isBlob2, + isRegExp: isRegExp2, + isFunction: isFunction2, + isStream: isStream2, + isURLSearchParams: isURLSearchParams2, + isTypedArray: isTypedArray2, + isFileList: isFileList2, + forEach: forEach2, + merge: merge2, + extend: extend2, + trim: trim5, + stripBOM: stripBOM2, + inherits: inherits2, + toFlatObject: toFlatObject2, + kindOf: kindOf2, + kindOfTest: kindOfTest2, + endsWith: endsWith2, + toArray: toArray2, + forEachEntry: forEachEntry2, + matchAll: matchAll2, + isHTMLForm: isHTMLForm2, + hasOwnProperty: hasOwnProperty2, + hasOwnProp: hasOwnProperty2, + // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors: reduceDescriptors2, + freezeMethods: freezeMethods2, + toObjectSet: toObjectSet2, + toCamelCase: toCamelCase2, + noop: noop2, + toFiniteNumber: toFiniteNumber2, + findKey: findKey2, + global: _global2, + isContextDefined: isContextDefined2, + isSpecCompliantForm: isSpecCompliantForm2, + toJSONObject: toJSONObject2, + isAsyncFn: isAsyncFn2, + isThenable: isThenable2, + setImmediate: _setImmediate2, + asap: asap2, + isIterable: isIterable2 + }; + function AxiosError3(message, code, config3, request, response) { + Error.call(this); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.message = message; + this.name = "AxiosError"; + code && (this.code = code); + config3 && (this.config = config3); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; + } + } + utils$1.inherits(AxiosError3, Error, { + toJSON: function toJSON2() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$1.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } + }); + var prototype$1 = AxiosError3.prototype; + var descriptors2 = {}; + [ + "ERR_BAD_OPTION_VALUE", + "ERR_BAD_OPTION", + "ECONNABORTED", + "ETIMEDOUT", + "ERR_NETWORK", + "ERR_FR_TOO_MANY_REDIRECTS", + "ERR_DEPRECATED", + "ERR_BAD_RESPONSE", + "ERR_BAD_REQUEST", + "ERR_CANCELED", + "ERR_NOT_SUPPORT", + "ERR_INVALID_URL" + // eslint-disable-next-line func-names + ].forEach((code) => { + descriptors2[code] = { value: code }; + }); + Object.defineProperties(AxiosError3, descriptors2); + Object.defineProperty(prototype$1, "isAxiosError", { value: true }); + AxiosError3.from = (error, code, config3, request, response, customProps) => { + const axiosError = Object.create(prototype$1); + utils$1.toFlatObject(error, axiosError, function filter2(obj) { + return obj !== Error.prototype; + }, (prop) => { + return prop !== "isAxiosError"; + }); + AxiosError3.call(axiosError, error.message, code, config3, request, response); + axiosError.cause = error; + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; + }; + function isVisitable2(thing) { + return utils$1.isPlainObject(thing) || utils$1.isArray(thing); + } + function removeBrackets2(key) { + return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key; + } + function renderKey2(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + token = removeBrackets2(token); + return !dots && i ? "[" + token + "]" : token; + }).join(dots ? "." : ""); + } + function isFlatArray2(arr) { + return utils$1.isArray(arr) && !arr.some(isVisitable2); + } + var predicates2 = utils$1.toFlatObject(utils$1, {}, null, function filter2(prop) { + return /^is[A-Z]/.test(prop); + }); + function toFormData3(obj, formData, options) { + if (!utils$1.isObject(obj)) { + throw new TypeError("target must be an object"); + } + formData = formData || new (FormData__default["default"] || FormData)(); + options = utils$1.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + return !utils$1.isUndefined(source[option]); + }); + const metaTokens = options.metaTokens; + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; + const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + if (!utils$1.isFunction(visitor)) { + throw new TypeError("visitor must be a function"); + } + function convertValue(value) { + if (value === null) return ""; + if (utils$1.isDate(value)) { + return value.toISOString(); + } + if (!useBlob && utils$1.isBlob(value)) { + throw new AxiosError3("Blob is not supported. Use a Buffer instead."); + } + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); + } + return value; + } + function defaultVisitor(value, key, path) { + let arr = value; + if (value && !path && typeof value === "object") { + if (utils$1.endsWith(key, "{}")) { + key = metaTokens ? key : key.slice(0, -2); + value = JSON.stringify(value); + } else if (utils$1.isArray(value) && isFlatArray2(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) { + key = removeBrackets2(key); + arr.forEach(function each(el2, index2) { + !(utils$1.isUndefined(el2) || el2 === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey2([key], index2, dots) : indexes === null ? key : key + "[]", + convertValue(el2) + ); + }); + return false; + } + } + if (isVisitable2(value)) { + return true; + } + formData.append(renderKey2(path, key, dots), convertValue(value)); + return false; + } + const stack = []; + const exposedHelpers = Object.assign(predicates2, { + defaultVisitor, + convertValue, + isVisitable: isVisitable2 + }); + function build(value, path) { + if (utils$1.isUndefined(value)) return; + if (stack.indexOf(value) !== -1) { + throw Error("Circular reference detected in " + path.join(".")); + } + stack.push(value); + utils$1.forEach(value, function each(el2, key) { + const result = !(utils$1.isUndefined(el2) || el2 === null) && visitor.call( + formData, + el2, + utils$1.isString(key) ? key.trim() : key, + path, + exposedHelpers + ); + if (result === true) { + build(el2, path ? path.concat(key) : [key]); + } + }); + stack.pop(); + } + if (!utils$1.isObject(obj)) { + throw new TypeError("data must be an object"); + } + build(obj); + return formData; + } + function encode$1(str) { + const charMap = { + "!": "%21", + "'": "%27", + "(": "%28", + ")": "%29", + "~": "%7E", + "%20": "+", + "%00": "\0" + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); + } + function AxiosURLSearchParams2(params, options) { + this._pairs = []; + params && toFormData3(params, this, options); + } + var prototype3 = AxiosURLSearchParams2.prototype; + prototype3.append = function append2(name, value) { + this._pairs.push([name, value]); + }; + prototype3.toString = function toString4(encoder5) { + const _encode = encoder5 ? function(value) { + return encoder5.call(this, value, encode$1); + } : encode$1; + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + "=" + _encode(pair[1]); + }, "").join("&"); + }; + function encode6(val) { + return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); + } + function buildURL2(url3, params, options) { + if (!params) { + return url3; + } + const _encode = options && options.encode || encode6; + if (utils$1.isFunction(options)) { + options = { + serialize: options + }; + } + const serializeFn = options && options.serialize; + let serializedParams; + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams2(params, options).toString(_encode); + } + if (serializedParams) { + const hashmarkIndex = url3.indexOf("#"); + if (hashmarkIndex !== -1) { + url3 = url3.slice(0, hashmarkIndex); + } + url3 += (url3.indexOf("?") === -1 ? "?" : "&") + serializedParams; + } + return url3; + } + var InterceptorManager2 = class { + constructor() { + this.handlers = []; + } + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id2) { + if (this.handlers[id2]) { + this.handlers[id2] = null; + } + } + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn2) { + utils$1.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn2(h); + } + }); + } + }; + var InterceptorManager$1 = InterceptorManager2; + var transitionalDefaults = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false + }; + var URLSearchParams = url__default["default"].URLSearchParams; + var ALPHA2 = "abcdefghijklmnopqrstuvwxyz"; + var DIGIT2 = "0123456789"; + var ALPHABET2 = { + DIGIT: DIGIT2, + ALPHA: ALPHA2, + ALPHA_DIGIT: ALPHA2 + ALPHA2.toUpperCase() + DIGIT2 + }; + var generateString2 = (size5 = 16, alphabet = ALPHABET2.ALPHA_DIGIT) => { + let str = ""; + const { length } = alphabet; + const randomValues = new Uint32Array(size5); + crypto__default["default"].randomFillSync(randomValues); + for (let i = 0; i < size5; i++) { + str += alphabet[randomValues[i] % length]; + } + return str; + }; + var platform$1 = { + isNode: true, + classes: { + URLSearchParams, + FormData: FormData__default["default"], + Blob: typeof Blob !== "undefined" && Blob || null + }, + ALPHABET: ALPHABET2, + generateString: generateString2, + protocols: ["http", "https", "file", "data"] + }; + var hasBrowserEnv2 = typeof window !== "undefined" && typeof document !== "undefined"; + var _navigator2 = typeof navigator === "object" && navigator || void 0; + var hasStandardBrowserEnv2 = hasBrowserEnv2 && (!_navigator2 || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator2.product) < 0); + var hasStandardBrowserWebWorkerEnv2 = (() => { + return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; + })(); + var origin2 = hasBrowserEnv2 && window.location.href || "http://localhost"; + var utils = /* @__PURE__ */ Object.freeze({ + __proto__: null, + hasBrowserEnv: hasBrowserEnv2, + hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv2, + hasStandardBrowserEnv: hasStandardBrowserEnv2, + navigator: _navigator2, + origin: origin2 + }); + var platform = { + ...utils, + ...platform$1 + }; + function toURLEncodedForm2(data, options) { + return toFormData3(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils$1.isBuffer(value)) { + this.append(key, value.toString("base64")); + return false; + } + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); + } + function parsePropPath2(name) { + return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => { + return match[0] === "[]" ? "" : match[1] || match[0]; + }); + } + function arrayToObject2(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; + } + function formDataToJSON2(formData) { + function buildPath(path, value, target, index2) { + let name = path[index2++]; + if (name === "__proto__") return true; + const isNumericKey = Number.isFinite(+name); + const isLast = index2 >= path.length; + name = !name && utils$1.isArray(target) ? target.length : name; + if (isLast) { + if (utils$1.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + return !isNumericKey; + } + if (!target[name] || !utils$1.isObject(target[name])) { + target[name] = []; + } + const result = buildPath(path, value, target[name], index2); + if (result && utils$1.isArray(target[name])) { + target[name] = arrayToObject2(target[name]); + } + return !isNumericKey; + } + if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + const obj = {}; + utils$1.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath2(name), value, obj, 0); + }); + return obj; + } + return null; + } + function stringifySafely2(rawValue, parser, encoder5) { + if (utils$1.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$1.trim(rawValue); + } catch (e) { + if (e.name !== "SyntaxError") { + throw e; + } + } + } + return (encoder5 || JSON.stringify)(rawValue); + } + var defaults2 = { + transitional: transitionalDefaults, + adapter: ["xhr", "http", "fetch"], + transformRequest: [function transformRequest2(data, headers) { + const contentType = headers.getContentType() || ""; + const hasJSONContentType = contentType.indexOf("application/json") > -1; + const isObjectPayload = utils$1.isObject(data); + if (isObjectPayload && utils$1.isHTMLForm(data)) { + data = new FormData(data); + } + const isFormData3 = utils$1.isFormData(data); + if (isFormData3) { + return hasJSONContentType ? JSON.stringify(formDataToJSON2(data)) : data; + } + if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); + return data.toString(); + } + let isFileList3; + if (isObjectPayload) { + if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { + return toURLEncodedForm2(data, this.formSerializer).toString(); + } + if ((isFileList3 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { + const _FormData = this.env && this.env.FormData; + return toFormData3( + isFileList3 ? { "files[]": data } : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + if (isObjectPayload || hasJSONContentType) { + headers.setContentType("application/json", false); + return stringifySafely2(data); + } + return data; + }], + transformResponse: [function transformResponse2(data) { + const transitional2 = this.transitional || defaults2.transitional; + const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing; + const JSONRequested = this.responseType === "json"; + if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) { + return data; + } + if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { + const silentJSONParsing = transitional2 && transitional2.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === "SyntaxError") { + throw AxiosError3.from(e, AxiosError3.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + return data; + }], + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + xsrfCookieName: "XSRF-TOKEN", + xsrfHeaderName: "X-XSRF-TOKEN", + maxContentLength: -1, + maxBodyLength: -1, + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + validateStatus: function validateStatus2(status) { + return status >= 200 && status < 300; + }, + headers: { + common: { + "Accept": "application/json, text/plain, */*", + "Content-Type": void 0 + } + } + }; + utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { + defaults2.headers[method] = {}; + }); + var defaults$1 = defaults2; + var ignoreDuplicateOf2 = utils$1.toObjectSet([ + "age", + "authorization", + "content-length", + "content-type", + "etag", + "expires", + "from", + "host", + "if-modified-since", + "if-unmodified-since", + "last-modified", + "location", + "max-forwards", + "proxy-authorization", + "referer", + "retry-after", + "user-agent" + ]); + var parseHeaders = (rawHeaders) => { + const parsed = {}; + let key; + let val; + let i; + rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { + i = line.indexOf(":"); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + if (!key || parsed[key] && ignoreDuplicateOf2[key]) { + return; + } + if (key === "set-cookie") { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; + } + }); + return parsed; + }; + var $internals2 = Symbol("internals"); + function normalizeHeader2(header) { + return header && String(header).trim().toLowerCase(); + } + function normalizeValue2(value) { + if (value === false || value == null) { + return value; + } + return utils$1.isArray(value) ? value.map(normalizeValue2) : String(value); + } + function parseTokens2(str) { + const tokens = /* @__PURE__ */ Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + while (match = tokensRE.exec(str)) { + tokens[match[1]] = match[2]; + } + return tokens; + } + var isValidHeaderName2 = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + function matchHeaderValue2(context, value, header, filter2, isHeaderNameFilter) { + if (utils$1.isFunction(filter2)) { + return filter2.call(this, value, header); + } + if (isHeaderNameFilter) { + value = header; + } + if (!utils$1.isString(value)) return; + if (utils$1.isString(filter2)) { + return value.indexOf(filter2) !== -1; + } + if (utils$1.isRegExp(filter2)) { + return filter2.test(value); + } + } + function formatHeader2(header) { + return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str) => { + return char.toUpperCase() + str; + }); + } + function buildAccessors2(obj, header) { + const accessorName = utils$1.toCamelCase(" " + header); + ["get", "set", "has"].forEach((methodName) => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); + } + var AxiosHeaders3 = class { + constructor(headers) { + headers && this.set(headers); + } + set(header, valueOrRewrite, rewrite) { + const self2 = this; + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader2(_header); + if (!lHeader) { + throw new Error("header name must be a non-empty string"); + } + const key = utils$1.findKey(self2, lHeader); + if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { + self2[key || _header] = normalizeValue2(_value); + } + } + const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName2(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils$1.isObject(header) && utils$1.isIterable(header)) { + let obj = {}, dest, key; + for (const entry of header) { + if (!utils$1.isArray(entry)) { + throw TypeError("Object iterator must return a key-value pair"); + } + obj[key = entry[0]] = (dest = obj[key]) ? utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1]; + } + setHeaders(obj, valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + return this; + } + get(header, parser) { + header = normalizeHeader2(header); + if (header) { + const key = utils$1.findKey(this, header); + if (key) { + const value = this[key]; + if (!parser) { + return value; + } + if (parser === true) { + return parseTokens2(value); + } + if (utils$1.isFunction(parser)) { + return parser.call(this, value, key); + } + if (utils$1.isRegExp(parser)) { + return parser.exec(value); + } + throw new TypeError("parser must be boolean|regexp|function"); + } + } + } + has(header, matcher) { + header = normalizeHeader2(header); + if (header) { + const key = utils$1.findKey(this, header); + return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue2(this, this[key], key, matcher))); + } + return false; + } + delete(header, matcher) { + const self2 = this; + let deleted = false; + function deleteHeader(_header) { + _header = normalizeHeader2(_header); + if (_header) { + const key = utils$1.findKey(self2, _header); + if (key && (!matcher || matchHeaderValue2(self2, self2[key], key, matcher))) { + delete self2[key]; + deleted = true; + } + } + } + if (utils$1.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + return deleted; + } + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + while (i--) { + const key = keys[i]; + if (!matcher || matchHeaderValue2(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + return deleted; + } + normalize(format) { + const self2 = this; + const headers = {}; + utils$1.forEach(this, (value, header) => { + const key = utils$1.findKey(headers, header); + if (key) { + self2[key] = normalizeValue2(value); + delete self2[header]; + return; + } + const normalized = format ? formatHeader2(header) : String(header).trim(); + if (normalized !== header) { + delete self2[header]; + } + self2[normalized] = normalizeValue2(value); + headers[normalized] = true; + }); + return this; + } + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + toJSON(asStrings) { + const obj = /* @__PURE__ */ Object.create(null); + utils$1.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value); + }); + return obj; + } + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); + } + getSetCookie() { + return this.get("set-cookie") || []; + } + get [Symbol.toStringTag]() { + return "AxiosHeaders"; + } + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + static concat(first, ...targets) { + const computed = new this(first); + targets.forEach((target) => computed.set(target)); + return computed; + } + static accessor(header) { + const internals = this[$internals2] = this[$internals2] = { + accessors: {} + }; + const accessors = internals.accessors; + const prototype4 = this.prototype; + function defineAccessor(_header) { + const lHeader = normalizeHeader2(_header); + if (!accessors[lHeader]) { + buildAccessors2(prototype4, _header); + accessors[lHeader] = true; + } + } + utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + return this; + } + }; + AxiosHeaders3.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); + utils$1.reduceDescriptors(AxiosHeaders3.prototype, ({ value }, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + }; + }); + utils$1.freezeMethods(AxiosHeaders3); + var AxiosHeaders$1 = AxiosHeaders3; + function transformData2(fns, response) { + const config3 = this || defaults$1; + const context = response || config3; + const headers = AxiosHeaders$1.from(context.headers); + let data = context.data; + utils$1.forEach(fns, function transform(fn2) { + data = fn2.call(config3, data, headers.normalize(), response ? response.status : void 0); + }); + headers.normalize(); + return data; + } + function isCancel3(value) { + return !!(value && value.__CANCEL__); + } + function CanceledError3(message, config3, request) { + AxiosError3.call(this, message == null ? "canceled" : message, AxiosError3.ERR_CANCELED, config3, request); + this.name = "CanceledError"; + } + utils$1.inherits(CanceledError3, AxiosError3, { + __CANCEL__: true + }); + function settle2(resolve, reject, response) { + const validateStatus2 = response.config.validateStatus; + if (!response.status || !validateStatus2 || validateStatus2(response.status)) { + resolve(response); + } else { + reject(new AxiosError3( + "Request failed with status code " + response.status, + [AxiosError3.ERR_BAD_REQUEST, AxiosError3.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } + } + function isAbsoluteURL2(url3) { + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url3); + } + function combineURLs2(baseURL, relativeURL) { + return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; + } + function buildFullPath2(baseURL, requestedURL, allowAbsoluteUrls) { + let isRelativeUrl = !isAbsoluteURL2(requestedURL); + if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) { + return combineURLs2(baseURL, requestedURL); + } + return requestedURL; + } + var VERSION3 = "1.9.0"; + function parseProtocol2(url3) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url3); + return match && match[1] || ""; + } + var DATA_URL_PATTERN2 = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; + function fromDataURI2(uri, asBlob, options) { + const _Blob = options && options.Blob || platform.classes.Blob; + const protocol = parseProtocol2(uri); + if (asBlob === void 0 && _Blob) { + asBlob = true; + } + if (protocol === "data") { + uri = protocol.length ? uri.slice(protocol.length + 1) : uri; + const match = DATA_URL_PATTERN2.exec(uri); + if (!match) { + throw new AxiosError3("Invalid URL", AxiosError3.ERR_INVALID_URL); + } + const mime = match[1]; + const isBase64 = match[2]; + const body = match[3]; + const buffer2 = Buffer.from(decodeURIComponent(body), isBase64 ? "base64" : "utf8"); + if (asBlob) { + if (!_Blob) { + throw new AxiosError3("Blob is not supported", AxiosError3.ERR_NOT_SUPPORT); + } + return new _Blob([buffer2], { type: mime }); + } + return buffer2; + } + throw new AxiosError3("Unsupported protocol " + protocol, AxiosError3.ERR_NOT_SUPPORT); + } + var kInternals2 = Symbol("internals"); + var AxiosTransformStream2 = class extends stream__default["default"].Transform { + constructor(options) { + options = utils$1.toFlatObject(options, { + maxRate: 0, + chunkSize: 64 * 1024, + minChunkSize: 100, + timeWindow: 500, + ticksRate: 2, + samplesCount: 15 + }, null, (prop, source) => { + return !utils$1.isUndefined(source[prop]); + }); + super({ + readableHighWaterMark: options.chunkSize + }); + const internals = this[kInternals2] = { + timeWindow: options.timeWindow, + chunkSize: options.chunkSize, + maxRate: options.maxRate, + minChunkSize: options.minChunkSize, + bytesSeen: 0, + isCaptured: false, + notifiedBytesLoaded: 0, + ts: Date.now(), + bytes: 0, + onReadCallback: null + }; + this.on("newListener", (event) => { + if (event === "progress") { + if (!internals.isCaptured) { + internals.isCaptured = true; + } + } + }); + } + _read(size5) { + const internals = this[kInternals2]; + if (internals.onReadCallback) { + internals.onReadCallback(); + } + return super._read(size5); + } + _transform(chunk, encoding, callback) { + const internals = this[kInternals2]; + const maxRate = internals.maxRate; + const readableHighWaterMark = this.readableHighWaterMark; + const timeWindow = internals.timeWindow; + const divider = 1e3 / timeWindow; + const bytesThreshold = maxRate / divider; + const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; + const pushChunk = (_chunk, _callback) => { + const bytes = Buffer.byteLength(_chunk); + internals.bytesSeen += bytes; + internals.bytes += bytes; + internals.isCaptured && this.emit("progress", internals.bytesSeen); + if (this.push(_chunk)) { + process.nextTick(_callback); + } else { + internals.onReadCallback = () => { + internals.onReadCallback = null; + process.nextTick(_callback); + }; + } + }; + const transformChunk = (_chunk, _callback) => { + const chunkSize = Buffer.byteLength(_chunk); + let chunkRemainder = null; + let maxChunkSize = readableHighWaterMark; + let bytesLeft; + let passed = 0; + if (maxRate) { + const now = Date.now(); + if (!internals.ts || (passed = now - internals.ts) >= timeWindow) { + internals.ts = now; + bytesLeft = bytesThreshold - internals.bytes; + internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; + passed = 0; + } + bytesLeft = bytesThreshold - internals.bytes; + } + if (maxRate) { + if (bytesLeft <= 0) { + return setTimeout(() => { + _callback(null, _chunk); + }, timeWindow - passed); + } + if (bytesLeft < maxChunkSize) { + maxChunkSize = bytesLeft; + } + } + if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) { + chunkRemainder = _chunk.subarray(maxChunkSize); + _chunk = _chunk.subarray(0, maxChunkSize); + } + pushChunk(_chunk, chunkRemainder ? () => { + process.nextTick(_callback, null, chunkRemainder); + } : _callback); + }; + transformChunk(chunk, function transformNextChunk(err, _chunk) { + if (err) { + return callback(err); + } + if (_chunk) { + transformChunk(_chunk, transformNextChunk); + } else { + callback(null); + } + }); + } + }; + var AxiosTransformStream$1 = AxiosTransformStream2; + var { asyncIterator: asyncIterator2 } = Symbol; + var readBlob2 = async function* (blob) { + if (blob.stream) { + yield* blob.stream(); + } else if (blob.arrayBuffer) { + yield await blob.arrayBuffer(); + } else if (blob[asyncIterator2]) { + yield* blob[asyncIterator2](); + } else { + yield blob; + } + }; + var readBlob$1 = readBlob2; + var BOUNDARY_ALPHABET2 = platform.ALPHABET.ALPHA_DIGIT + "-_"; + var textEncoder2 = typeof TextEncoder === "function" ? new TextEncoder() : new util__default["default"].TextEncoder(); + var CRLF2 = "\r\n"; + var CRLF_BYTES2 = textEncoder2.encode(CRLF2); + var CRLF_BYTES_COUNT2 = 2; + var FormDataPart2 = class { + constructor(name, value) { + const { escapeName } = this.constructor; + const isStringValue = utils$1.isString(value); + let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF2}`; + if (isStringValue) { + value = textEncoder2.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF2)); + } else { + headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF2}`; + } + this.headers = textEncoder2.encode(headers + CRLF2); + this.contentLength = isStringValue ? value.byteLength : value.size; + this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT2; + this.name = name; + this.value = value; + } + async *encode() { + yield this.headers; + const { value } = this; + if (utils$1.isTypedArray(value)) { + yield value; + } else { + yield* readBlob$1(value); + } + yield CRLF_BYTES2; + } + static escapeName(name) { + return String(name).replace(/[\r\n"]/g, (match) => ({ + "\r": "%0D", + "\n": "%0A", + '"': "%22" + })[match]); + } + }; + var formDataToStream2 = (form, headersHandler, options) => { + const { + tag = "form-data-boundary", + size: size5 = 25, + boundary = tag + "-" + platform.generateString(size5, BOUNDARY_ALPHABET2) + } = options || {}; + if (!utils$1.isFormData(form)) { + throw TypeError("FormData instance required"); + } + if (boundary.length < 1 || boundary.length > 70) { + throw Error("boundary must be 10-70 characters long"); + } + const boundaryBytes = textEncoder2.encode("--" + boundary + CRLF2); + const footerBytes = textEncoder2.encode("--" + boundary + "--" + CRLF2); + let contentLength = footerBytes.byteLength; + const parts = Array.from(form.entries()).map(([name, value]) => { + const part = new FormDataPart2(name, value); + contentLength += part.size; + return part; + }); + contentLength += boundaryBytes.byteLength * parts.length; + contentLength = utils$1.toFiniteNumber(contentLength); + const computedHeaders = { + "Content-Type": `multipart/form-data; boundary=${boundary}` + }; + if (Number.isFinite(contentLength)) { + computedHeaders["Content-Length"] = contentLength; + } + headersHandler && headersHandler(computedHeaders); + return stream4.Readable.from(async function* () { + for (const part of parts) { + yield boundaryBytes; + yield* part.encode(); + } + yield footerBytes; + }()); + }; + var formDataToStream$1 = formDataToStream2; + var ZlibHeaderTransformStream2 = class extends stream__default["default"].Transform { + __transform(chunk, encoding, callback) { + this.push(chunk); + callback(); + } + _transform(chunk, encoding, callback) { + if (chunk.length !== 0) { + this._transform = this.__transform; + if (chunk[0] !== 120) { + const header = Buffer.alloc(2); + header[0] = 120; + header[1] = 156; + this.push(header, encoding); + } + } + this.__transform(chunk, encoding, callback); + } + }; + var ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream2; + var callbackify2 = (fn2, reducer) => { + return utils$1.isAsyncFn(fn2) ? function(...args) { + const cb = args.pop(); + fn2.apply(this, args).then((value) => { + try { + reducer ? cb(null, ...reducer(value)) : cb(null, value); + } catch (err) { + cb(err); + } + }, cb); + } : fn2; + }; + var callbackify$1 = callbackify2; + function speedometer2(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + min = min !== void 0 ? min : 1e3; + return function push(chunkLength) { + const now = Date.now(); + const startedAt = timestamps[tail]; + if (!firstSampleTS) { + firstSampleTS = now; + } + bytes[head] = chunkLength; + timestamps[head] = now; + let i = tail; + let bytesCount = 0; + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + head = (head + 1) % samplesCount; + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + if (now - firstSampleTS < min) { + return; + } + const passed = startedAt && now - startedAt; + return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; + }; + } + function throttle2(fn2, freq) { + let timestamp = 0; + let threshold = 1e3 / freq; + let lastArgs; + let timer; + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn2.apply(null, args); + }; + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if (passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs); + }, threshold - passed); + } + } + }; + const flush = () => lastArgs && invoke(lastArgs); + return [throttled, flush]; + } + var progressEventReducer2 = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer2(50, 250); + return throttle2((e) => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : void 0; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange2 = loaded <= total; + bytesNotified = loaded; + const data = { + loaded, + total, + progress: total ? loaded / total : void 0, + bytes: progressBytes, + rate: rate ? rate : void 0, + estimated: rate && total && inRange2 ? (total - loaded) / rate : void 0, + event: e, + lengthComputable: total != null, + [isDownloadStream ? "download" : "upload"]: true + }; + listener(data); + }, freq); + }; + var progressEventDecorator2 = (total, throttled) => { + const lengthComputable = total != null; + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; + }; + var asyncDecorator2 = (fn2) => (...args) => utils$1.asap(() => fn2(...args)); + var zlibOptions2 = { + flush: zlib__default["default"].constants.Z_SYNC_FLUSH, + finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH + }; + var brotliOptions2 = { + flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH + }; + var isBrotliSupported2 = utils$1.isFunction(zlib__default["default"].createBrotliDecompress); + var { http: httpFollow2, https: httpsFollow2 } = followRedirects__default["default"]; + var isHttps2 = /https:?/; + var supportedProtocols2 = platform.protocols.map((protocol) => { + return protocol + ":"; + }); + var flushOnFinish2 = (stream5, [throttled, flush]) => { + stream5.on("end", flush).on("error", flush); + return throttled; + }; + function dispatchBeforeRedirect2(options, responseDetails) { + if (options.beforeRedirects.proxy) { + options.beforeRedirects.proxy(options); + } + if (options.beforeRedirects.config) { + options.beforeRedirects.config(options, responseDetails); + } + } + function setProxy2(options, configProxy, location) { + let proxy = configProxy; + if (!proxy && proxy !== false) { + const proxyUrl = proxyFromEnv__default["default"].getProxyForUrl(location); + if (proxyUrl) { + proxy = new URL(proxyUrl); + } + } + if (proxy) { + if (proxy.username) { + proxy.auth = (proxy.username || "") + ":" + (proxy.password || ""); + } + if (proxy.auth) { + if (proxy.auth.username || proxy.auth.password) { + proxy.auth = (proxy.auth.username || "") + ":" + (proxy.auth.password || ""); + } + const base64 = Buffer.from(proxy.auth, "utf8").toString("base64"); + options.headers["Proxy-Authorization"] = "Basic " + base64; + } + options.headers.host = options.hostname + (options.port ? ":" + options.port : ""); + const proxyHost = proxy.hostname || proxy.host; + options.hostname = proxyHost; + options.host = proxyHost; + options.port = proxy.port; + options.path = location; + if (proxy.protocol) { + options.protocol = proxy.protocol.includes(":") ? proxy.protocol : `${proxy.protocol}:`; + } + } + options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { + setProxy2(redirectOptions, configProxy, redirectOptions.href); + }; + } + var isHttpAdapterSupported2 = typeof process !== "undefined" && utils$1.kindOf(process) === "process"; + var wrapAsync2 = (asyncExecutor) => { + return new Promise((resolve, reject) => { + let onDone; + let isDone; + const done = (value, isRejected) => { + if (isDone) return; + isDone = true; + onDone && onDone(value, isRejected); + }; + const _resolve = (value) => { + done(value); + resolve(value); + }; + const _reject = (reason) => { + done(reason, true); + reject(reason); + }; + asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject); + }); + }; + var resolveFamily2 = ({ address, family }) => { + if (!utils$1.isString(address)) { + throw TypeError("address must be a string"); + } + return { + address, + family: family || (address.indexOf(".") < 0 ? 6 : 4) + }; + }; + var buildAddressEntry2 = (address, family) => resolveFamily2(utils$1.isObject(address) ? address : { address, family }); + var httpAdapter2 = isHttpAdapterSupported2 && function httpAdapter3(config3) { + return wrapAsync2(async function dispatchHttpRequest(resolve, reject, onDone) { + let { data, lookup, family } = config3; + const { responseType, responseEncoding } = config3; + const method = config3.method.toUpperCase(); + let isDone; + let rejected = false; + let req; + if (lookup) { + const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]); + lookup = (hostname, opt, cb) => { + _lookup(hostname, opt, (err, arg0, arg1) => { + if (err) { + return cb(err); + } + const addresses = utils$1.isArray(arg0) ? arg0.map((addr) => buildAddressEntry2(addr)) : [buildAddressEntry2(arg0, arg1)]; + opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); + }); + }; + } + const emitter = new events.EventEmitter(); + const onFinished = () => { + if (config3.cancelToken) { + config3.cancelToken.unsubscribe(abort); + } + if (config3.signal) { + config3.signal.removeEventListener("abort", abort); + } + emitter.removeAllListeners(); + }; + onDone((value, isRejected) => { + isDone = true; + if (isRejected) { + rejected = true; + onFinished(); + } + }); + function abort(reason) { + emitter.emit("abort", !reason || reason.type ? new CanceledError3(null, config3, req) : reason); + } + emitter.once("abort", reject); + if (config3.cancelToken || config3.signal) { + config3.cancelToken && config3.cancelToken.subscribe(abort); + if (config3.signal) { + config3.signal.aborted ? abort() : config3.signal.addEventListener("abort", abort); + } + } + const fullPath = buildFullPath2(config3.baseURL, config3.url, config3.allowAbsoluteUrls); + const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : void 0); + const protocol = parsed.protocol || supportedProtocols2[0]; + if (protocol === "data:") { + let convertedData; + if (method !== "GET") { + return settle2(resolve, reject, { + status: 405, + statusText: "method not allowed", + headers: {}, + config: config3 + }); + } + try { + convertedData = fromDataURI2(config3.url, responseType === "blob", { + Blob: config3.env && config3.env.Blob + }); + } catch (err) { + throw AxiosError3.from(err, AxiosError3.ERR_BAD_REQUEST, config3); + } + if (responseType === "text") { + convertedData = convertedData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === "utf8") { + convertedData = utils$1.stripBOM(convertedData); + } + } else if (responseType === "stream") { + convertedData = stream__default["default"].Readable.from(convertedData); + } + return settle2(resolve, reject, { + data: convertedData, + status: 200, + statusText: "OK", + headers: new AxiosHeaders$1(), + config: config3 + }); + } + if (supportedProtocols2.indexOf(protocol) === -1) { + return reject(new AxiosError3( + "Unsupported protocol " + protocol, + AxiosError3.ERR_BAD_REQUEST, + config3 + )); + } + const headers = AxiosHeaders$1.from(config3.headers).normalize(); + headers.set("User-Agent", "axios/" + VERSION3, false); + const { onUploadProgress, onDownloadProgress } = config3; + const maxRate = config3.maxRate; + let maxUploadRate = void 0; + let maxDownloadRate = void 0; + if (utils$1.isSpecCompliantForm(data)) { + const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); + data = formDataToStream$1(data, (formHeaders) => { + headers.set(formHeaders); + }, { + tag: `axios-${VERSION3}-boundary`, + boundary: userBoundary && userBoundary[1] || void 0 + }); + } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) { + headers.set(data.getHeaders()); + if (!headers.hasContentLength()) { + try { + const knownLength = await util__default["default"].promisify(data.getLength).call(data); + Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); + } catch (e) { + } + } + } else if (utils$1.isBlob(data) || utils$1.isFile(data)) { + data.size && headers.setContentType(data.type || "application/octet-stream"); + headers.setContentLength(data.size || 0); + data = stream__default["default"].Readable.from(readBlob$1(data)); + } else if (data && !utils$1.isStream(data)) { + if (Buffer.isBuffer(data)) ; + else if (utils$1.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils$1.isString(data)) { + data = Buffer.from(data, "utf-8"); + } else { + return reject(new AxiosError3( + "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream", + AxiosError3.ERR_BAD_REQUEST, + config3 + )); + } + headers.setContentLength(data.length, false); + if (config3.maxBodyLength > -1 && data.length > config3.maxBodyLength) { + return reject(new AxiosError3( + "Request body larger than maxBodyLength limit", + AxiosError3.ERR_BAD_REQUEST, + config3 + )); + } + } + const contentLength = utils$1.toFiniteNumber(headers.getContentLength()); + if (utils$1.isArray(maxRate)) { + maxUploadRate = maxRate[0]; + maxDownloadRate = maxRate[1]; + } else { + maxUploadRate = maxDownloadRate = maxRate; + } + if (data && (onUploadProgress || maxUploadRate)) { + if (!utils$1.isStream(data)) { + data = stream__default["default"].Readable.from(data, { objectMode: false }); + } + data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ + maxRate: utils$1.toFiniteNumber(maxUploadRate) + })], utils$1.noop); + onUploadProgress && data.on("progress", flushOnFinish2( + data, + progressEventDecorator2( + contentLength, + progressEventReducer2(asyncDecorator2(onUploadProgress), false, 3) + ) + )); + } + let auth = void 0; + if (config3.auth) { + const username = config3.auth.username || ""; + const password = config3.auth.password || ""; + auth = username + ":" + password; + } + if (!auth && parsed.username) { + const urlUsername = parsed.username; + const urlPassword = parsed.password; + auth = urlUsername + ":" + urlPassword; + } + auth && headers.delete("authorization"); + let path; + try { + path = buildURL2( + parsed.pathname + parsed.search, + config3.params, + config3.paramsSerializer + ).replace(/^\?/, ""); + } catch (err) { + const customErr = new Error(err.message); + customErr.config = config3; + customErr.url = config3.url; + customErr.exists = true; + return reject(customErr); + } + headers.set( + "Accept-Encoding", + "gzip, compress, deflate" + (isBrotliSupported2 ? ", br" : ""), + false + ); + const options = { + path, + method, + headers: headers.toJSON(), + agents: { http: config3.httpAgent, https: config3.httpsAgent }, + auth, + protocol, + family, + beforeRedirect: dispatchBeforeRedirect2, + beforeRedirects: {} + }; + !utils$1.isUndefined(lookup) && (options.lookup = lookup); + if (config3.socketPath) { + options.socketPath = config3.socketPath; + } else { + options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; + options.port = parsed.port; + setProxy2(options, config3.proxy, protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options.path); + } + let transport; + const isHttpsRequest = isHttps2.test(options.protocol); + options.agent = isHttpsRequest ? config3.httpsAgent : config3.httpAgent; + if (config3.transport) { + transport = config3.transport; + } else if (config3.maxRedirects === 0) { + transport = isHttpsRequest ? https__default["default"] : http__default["default"]; + } else { + if (config3.maxRedirects) { + options.maxRedirects = config3.maxRedirects; + } + if (config3.beforeRedirect) { + options.beforeRedirects.config = config3.beforeRedirect; + } + transport = isHttpsRequest ? httpsFollow2 : httpFollow2; + } + if (config3.maxBodyLength > -1) { + options.maxBodyLength = config3.maxBodyLength; + } else { + options.maxBodyLength = Infinity; + } + if (config3.insecureHTTPParser) { + options.insecureHTTPParser = config3.insecureHTTPParser; + } + req = transport.request(options, function handleResponse(res) { + if (req.destroyed) return; + const streams = [res]; + const responseLength = +res.headers["content-length"]; + if (onDownloadProgress || maxDownloadRate) { + const transformStream = new AxiosTransformStream$1({ + maxRate: utils$1.toFiniteNumber(maxDownloadRate) + }); + onDownloadProgress && transformStream.on("progress", flushOnFinish2( + transformStream, + progressEventDecorator2( + responseLength, + progressEventReducer2(asyncDecorator2(onDownloadProgress), true, 3) + ) + )); + streams.push(transformStream); + } + let responseStream = res; + const lastRequest = res.req || req; + if (config3.decompress !== false && res.headers["content-encoding"]) { + if (method === "HEAD" || res.statusCode === 204) { + delete res.headers["content-encoding"]; + } + switch ((res.headers["content-encoding"] || "").toLowerCase()) { + /*eslint default-case:0*/ + case "gzip": + case "x-gzip": + case "compress": + case "x-compress": + streams.push(zlib__default["default"].createUnzip(zlibOptions2)); + delete res.headers["content-encoding"]; + break; + case "deflate": + streams.push(new ZlibHeaderTransformStream$1()); + streams.push(zlib__default["default"].createUnzip(zlibOptions2)); + delete res.headers["content-encoding"]; + break; + case "br": + if (isBrotliSupported2) { + streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions2)); + delete res.headers["content-encoding"]; + } + } + } + responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0]; + const offListeners = stream__default["default"].finished(responseStream, () => { + offListeners(); + onFinished(); + }); + const response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: new AxiosHeaders$1(res.headers), + config: config3, + request: lastRequest + }; + if (responseType === "stream") { + response.data = responseStream; + settle2(resolve, reject, response); + } else { + const responseBuffer = []; + let totalResponseBytes = 0; + responseStream.on("data", function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; + if (config3.maxContentLength > -1 && totalResponseBytes > config3.maxContentLength) { + rejected = true; + responseStream.destroy(); + reject(new AxiosError3( + "maxContentLength size of " + config3.maxContentLength + " exceeded", + AxiosError3.ERR_BAD_RESPONSE, + config3, + lastRequest + )); + } + }); + responseStream.on("aborted", function handlerStreamAborted() { + if (rejected) { + return; + } + const err = new AxiosError3( + "stream has been aborted", + AxiosError3.ERR_BAD_RESPONSE, + config3, + lastRequest + ); + responseStream.destroy(err); + reject(err); + }); + responseStream.on("error", function handleStreamError(err) { + if (req.destroyed) return; + reject(AxiosError3.from(err, null, config3, lastRequest)); + }); + responseStream.on("end", function handleStreamEnd() { + try { + let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (responseType !== "arraybuffer") { + responseData = responseData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === "utf8") { + responseData = utils$1.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + return reject(AxiosError3.from(err, null, config3, response.request, response)); + } + settle2(resolve, reject, response); + }); + } + emitter.once("abort", (err) => { + if (!responseStream.destroyed) { + responseStream.emit("error", err); + responseStream.destroy(); + } + }); + }); + emitter.once("abort", (err) => { + reject(err); + req.destroy(err); + }); + req.on("error", function handleRequestError(err) { + reject(AxiosError3.from(err, null, config3, req)); + }); + req.on("socket", function handleRequestSocket(socket) { + socket.setKeepAlive(true, 1e3 * 60); + }); + if (config3.timeout) { + const timeout = parseInt(config3.timeout, 10); + if (Number.isNaN(timeout)) { + reject(new AxiosError3( + "error trying to parse `config.timeout` to int", + AxiosError3.ERR_BAD_OPTION_VALUE, + config3, + req + )); + return; + } + req.setTimeout(timeout, function handleRequestTimeout() { + if (isDone) return; + let timeoutErrorMessage = config3.timeout ? "timeout of " + config3.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = config3.transitional || transitionalDefaults; + if (config3.timeoutErrorMessage) { + timeoutErrorMessage = config3.timeoutErrorMessage; + } + reject(new AxiosError3( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError3.ETIMEDOUT : AxiosError3.ECONNABORTED, + config3, + req + )); + abort(); + }); + } + if (utils$1.isStream(data)) { + let ended = false; + let errored = false; + data.on("end", () => { + ended = true; + }); + data.once("error", (err) => { + errored = true; + req.destroy(err); + }); + data.on("close", () => { + if (!ended && !errored) { + abort(new CanceledError3("Request stream has been aborted", config3, req)); + } + }); + data.pipe(req); + } else { + req.end(data); + } + }); + }; + var isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin3, isMSIE) => (url3) => { + url3 = new URL(url3, platform.origin); + return origin3.protocol === url3.protocol && origin3.host === url3.host && (isMSIE || origin3.port === url3.port); + })( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) + ) : () => true; + var cookies = platform.hasStandardBrowserEnv ? ( + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + "=" + encodeURIComponent(value)]; + utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); + utils$1.isString(path) && cookie.push("path=" + path); + utils$1.isString(domain) && cookie.push("domain=" + domain); + secure === true && cookie.push("secure"); + document.cookie = cookie.join("; "); + }, + read(name) { + const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)")); + return match ? decodeURIComponent(match[3]) : null; + }, + remove(name) { + this.write(name, "", Date.now() - 864e5); + } + } + ) : ( + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() { + }, + read() { + return null; + }, + remove() { + } + } + ); + var headersToObject2 = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; + function mergeConfig3(config1, config22) { + config22 = config22 || {}; + const config3 = {}; + function getMergedValue(target, source, prop, caseless) { + if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { + return utils$1.merge.call({ caseless }, target, source); + } else if (utils$1.isPlainObject(source)) { + return utils$1.merge({}, source); + } else if (utils$1.isArray(source)) { + return source.slice(); + } + return source; + } + function mergeDeepProperties(a, b2, prop, caseless) { + if (!utils$1.isUndefined(b2)) { + return getMergedValue(a, b2, prop, caseless); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(void 0, a, prop, caseless); + } + } + function valueFromConfig2(a, b2) { + if (!utils$1.isUndefined(b2)) { + return getMergedValue(void 0, b2); + } + } + function defaultToConfig2(a, b2) { + if (!utils$1.isUndefined(b2)) { + return getMergedValue(void 0, b2); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(void 0, a); + } + } + function mergeDirectKeys(a, b2, prop) { + if (prop in config22) { + return getMergedValue(a, b2); + } else if (prop in config1) { + return getMergedValue(void 0, a); + } + } + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b2, prop) => mergeDeepProperties(headersToObject2(a), headersToObject2(b2), prop, true) + }; + utils$1.forEach(Object.keys(Object.assign({}, config1, config22)), function computeConfigValue(prop) { + const merge3 = mergeMap[prop] || mergeDeepProperties; + const configValue = merge3(config1[prop], config22[prop], prop); + utils$1.isUndefined(configValue) && merge3 !== mergeDirectKeys || (config3[prop] = configValue); + }); + return config3; + } + var resolveConfig = (config3) => { + const newConfig = mergeConfig3({}, config3); + let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; + newConfig.headers = headers = AxiosHeaders$1.from(headers); + newConfig.url = buildURL2(buildFullPath2(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config3.params, config3.paramsSerializer); + if (auth) { + headers.set( + "Authorization", + "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : "")) + ); + } + let contentType; + if (utils$1.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(void 0); + } else if ((contentType = headers.getContentType()) !== false) { + const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; + headers.setContentType([type || "multipart/form-data", ...tokens].join("; ")); + } + } + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) { + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + return newConfig; + }; + var isXHRAdapterSupported2 = typeof XMLHttpRequest !== "undefined"; + var xhrAdapter = isXHRAdapterSupported2 && function(config3) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config3); + let requestData = _config.data; + const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); + let { responseType, onUploadProgress, onDownloadProgress } = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + function done() { + flushUpload && flushUpload(); + flushDownload && flushDownload(); + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + _config.signal && _config.signal.removeEventListener("abort", onCanceled); + } + let request = new XMLHttpRequest(); + request.open(_config.method.toUpperCase(), _config.url, true); + request.timeout = _config.timeout; + function onloadend() { + if (!request) { + return; + } + const responseHeaders = AxiosHeaders$1.from( + "getAllResponseHeaders" in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config3, + request + }; + settle2(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + request = null; + } + if ("onloadend" in request) { + request.onloadend = onloadend; + } else { + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { + return; + } + setTimeout(onloadend); + }; + } + request.onabort = function handleAbort() { + if (!request) { + return; + } + reject(new AxiosError3("Request aborted", AxiosError3.ECONNABORTED, config3, request)); + request = null; + }; + request.onerror = function handleError() { + reject(new AxiosError3("Network Error", AxiosError3.ERR_NETWORK, config3, request)); + request = null; + }; + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = _config.transitional || transitionalDefaults; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new AxiosError3( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError3.ETIMEDOUT : AxiosError3.ECONNABORTED, + config3, + request + )); + request = null; + }; + requestData === void 0 && requestHeaders.setContentType(null); + if ("setRequestHeader" in request) { + utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + if (!utils$1.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + if (responseType && responseType !== "json") { + request.responseType = _config.responseType; + } + if (onDownloadProgress) { + [downloadThrottled, flushDownload] = progressEventReducer2(onDownloadProgress, true); + request.addEventListener("progress", downloadThrottled); + } + if (onUploadProgress && request.upload) { + [uploadThrottled, flushUpload] = progressEventReducer2(onUploadProgress); + request.upload.addEventListener("progress", uploadThrottled); + request.upload.addEventListener("loadend", flushUpload); + } + if (_config.cancelToken || _config.signal) { + onCanceled = (cancel) => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError3(null, config3, request) : cancel); + request.abort(); + request = null; + }; + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled); + } + } + const protocol = parseProtocol2(_config.url); + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError3("Unsupported protocol " + protocol + ":", AxiosError3.ERR_BAD_REQUEST, config3)); + return; + } + request.send(requestData || null); + }); + }; + var composeSignals2 = (signals, timeout) => { + const { length } = signals = signals ? signals.filter(Boolean) : []; + if (timeout || length) { + let controller = new AbortController(); + let aborted; + const onabort = function(reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof AxiosError3 ? err : new CanceledError3(err instanceof Error ? err.message : err)); + } + }; + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new AxiosError3(`timeout ${timeout} of ms exceeded`, AxiosError3.ETIMEDOUT)); + }, timeout); + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach((signal2) => { + signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort); + }); + signals = null; + } + }; + signals.forEach((signal2) => signal2.addEventListener("abort", onabort)); + const { signal } = controller; + signal.unsubscribe = () => utils$1.asap(unsubscribe); + return signal; + } + }; + var composeSignals$1 = composeSignals2; + var streamChunk2 = function* (chunk, chunkSize) { + let len = chunk.byteLength; + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + let pos = 0; + let end; + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } + }; + var readBytes2 = async function* (iterable, chunkSize) { + for await (const chunk of readStream2(iterable)) { + yield* streamChunk2(chunk, chunkSize); + } + }; + var readStream2 = async function* (stream5) { + if (stream5[Symbol.asyncIterator]) { + yield* stream5; + return; + } + const reader = stream5.getReader(); + try { + for (; ; ) { + const { done, value } = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } + }; + var trackStream2 = (stream5, chunkSize, onProgress, onFinish) => { + const iterator3 = readBytes2(stream5, chunkSize); + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + }; + return new ReadableStream({ + async pull(controller) { + try { + const { done: done2, value } = await iterator3.next(); + if (done2) { + _onFinish(); + controller.close(); + return; + } + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator3.return(); + } + }, { + highWaterMark: 2 + }); + }; + var isFetchSupported2 = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function"; + var isReadableStreamSupported2 = isFetchSupported2 && typeof ReadableStream === "function"; + var encodeText2 = isFetchSupported2 && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder5) => (str) => encoder5.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Response(str).arrayBuffer())); + var test2 = (fn2, ...args) => { + try { + return !!fn2(...args); + } catch (e) { + return false; + } + }; + var supportsRequestStream2 = isReadableStreamSupported2 && test2(() => { + let duplexAccessed = false; + const hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: "POST", + get duplex() { + duplexAccessed = true; + return "half"; + } + }).headers.has("Content-Type"); + return duplexAccessed && !hasContentType; + }); + var DEFAULT_CHUNK_SIZE2 = 64 * 1024; + var supportsResponseStream2 = isReadableStreamSupported2 && test2(() => utils$1.isReadableStream(new Response("").body)); + var resolvers2 = { + stream: supportsResponseStream2 && ((res) => res.body) + }; + isFetchSupported2 && ((res) => { + ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => { + !resolvers2[type] && (resolvers2[type] = utils$1.isFunction(res[type]) ? (res2) => res2[type]() : (_, config3) => { + throw new AxiosError3(`Response type '${type}' is not supported`, AxiosError3.ERR_NOT_SUPPORT, config3); + }); + }); + })(new Response()); + var getBodyLength2 = async (body) => { + if (body == null) { + return 0; + } + if (utils$1.isBlob(body)) { + return body.size; + } + if (utils$1.isSpecCompliantForm(body)) { + const _request = new Request(platform.origin, { + method: "POST", + body + }); + return (await _request.arrayBuffer()).byteLength; + } + if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { + return body.byteLength; + } + if (utils$1.isURLSearchParams(body)) { + body = body + ""; + } + if (utils$1.isString(body)) { + return (await encodeText2(body)).byteLength; + } + }; + var resolveBodyLength2 = async (headers, body) => { + const length = utils$1.toFiniteNumber(headers.getContentLength()); + return length == null ? getBodyLength2(body) : length; + }; + var fetchAdapter = isFetchSupported2 && (async (config3) => { + let { + url: url3, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = "same-origin", + fetchOptions + } = resolveConfig(config3); + responseType = responseType ? (responseType + "").toLowerCase() : "text"; + let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + let request; + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + let requestContentLength; + try { + if (onUploadProgress && supportsRequestStream2 && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength2(headers, data)) !== 0) { + let _request = new Request(url3, { + method: "POST", + body: data, + duplex: "half" + }); + let contentTypeHeader; + if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) { + headers.setContentType(contentTypeHeader); + } + if (_request.body) { + const [onProgress, flush] = progressEventDecorator2( + requestContentLength, + progressEventReducer2(asyncDecorator2(onUploadProgress)) + ); + data = trackStream2(_request.body, DEFAULT_CHUNK_SIZE2, onProgress, flush); + } + } + if (!utils$1.isString(withCredentials)) { + withCredentials = withCredentials ? "include" : "omit"; + } + const isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url3, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : void 0 + }); + let response = await fetch(request); + const isStreamResponse = supportsResponseStream2 && (responseType === "stream" || responseType === "response"); + if (supportsResponseStream2 && (onDownloadProgress || isStreamResponse && unsubscribe)) { + const options = {}; + ["status", "statusText", "headers"].forEach((prop) => { + options[prop] = response[prop]; + }); + const responseContentLength = utils$1.toFiniteNumber(response.headers.get("content-length")); + const [onProgress, flush] = onDownloadProgress && progressEventDecorator2( + responseContentLength, + progressEventReducer2(asyncDecorator2(onDownloadProgress), true) + ) || []; + response = new Response( + trackStream2(response.body, DEFAULT_CHUNK_SIZE2, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + responseType = responseType || "text"; + let responseData = await resolvers2[utils$1.findKey(resolvers2, responseType) || "text"](response, config3); + !isStreamResponse && unsubscribe && unsubscribe(); + return await new Promise((resolve, reject) => { + settle2(resolve, reject, { + data: responseData, + headers: AxiosHeaders$1.from(response.headers), + status: response.status, + statusText: response.statusText, + config: config3, + request + }); + }); + } catch (err) { + unsubscribe && unsubscribe(); + if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError3("Network Error", AxiosError3.ERR_NETWORK, config3, request), + { + cause: err.cause || err + } + ); + } + throw AxiosError3.from(err, err && err.code, config3, request); + } + }); + var knownAdapters2 = { + http: httpAdapter2, + xhr: xhrAdapter, + fetch: fetchAdapter + }; + utils$1.forEach(knownAdapters2, (fn2, value) => { + if (fn2) { + try { + Object.defineProperty(fn2, "name", { value }); + } catch (e) { + } + Object.defineProperty(fn2, "adapterName", { value }); + } + }); + var renderReason2 = (reason) => `- ${reason}`; + var isResolvedHandle2 = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; + var adapters = { + getAdapter: (adapters2) => { + adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2]; + const { length } = adapters2; + let nameOrAdapter; + let adapter; + const rejectedReasons = {}; + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters2[i]; + let id2; + adapter = nameOrAdapter; + if (!isResolvedHandle2(nameOrAdapter)) { + adapter = knownAdapters2[(id2 = String(nameOrAdapter)).toLowerCase()]; + if (adapter === void 0) { + throw new AxiosError3(`Unknown adapter '${id2}'`); + } + } + if (adapter) { + break; + } + rejectedReasons[id2 || "#" + i] = adapter; + } + if (!adapter) { + const reasons = Object.entries(rejectedReasons).map( + ([id2, state]) => `adapter ${id2} ` + (state === false ? "is not supported by the environment" : "is not available in the build") + ); + let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason2).join("\n") : " " + renderReason2(reasons[0]) : "as no adapter specified"; + throw new AxiosError3( + `There is no suitable adapter to dispatch the request ` + s, + "ERR_NOT_SUPPORT" + ); + } + return adapter; + }, + adapters: knownAdapters2 + }; + function throwIfCancellationRequested2(config3) { + if (config3.cancelToken) { + config3.cancelToken.throwIfRequested(); + } + if (config3.signal && config3.signal.aborted) { + throw new CanceledError3(null, config3); + } + } + function dispatchRequest2(config3) { + throwIfCancellationRequested2(config3); + config3.headers = AxiosHeaders$1.from(config3.headers); + config3.data = transformData2.call( + config3, + config3.transformRequest + ); + if (["post", "put", "patch"].indexOf(config3.method) !== -1) { + config3.headers.setContentType("application/x-www-form-urlencoded", false); + } + const adapter = adapters.getAdapter(config3.adapter || defaults$1.adapter); + return adapter(config3).then(function onAdapterResolution(response) { + throwIfCancellationRequested2(config3); + response.data = transformData2.call( + config3, + config3.transformResponse, + response + ); + response.headers = AxiosHeaders$1.from(response.headers); + return response; + }, function onAdapterRejection(reason) { + if (!isCancel3(reason)) { + throwIfCancellationRequested2(config3); + if (reason && reason.response) { + reason.response.data = transformData2.call( + config3, + config3.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + } + } + return Promise.reject(reason); + }); + } + var validators$1 = {}; + ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => { + validators$1[type] = function validator2(thing) { + return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type; + }; + }); + var deprecatedWarnings2 = {}; + validators$1.transitional = function transitional2(validator2, version4, message) { + function formatMessage(opt, desc) { + return "[Axios v" + VERSION3 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); + } + return (value, opt, opts) => { + if (validator2 === false) { + throw new AxiosError3( + formatMessage(opt, " has been removed" + (version4 ? " in " + version4 : "")), + AxiosError3.ERR_DEPRECATED + ); + } + if (version4 && !deprecatedWarnings2[opt]) { + deprecatedWarnings2[opt] = true; + console.warn( + formatMessage( + opt, + " has been deprecated since v" + version4 + " and will be removed in the near future" + ) + ); + } + return validator2 ? validator2(value, opt, opts) : true; + }; + }; + validators$1.spelling = function spelling2(correctSpelling) { + return (value, opt) => { + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + }; + }; + function assertOptions2(options, schema, allowUnknown) { + if (typeof options !== "object") { + throw new AxiosError3("options must be an object", AxiosError3.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator2 = schema[opt]; + if (validator2) { + const value = options[opt]; + const result = value === void 0 || validator2(value, opt, options); + if (result !== true) { + throw new AxiosError3("option " + opt + " must be " + result, AxiosError3.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError3("Unknown option " + opt, AxiosError3.ERR_BAD_OPTION); + } + } + } + var validator = { + assertOptions: assertOptions2, + validators: validators$1 + }; + var validators3 = validator.validators; + var Axios3 = class { + constructor(instanceConfig) { + this.defaults = instanceConfig || {}; + this.interceptors = { + request: new InterceptorManager$1(), + response: new InterceptorManager$1() + }; + } + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config3) { + try { + return await this._request(configOrUrl, config3); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error(); + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; + try { + if (!err.stack) { + err.stack = stack; + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { + err.stack += "\n" + stack; + } + } catch (e) { + } + } + throw err; + } + } + _request(configOrUrl, config3) { + if (typeof configOrUrl === "string") { + config3 = config3 || {}; + config3.url = configOrUrl; + } else { + config3 = configOrUrl || {}; + } + config3 = mergeConfig3(this.defaults, config3); + const { transitional: transitional2, paramsSerializer, headers } = config3; + if (transitional2 !== void 0) { + validator.assertOptions(transitional2, { + silentJSONParsing: validators3.transitional(validators3.boolean), + forcedJSONParsing: validators3.transitional(validators3.boolean), + clarifyTimeoutError: validators3.transitional(validators3.boolean) + }, false); + } + if (paramsSerializer != null) { + if (utils$1.isFunction(paramsSerializer)) { + config3.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions(paramsSerializer, { + encode: validators3.function, + serialize: validators3.function + }, true); + } + } + if (config3.allowAbsoluteUrls !== void 0) ; + else if (this.defaults.allowAbsoluteUrls !== void 0) { + config3.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; + } else { + config3.allowAbsoluteUrls = true; + } + validator.assertOptions(config3, { + baseUrl: validators3.spelling("baseURL"), + withXsrfToken: validators3.spelling("withXSRFToken") + }, true); + config3.method = (config3.method || this.defaults.method || "get").toLowerCase(); + let contextHeaders = headers && utils$1.merge( + headers.common, + headers[config3.method] + ); + headers && utils$1.forEach( + ["delete", "get", "head", "post", "put", "patch", "common"], + (method) => { + delete headers[method]; + } + ); + config3.headers = AxiosHeaders$1.concat(contextHeaders, headers); + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config3) === false) { + return; + } + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + let promise; + let i = 0; + let len; + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest2.bind(this), void 0]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + promise = Promise.resolve(config3); + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + return promise; + } + len = requestInterceptorChain.length; + let newConfig = config3; + i = 0; + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + try { + promise = dispatchRequest2.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + i = 0; + len = responseInterceptorChain.length; + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + return promise; + } + getUri(config3) { + config3 = mergeConfig3(this.defaults, config3); + const fullPath = buildFullPath2(config3.baseURL, config3.url, config3.allowAbsoluteUrls); + return buildURL2(fullPath, config3.params, config3.paramsSerializer); + } + }; + utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData2(method) { + Axios3.prototype[method] = function(url3, config3) { + return this.request(mergeConfig3(config3 || {}, { + method, + url: url3, + data: (config3 || {}).data + })); + }; + }); + utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData2(method) { + function generateHTTPMethod(isForm) { + return function httpMethod(url3, data, config3) { + return this.request(mergeConfig3(config3 || {}, { + method, + headers: isForm ? { + "Content-Type": "multipart/form-data" + } : {}, + url: url3, + data + })); + }; + } + Axios3.prototype[method] = generateHTTPMethod(); + Axios3.prototype[method + "Form"] = generateHTTPMethod(true); + }); + var Axios$1 = Axios3; + var CancelToken3 = class _CancelToken { + constructor(executor) { + if (typeof executor !== "function") { + throw new TypeError("executor must be a function."); + } + let resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + const token = this; + this.promise.then((cancel) => { + if (!token._listeners) return; + let i = token._listeners.length; + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + this.promise.then = (onfulfilled) => { + let _resolve; + const promise = new Promise((resolve) => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + return promise; + }; + executor(function cancel(message, config3, request) { + if (token.reason) { + return; + } + token.reason = new CanceledError3(message, config3, request); + resolvePromise(token.reason); + }); + } + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + /** + * Subscribe to the cancel signal + */ + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + /** + * Unsubscribe from the cancel signal + */ + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index2 = this._listeners.indexOf(listener); + if (index2 !== -1) { + this._listeners.splice(index2, 1); + } + } + toAbortSignal() { + const controller = new AbortController(); + const abort = (err) => { + controller.abort(err); + }; + this.subscribe(abort); + controller.signal.unsubscribe = () => this.unsubscribe(abort); + return controller.signal; + } + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new _CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; + } + }; + var CancelToken$1 = CancelToken3; + function spread3(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; + } + function isAxiosError3(payload) { + return utils$1.isObject(payload) && payload.isAxiosError === true; + } + var HttpStatusCode3 = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511 + }; + Object.entries(HttpStatusCode3).forEach(([key, value]) => { + HttpStatusCode3[value] = key; + }); + var HttpStatusCode$1 = HttpStatusCode3; + function createInstance2(defaultConfig) { + const context = new Axios$1(defaultConfig); + const instance = bind2(Axios$1.prototype.request, context); + utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true }); + utils$1.extend(instance, context, null, { allOwnKeys: true }); + instance.create = function create(instanceConfig) { + return createInstance2(mergeConfig3(defaultConfig, instanceConfig)); + }; + return instance; + } + var axios2 = createInstance2(defaults$1); + axios2.Axios = Axios$1; + axios2.CanceledError = CanceledError3; + axios2.CancelToken = CancelToken$1; + axios2.isCancel = isCancel3; + axios2.VERSION = VERSION3; + axios2.toFormData = toFormData3; + axios2.AxiosError = AxiosError3; + axios2.Cancel = axios2.CanceledError; + axios2.all = function all3(promises) { + return Promise.all(promises); + }; + axios2.spread = spread3; + axios2.isAxiosError = isAxiosError3; + axios2.mergeConfig = mergeConfig3; + axios2.AxiosHeaders = AxiosHeaders$1; + axios2.formToJSON = (thing) => formDataToJSON2(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); + axios2.getAdapter = adapters.getAdapter; + axios2.HttpStatusCode = HttpStatusCode$1; + axios2.default = axios2; + module2.exports = axios2; + } +}); + +// node_modules/is-electron/index.js +var require_is_electron = __commonJS({ + "node_modules/is-electron/index.js"(exports2, module2) { + function isElectron() { + if (typeof window !== "undefined" && typeof window.process === "object" && window.process.type === "renderer") { + return true; + } + if (typeof process !== "undefined" && typeof process.versions === "object" && !!process.versions.electron) { + return true; + } + if (typeof navigator === "object" && typeof navigator.userAgent === "string" && navigator.userAgent.indexOf("Electron") >= 0) { + return true; + } + return false; + } + module2.exports = isElectron; + } +}); + +// node_modules/p-queue/node_modules/eventemitter3/index.js +var require_eventemitter3 = __commonJS({ + "node_modules/p-queue/node_modules/eventemitter3/index.js"(exports2, module2) { + "use strict"; + var has = Object.prototype.hasOwnProperty; + var prefix = "~"; + function Events() { + } + if (Object.create) { + Events.prototype = /* @__PURE__ */ Object.create(null); + if (!new Events().__proto__) prefix = false; + } + function EE(fn2, context, once) { + this.fn = fn2; + this.context = context; + this.once = once || false; + } + function addListener(emitter, event, fn2, context, once) { + if (typeof fn2 !== "function") { + throw new TypeError("The listener must be a function"); + } + var listener = new EE(fn2, context || emitter, once), evt = prefix ? prefix + event : event; + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + return emitter; + } + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + function EventEmitter3() { + this._events = new Events(); + this._eventsCount = 0; + } + EventEmitter3.prototype.eventNames = function eventNames() { + var names = [], events, name; + if (this._eventsCount === 0) return names; + for (name in events = this._events) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + return names; + }; + EventEmitter3.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event, handlers = this._events[evt]; + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + for (var i = 0, l = handlers.length, ee2 = new Array(l); i < l; i++) { + ee2[i] = handlers[i].fn; + } + return ee2; + }; + EventEmitter3.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event, listeners = this._events[evt]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + EventEmitter3.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return false; + var listeners = this._events[evt], len = arguments.length, args, i; + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); + switch (len) { + case 1: + return listeners.fn.call(listeners.context), true; + case 2: + return listeners.fn.call(listeners.context, a1), true; + case 3: + return listeners.fn.call(listeners.context, a1, a2), true; + case 4: + return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: + return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: + return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + for (i = 1, args = new Array(len - 1); i < len; i++) { + args[i - 1] = arguments[i]; + } + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length, j2; + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); + switch (len) { + case 1: + listeners[i].fn.call(listeners[i].context); + break; + case 2: + listeners[i].fn.call(listeners[i].context, a1); + break; + case 3: + listeners[i].fn.call(listeners[i].context, a1, a2); + break; + case 4: + listeners[i].fn.call(listeners[i].context, a1, a2, a3); + break; + default: + if (!args) for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) { + args[j2 - 1] = arguments[j2]; + } + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + return true; + }; + EventEmitter3.prototype.on = function on2(event, fn2, context) { + return addListener(this, event, fn2, context, false); + }; + EventEmitter3.prototype.once = function once(event, fn2, context) { + return addListener(this, event, fn2, context, true); + }; + EventEmitter3.prototype.removeListener = function removeListener(event, fn2, context, once) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return this; + if (!fn2) { + clearEvent(this, evt); + return this; + } + var listeners = this._events[evt]; + if (listeners.fn) { + if (listeners.fn === fn2 && (!once || listeners.once) && (!context || listeners.context === context)) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if (listeners[i].fn !== fn2 || once && !listeners[i].once || context && listeners[i].context !== context) { + events.push(listeners[i]); + } + } + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + return this; + }; + EventEmitter3.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + return this; + }; + EventEmitter3.prototype.off = EventEmitter3.prototype.removeListener; + EventEmitter3.prototype.addListener = EventEmitter3.prototype.on; + EventEmitter3.prefixed = prefix; + EventEmitter3.EventEmitter = EventEmitter3; + if ("undefined" !== typeof module2) { + module2.exports = EventEmitter3; + } + } +}); + +// node_modules/p-finally/index.js +var require_p_finally = __commonJS({ + "node_modules/p-finally/index.js"(exports2, module2) { + "use strict"; + module2.exports = (promise, onFinally) => { + onFinally = onFinally || (() => { + }); + return promise.then( + (val) => new Promise((resolve) => { + resolve(onFinally()); + }).then(() => val), + (err) => new Promise((resolve) => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); + }; + } +}); + +// node_modules/p-timeout/index.js +var require_p_timeout = __commonJS({ + "node_modules/p-timeout/index.js"(exports2, module2) { + "use strict"; + var pFinally = require_p_finally(); + var TimeoutError2 = class extends Error { + constructor(message) { + super(message); + this.name = "TimeoutError"; + } + }; + var pTimeout = (promise, milliseconds, fallback2) => new Promise((resolve, reject) => { + if (typeof milliseconds !== "number" || milliseconds < 0) { + throw new TypeError("Expected `milliseconds` to be a positive number"); + } + if (milliseconds === Infinity) { + resolve(promise); + return; + } + const timer = setTimeout(() => { + if (typeof fallback2 === "function") { + try { + resolve(fallback2()); + } catch (error) { + reject(error); + } + return; + } + const message = typeof fallback2 === "string" ? fallback2 : `Promise timed out after ${milliseconds} milliseconds`; + const timeoutError = fallback2 instanceof Error ? fallback2 : new TimeoutError2(message); + if (typeof promise.cancel === "function") { + promise.cancel(); + } + reject(timeoutError); + }, milliseconds); + pFinally( + // eslint-disable-next-line promise/prefer-await-to-then + promise.then(resolve, reject), + () => { + clearTimeout(timer); + } + ); + }); + module2.exports = pTimeout; + module2.exports.default = pTimeout; + module2.exports.TimeoutError = TimeoutError2; + } +}); + +// node_modules/p-queue/dist/lower-bound.js +var require_lower_bound = __commonJS({ + "node_modules/p-queue/dist/lower-bound.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + function lowerBound(array, value, comparator) { + let first = 0; + let count = array.length; + while (count > 0) { + const step = count / 2 | 0; + let it2 = first + step; + if (comparator(array[it2], value) <= 0) { + first = ++it2; + count -= step + 1; + } else { + count = step; + } + } + return first; + } + exports2.default = lowerBound; + } +}); + +// node_modules/p-queue/dist/priority-queue.js +var require_priority_queue = __commonJS({ + "node_modules/p-queue/dist/priority-queue.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var lower_bound_1 = require_lower_bound(); + var PriorityQueue = class { + constructor() { + this._queue = []; + } + enqueue(run, options) { + options = Object.assign({ priority: 0 }, options); + const element = { + priority: options.priority, + run + }; + if (this.size && this._queue[this.size - 1].priority >= options.priority) { + this._queue.push(element); + return; + } + const index2 = lower_bound_1.default(this._queue, element, (a, b2) => b2.priority - a.priority); + this._queue.splice(index2, 0, element); + } + dequeue() { + const item = this._queue.shift(); + return item === null || item === void 0 ? void 0 : item.run; + } + filter(options) { + return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); + } + get size() { + return this._queue.length; + } + }; + exports2.default = PriorityQueue; + } +}); + +// node_modules/p-queue/dist/index.js +var require_dist = __commonJS({ + "node_modules/p-queue/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + var EventEmitter3 = require_eventemitter3(); + var p_timeout_1 = require_p_timeout(); + var priority_queue_1 = require_priority_queue(); + var empty2 = () => { + }; + var timeoutError = new p_timeout_1.TimeoutError(); + var PQueue = class extends EventEmitter3 { + constructor(options) { + var _a2, _b, _c2, _d2; + super(); + this._intervalCount = 0; + this._intervalEnd = 0; + this._pendingCount = 0; + this._resolveEmpty = empty2; + this._resolveIdle = empty2; + options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); + if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { + throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a2 = options.intervalCap) === null || _a2 === void 0 ? void 0 : _a2.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`); + } + if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) { + throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d2 = (_c2 = options.interval) === null || _c2 === void 0 ? void 0 : _c2.toString()) !== null && _d2 !== void 0 ? _d2 : ""}\` (${typeof options.interval})`); + } + this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; + this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; + this._intervalCap = options.intervalCap; + this._interval = options.interval; + this._queue = new options.queueClass(); + this._queueClass = options.queueClass; + this.concurrency = options.concurrency; + this._timeout = options.timeout; + this._throwOnTimeout = options.throwOnTimeout === true; + this._isPaused = options.autoStart === false; + } + get _doesIntervalAllowAnother() { + return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + } + get _doesConcurrentAllowAnother() { + return this._pendingCount < this._concurrency; + } + _next() { + this._pendingCount--; + this._tryToStartAnother(); + this.emit("next"); + } + _resolvePromises() { + this._resolveEmpty(); + this._resolveEmpty = empty2; + if (this._pendingCount === 0) { + this._resolveIdle(); + this._resolveIdle = empty2; + this.emit("idle"); + } + } + _onResumeInterval() { + this._onInterval(); + this._initializeIntervalIfNeeded(); + this._timeoutId = void 0; + } + _isIntervalPaused() { + const now = Date.now(); + if (this._intervalId === void 0) { + const delay = this._intervalEnd - now; + if (delay < 0) { + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + } else { + if (this._timeoutId === void 0) { + this._timeoutId = setTimeout(() => { + this._onResumeInterval(); + }, delay); + } + return true; + } + } + return false; + } + _tryToStartAnother() { + if (this._queue.size === 0) { + if (this._intervalId) { + clearInterval(this._intervalId); + } + this._intervalId = void 0; + this._resolvePromises(); + return false; + } + if (!this._isPaused) { + const canInitializeInterval = !this._isIntervalPaused(); + if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { + const job = this._queue.dequeue(); + if (!job) { + return false; + } + this.emit("active"); + job(); + if (canInitializeInterval) { + this._initializeIntervalIfNeeded(); + } + return true; + } + } + return false; + } + _initializeIntervalIfNeeded() { + if (this._isIntervalIgnored || this._intervalId !== void 0) { + return; + } + this._intervalId = setInterval(() => { + this._onInterval(); + }, this._interval); + this._intervalEnd = Date.now() + this._interval; + } + _onInterval() { + if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { + clearInterval(this._intervalId); + this._intervalId = void 0; + } + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + this._processQueue(); + } + /** + Executes all queued functions until it reaches the limit. + */ + _processQueue() { + while (this._tryToStartAnother()) { + } + } + get concurrency() { + return this._concurrency; + } + set concurrency(newConcurrency) { + if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + } + this._concurrency = newConcurrency; + this._processQueue(); + } + /** + Adds a sync or async task to the queue. Always returns a promise. + */ + async add(fn2, options = {}) { + return new Promise((resolve, reject) => { + const run = async () => { + this._pendingCount++; + this._intervalCount++; + try { + const operation = this._timeout === void 0 && options.timeout === void 0 ? fn2() : p_timeout_1.default(Promise.resolve(fn2()), options.timeout === void 0 ? this._timeout : options.timeout, () => { + if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) { + reject(timeoutError); + } + return void 0; + }); + resolve(await operation); + } catch (error) { + reject(error); + } + this._next(); + }; + this._queue.enqueue(run, options); + this._tryToStartAnother(); + this.emit("add"); + }); + } + /** + Same as `.add()`, but accepts an array of sync or async functions. + + @returns A promise that resolves when all functions are resolved. + */ + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); + } + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this._isPaused) { + return this; + } + this._isPaused = false; + this._processQueue(); + return this; + } + /** + Put queue execution on hold. + */ + pause() { + this._isPaused = true; + } + /** + Clear the queue. + */ + clear() { + this._queue = new this._queueClass(); + } + /** + Can be called multiple times. Useful if you for example add additional items at a later time. + + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + if (this._queue.size === 0) { + return; + } + return new Promise((resolve) => { + const existingResolve = this._resolveEmpty; + this._resolveEmpty = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + if (this._pendingCount === 0 && this._queue.size === 0) { + return; + } + return new Promise((resolve) => { + const existingResolve = this._resolveIdle; + this._resolveIdle = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + Size of the queue. + */ + get size() { + return this._queue.size; + } + /** + Size of the queue, filtered by the given options. + + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + return this._queue.filter(options).length; + } + /** + Number of pending promises. + */ + get pending() { + return this._pendingCount; + } + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this._isPaused; + } + get timeout() { + return this._timeout; + } + /** + Set the timeout for future operations. + */ + set timeout(milliseconds) { + this._timeout = milliseconds; + } + }; + exports2.default = PQueue; + } +}); + +// node_modules/retry/lib/retry_operation.js +var require_retry_operation = __commonJS({ + "node_modules/retry/lib/retry_operation.js"(exports2, module2) { + function RetryOperation(timeouts, options) { + if (typeof options === "boolean") { + options = { forever: options }; + } + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); + } + } + module2.exports = RetryOperation; + RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); + }; + RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } + this._timeouts = []; + this._cachedTimeouts = null; + }; + RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (!err) { + return false; + } + var currentTime = (/* @__PURE__ */ new Date()).getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error("RetryOperation timeout occurred")); + return false; + } + this._errors.push(err); + var timeout = this._timeouts.shift(); + if (timeout === void 0) { + if (this._cachedTimeouts) { + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } + } + var self2 = this; + this._timer = setTimeout(function() { + self2._attempts++; + if (self2._operationTimeoutCb) { + self2._timeout = setTimeout(function() { + self2._operationTimeoutCb(self2._attempts); + }, self2._operationTimeout); + if (self2._options.unref) { + self2._timeout.unref(); + } + } + self2._fn(self2._attempts); + }, timeout); + if (this._options.unref) { + this._timer.unref(); + } + return true; + }; + RetryOperation.prototype.attempt = function(fn2, timeoutOps) { + this._fn = fn2; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } + var self2 = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self2._operationTimeoutCb(); + }, self2._operationTimeout); + } + this._operationStart = (/* @__PURE__ */ new Date()).getTime(); + this._fn(this._attempts); + }; + RetryOperation.prototype.try = function(fn2) { + console.log("Using RetryOperation.try() is deprecated"); + this.attempt(fn2); + }; + RetryOperation.prototype.start = function(fn2) { + console.log("Using RetryOperation.start() is deprecated"); + this.attempt(fn2); + }; + RetryOperation.prototype.start = RetryOperation.prototype.try; + RetryOperation.prototype.errors = function() { + return this._errors; + }; + RetryOperation.prototype.attempts = function() { + return this._attempts; + }; + RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; + counts[message] = count; + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; + } + } + return mainError; + }; + } +}); + +// node_modules/retry/lib/retry.js +var require_retry = __commonJS({ + "node_modules/retry/lib/retry.js"(exports2) { + var RetryOperation = require_retry_operation(); + exports2.operation = function(options) { + var timeouts = exports2.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); + }; + exports2.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1e3, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } + if (opts.minTimeout > opts.maxTimeout) { + throw new Error("minTimeout is greater than maxTimeout"); + } + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); + } + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } + timeouts.sort(function(a, b2) { + return a - b2; + }); + return timeouts; + }; + exports2.createTimeout = function(attempt, opts) { + var random = opts.randomize ? Math.random() + 1 : 1; + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + return timeout; + }; + exports2.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; + } + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === "function") { + methods.push(key); + } + } + } + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; + obj[method] = function retryWrapper(original2) { + var op2 = exports2.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + args.push(function(err) { + if (op2.retry(err)) { + return; + } + if (err) { + arguments[0] = op2.mainError(); + } + callback.apply(this, arguments); + }); + op2.attempt(function() { + original2.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } + }; + } +}); + +// node_modules/retry/index.js +var require_retry2 = __commonJS({ + "node_modules/retry/index.js"(exports2, module2) { + module2.exports = require_retry(); + } +}); + +// node_modules/p-retry/index.js +var require_p_retry = __commonJS({ + "node_modules/p-retry/index.js"(exports2, module2) { + "use strict"; + var retry = require_retry2(); + var networkErrorMsgs = [ + "Failed to fetch", + // Chrome + "NetworkError when attempting to fetch resource.", + // Firefox + "The Internet connection appears to be offline.", + // Safari + "Network request failed" + // `cross-fetch` + ]; + var AbortError = class extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({ message } = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } + this.name = "AbortError"; + this.message = message; + } + }; + var decorateErrorWithCounts = (error, attemptNumber, options) => { + const retriesLeft = options.retries - (attemptNumber - 1); + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; + }; + var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage); + var pRetry = (input, options) => new Promise((resolve, reject) => { + options = { + onFailedAttempt: () => { + }, + retries: 10, + ...options + }; + const operation = retry.operation(options); + operation.attempt(async (attemptNumber) => { + try { + resolve(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } + if (error instanceof AbortError) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); + try { + await options.onFailedAttempt(error); + } catch (error2) { + reject(error2); + return; + } + if (!operation.retry(error)) { + reject(operation.mainError()); + } + } + } + }); + }); + module2.exports = pRetry; + module2.exports.default = pRetry; + module2.exports.AbortError = AbortError; + } +}); + +// node_modules/@slack/web-api/dist/errors.js +var require_errors3 = __commonJS({ + "node_modules/@slack/web-api/dist/errors.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ErrorCode = void 0; + exports2.errorWithCode = errorWithCode; + exports2.requestErrorWithOriginal = requestErrorWithOriginal; + exports2.httpErrorFromResponse = httpErrorFromResponse; + exports2.platformErrorFromResult = platformErrorFromResult; + exports2.rateLimitedErrorWithDelay = rateLimitedErrorWithDelay; + var ErrorCode; + (function(ErrorCode2) { + ErrorCode2["RequestError"] = "slack_webapi_request_error"; + ErrorCode2["HTTPError"] = "slack_webapi_http_error"; + ErrorCode2["PlatformError"] = "slack_webapi_platform_error"; + ErrorCode2["RateLimitedError"] = "slack_webapi_rate_limited_error"; + ErrorCode2["FileUploadInvalidArgumentsError"] = "slack_webapi_file_upload_invalid_args_error"; + ErrorCode2["FileUploadReadFileDataError"] = "slack_webapi_file_upload_read_file_data_error"; + })(ErrorCode || (exports2.ErrorCode = ErrorCode = {})); + function errorWithCode(error, code) { + const codedError = error; + codedError.code = code; + return codedError; + } + function requestErrorWithOriginal(original, attachOriginal) { + const error = errorWithCode(new Error(`A request error occurred: ${original.message}`), ErrorCode.RequestError); + if (attachOriginal) { + error.original = original; + } + return error; + } + function httpErrorFromResponse(response) { + const error = errorWithCode(new Error(`An HTTP protocol error occurred: statusCode = ${response.status}`), ErrorCode.HTTPError); + error.statusCode = response.status; + error.statusMessage = response.statusText; + const nonNullHeaders = {}; + for (const k2 of Object.keys(response.headers)) { + if (k2 && response.headers[k2]) { + nonNullHeaders[k2] = response.headers[k2]; + } + } + error.headers = nonNullHeaders; + error.body = response.data; + return error; + } + function platformErrorFromResult(result) { + const error = errorWithCode(new Error(`An API error occurred: ${result.error}`), ErrorCode.PlatformError); + error.data = result; + return error; + } + function rateLimitedErrorWithDelay(retrySec) { + const error = errorWithCode(new Error(`A rate-limit has been reached, you may retry this request in ${retrySec} seconds`), ErrorCode.RateLimitedError); + error.retryAfter = retrySec; + return error; + } + } +}); + +// node_modules/@slack/web-api/dist/file-upload.js +var require_file_upload = __commonJS({ + "node_modules/@slack/web-api/dist/file-upload.js"(exports2) { + "use strict"; + var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getFileUploadJob = getFileUploadJob; + exports2.getMultipleFileUploadJobs = getMultipleFileUploadJobs; + exports2.getFileData = getFileData; + exports2.getFileDataLength = getFileDataLength; + exports2.getFileDataAsStream = getFileDataAsStream; + exports2.getAllFileUploadsToComplete = getAllFileUploadsToComplete; + exports2.warnIfNotUsingFilesUploadV2 = warnIfNotUsingFilesUploadV2; + exports2.warnIfChannels = warnIfChannels; + exports2.errorIfChannelsCsv = errorIfChannelsCsv; + exports2.errorIfInvalidOrMissingFileData = errorIfInvalidOrMissingFileData; + exports2.warnIfMissingOrInvalidFileNameAndDefault = warnIfMissingOrInvalidFileNameAndDefault; + exports2.warnIfLegacyFileType = warnIfLegacyFileType; + exports2.buildMissingFileIdError = buildMissingFileIdError; + exports2.buildFileSizeErrorMsg = buildFileSizeErrorMsg; + exports2.buildLegacyFileTypeWarning = buildLegacyFileTypeWarning; + exports2.buildMissingFileNameWarning = buildMissingFileNameWarning; + exports2.buildMissingExtensionWarning = buildMissingExtensionWarning; + exports2.buildLegacyMethodWarning = buildLegacyMethodWarning; + exports2.buildGeneralFilesUploadWarning = buildGeneralFilesUploadWarning; + exports2.buildFilesUploadMissingMessage = buildFilesUploadMissingMessage; + exports2.buildChannelsWarning = buildChannelsWarning; + exports2.buildMultipleChannelsErrorMsg = buildMultipleChannelsErrorMsg; + exports2.buildInvalidFilesUploadParamError = buildInvalidFilesUploadParamError; + var node_fs_1 = __require("node:fs"); + var node_stream_1 = __require("node:stream"); + var errors_1 = require_errors3(); + function getFileUploadJob(options, logger) { + return __awaiter(this, void 0, void 0, function* () { + var _a2, _b, _c2, _d2; + warnIfLegacyFileType(options, logger); + warnIfChannels(options, logger); + errorIfChannelsCsv(options); + const fileName = warnIfMissingOrInvalidFileNameAndDefault(options, logger); + const fileData = yield getFileData(options); + const fileDataBytesLength = getFileDataLength(fileData); + const fileUploadJob = { + // supplied by user + alt_text: options.alt_text, + channel_id: (_a2 = options.channels) !== null && _a2 !== void 0 ? _a2 : options.channel_id, + filename: (_b = options.filename) !== null && _b !== void 0 ? _b : fileName, + initial_comment: options.initial_comment, + snippet_type: options.snippet_type, + title: (_d2 = (_c2 = options.title) !== null && _c2 !== void 0 ? _c2 : options.filename) !== null && _d2 !== void 0 ? _d2 : fileName, + // default title to filename unless otherwise specified + // calculated + data: fileData, + length: fileDataBytesLength + }; + if ("thread_ts" in options) { + fileUploadJob.thread_ts = options.thread_ts; + } + if ("token" in options) { + fileUploadJob.token = options.token; + } + if ("content" in options) { + return Object.assign({ content: options.content }, fileUploadJob); + } + if ("file" in options) { + return Object.assign({ file: options.file }, fileUploadJob); + } + throw (0, errors_1.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + }); + } + function getMultipleFileUploadJobs(options, logger) { + return __awaiter(this, void 0, void 0, function* () { + if ("file_uploads" in options) { + return Promise.all(options.file_uploads.map((upload) => { + const { channel_id, channels, initial_comment, thread_ts } = upload; + if (channel_id || channels || initial_comment || thread_ts) { + throw (0, errors_1.errorWithCode)(new Error(buildInvalidFilesUploadParamError()), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } + const uploadJobArgs = Object.assign(Object.assign({}, upload), { channels: options.channels, channel_id: options.channel_id, initial_comment: options.initial_comment }); + if ("thread_ts" in options) { + uploadJobArgs.thread_ts = options.thread_ts; + } + if ("token" in options) { + uploadJobArgs.token = options.token; + } + if ("content" in upload) { + return getFileUploadJob(Object.assign({ content: upload.content }, uploadJobArgs), logger); + } + if ("file" in upload) { + return getFileUploadJob(Object.assign({ file: upload.file }, uploadJobArgs), logger); + } + throw (0, errors_1.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + })); + } + throw new Error(buildFilesUploadMissingMessage()); + }); + } + function getFileData(options) { + return __awaiter(this, void 0, void 0, function* () { + errorIfInvalidOrMissingFileData(options); + if ("file" in options) { + const { file } = options; + if (Buffer.isBuffer(file)) + return file; + if (typeof file === "string") { + try { + const dataBuffer = (0, node_fs_1.readFileSync)(file); + return dataBuffer; + } catch (error) { + throw (0, errors_1.errorWithCode)(new Error(`Unable to resolve file data for ${file}. Please supply a filepath string, or binary data Buffer or String directly.`), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } + } + const data = yield getFileDataAsStream(file); + if (data) + return data; + } + if ("content" in options) + return Buffer.from(options.content); + throw (0, errors_1.errorWithCode)(new Error("There was an issue getting the file data for the file or content supplied"), errors_1.ErrorCode.FileUploadReadFileDataError); + }); + } + function getFileDataLength(data) { + if (data) { + return Buffer.byteLength(data, "utf8"); + } + throw (0, errors_1.errorWithCode)(new Error(buildFileSizeErrorMsg()), errors_1.ErrorCode.FileUploadReadFileDataError); + } + function getFileDataAsStream(readable) { + return __awaiter(this, void 0, void 0, function* () { + const chunks = []; + return new Promise((resolve, reject) => { + readable.on("readable", () => { + let chunk = readable.read(); + while (chunk !== null) { + chunks.push(chunk); + chunk = readable.read(); + } + }); + readable.on("end", () => { + if (chunks.length > 0) { + const content = Buffer.concat(chunks); + resolve(content); + } else { + reject(Error("No data in supplied file")); + } + }); + }); + }); + } + function getAllFileUploadsToComplete(fileUploads) { + const toComplete = {}; + for (const upload of fileUploads) { + const { channel_id, thread_ts, initial_comment, file_id, title } = upload; + if (file_id) { + const compareString = `:::${channel_id}:::${thread_ts}:::${initial_comment}`; + if (!Object.prototype.hasOwnProperty.call(toComplete, compareString)) { + toComplete[compareString] = { + files: [{ id: file_id, title }], + channel_id, + initial_comment + }; + if (thread_ts && channel_id) { + const fileThreadDestinationArgument = { + channel_id, + thread_ts + }; + toComplete[compareString] = Object.assign(Object.assign({}, toComplete[compareString]), fileThreadDestinationArgument); + } + if ("token" in upload) { + toComplete[compareString].token = upload.token; + } + } else { + toComplete[compareString].files.push({ + id: file_id, + title + }); + } + } else { + throw new Error(buildMissingFileIdError()); + } + } + return toComplete; + } + function warnIfNotUsingFilesUploadV2(method, logger) { + const targetMethods = ["files.upload"]; + const isTargetMethod = targetMethods.includes(method); + if (method === "files.upload") + logger.warn(buildLegacyMethodWarning(method)); + if (isTargetMethod) + logger.info(buildGeneralFilesUploadWarning()); + } + function warnIfChannels(options, logger) { + if (options.channels) + logger.warn(buildChannelsWarning()); + } + function errorIfChannelsCsv(options) { + const channels = options.channels ? options.channels.split(",") : []; + if (channels.length > 1) { + throw (0, errors_1.errorWithCode)(new Error(buildMultipleChannelsErrorMsg()), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } + } + function errorIfInvalidOrMissingFileData(options) { + const hasFile = "file" in options; + const hasContent = "content" in options; + if (!(hasFile || hasContent) || hasFile && hasContent) { + throw (0, errors_1.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You cannot supply both"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } + if ("file" in options) { + const { file } = options; + if (file && !(typeof file === "string" || Buffer.isBuffer(file) || file instanceof node_stream_1.Readable)) { + throw (0, errors_1.errorWithCode)(new Error("file must be a valid string path, buffer or Readable"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } + } + if ("content" in options && options.content && typeof options.content !== "string") { + throw (0, errors_1.errorWithCode)(new Error("content must be a string"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } + } + function warnIfMissingOrInvalidFileNameAndDefault(options, logger) { + var _a2; + const DEFAULT_FILETYPE = "txt"; + const DEFAULT_FILENAME = `file.${(_a2 = options.filetype) !== null && _a2 !== void 0 ? _a2 : DEFAULT_FILETYPE}`; + const { filename } = options; + if (!filename) { + logger.warn(buildMissingFileNameWarning()); + return DEFAULT_FILENAME; + } + if (filename.split(".").length < 2) { + logger.warn(buildMissingExtensionWarning(filename)); + } + return filename; + } + function warnIfLegacyFileType(options, logger) { + if (options.filetype) { + logger.warn(buildLegacyFileTypeWarning()); + } + } + function buildMissingFileIdError() { + return "Missing required file id for file upload completion"; + } + function buildFileSizeErrorMsg() { + return "There was an issue calculating the size of your file"; + } + function buildLegacyFileTypeWarning() { + return "filetype is no longer a supported field in files.uploadV2. \nPlease remove this field. To indicate file type, please do so via the required filename property using the appropriate file extension, e.g. image.png, text.txt"; + } + function buildMissingFileNameWarning() { + return "filename is a required field for files.uploadV2. \n For backwards compatibility and ease of migration, defaulting the filename. For best experience and consistent unfurl behavior, you should set the filename property with correct file extension, e.g. image.png, text.txt"; + } + function buildMissingExtensionWarning(filename) { + return `filename supplied '${filename}' may be missing a proper extension. Missing extenions may result in unexpected unfurl behavior when shared`; + } + function buildLegacyMethodWarning(method) { + return `${method} may cause some issues like timeouts for relatively large files.`; + } + function buildGeneralFilesUploadWarning() { + return "Our latest recommendation is to use client.files.uploadV2() method, which is mostly compatible and much stabler, instead."; + } + function buildFilesUploadMissingMessage() { + return "Something went wrong with processing file_uploads"; + } + function buildChannelsWarning() { + return "Although the 'channels' parameter is still supported for smoother migration from legacy files.upload, we recommend using the new channel_id parameter with a single str value instead (e.g. 'C12345')."; + } + function buildMultipleChannelsErrorMsg() { + return "Sharing files with multiple channels is no longer supported in v2. Share files in each channel separately instead."; + } + function buildInvalidFilesUploadParamError() { + return "You may supply file_uploads only for a single channel, comment, thread respectively. Therefore, please supply any channel_id, initial_comment, thread_ts in the top-layer."; + } + } +}); + +// node_modules/@slack/web-api/dist/helpers.js +var require_helpers = __commonJS({ + "node_modules/@slack/web-api/dist/helpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.default = delay; + function delay(ms) { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); + } + } +}); + +// node_modules/@slack/web-api/package.json +var require_package3 = __commonJS({ + "node_modules/@slack/web-api/package.json"(exports2, module2) { + module2.exports = { + name: "@slack/web-api", + version: "7.9.2", + description: "Official library for using the Slack Platform's Web API", + author: "Slack Technologies, LLC", + license: "MIT", + keywords: ["slack", "web-api", "bot", "client", "http", "api", "proxy", "rate-limiting", "pagination"], + main: "dist/index.js", + types: "./dist/index.d.ts", + files: ["dist/**/*"], + engines: { + node: ">= 18", + npm: ">= 8.6.0" + }, + repository: "slackapi/node-slack-sdk", + homepage: "https://tools.slack.dev/node-slack-sdk/web-api", + publishConfig: { + access: "public" + }, + bugs: { + url: "https://github.com/slackapi/node-slack-sdk/issues" + }, + scripts: { + prepare: "npm run build", + build: "npm run build:clean && tsc", + "build:clean": "shx rm -rf ./dist ./coverage", + lint: "npx @biomejs/biome check .", + "lint:fix": "npx @biomejs/biome check --write .", + mocha: 'mocha --config ./test/.mocharc.json "./src/**/*.spec.ts"', + test: "npm run lint && npm run test:types && npm run test:integration && npm run test:unit", + "test:integration": "npm run build && node test/integration/commonjs-project/index.js && node test/integration/esm-project/index.mjs && npm run test:integration:ts", + "test:integration:ts": "cd test/integration/ts-4.7-project && npm i && npm run build", + "test:unit": "npm run build && c8 --config ./test/.c8rc.json npm run mocha", + "test:types": "tsd", + watch: "npx nodemon --watch 'src' --ext 'ts' --exec npm run build" + }, + dependencies: { + "@slack/logger": "^4.0.0", + "@slack/types": "^2.9.0", + "@types/node": ">=18.0.0", + "@types/retry": "0.12.0", + axios: "^1.8.3", + eventemitter3: "^5.0.1", + "form-data": "^4.0.0", + "is-electron": "2.2.2", + "is-stream": "^2", + "p-queue": "^6", + "p-retry": "^4", + retry: "^0.13.1" + }, + devDependencies: { + "@biomejs/biome": "^1.8.3", + "@tsconfig/recommended": "^1", + "@types/busboy": "^1.5.4", + "@types/chai": "^4", + "@types/mocha": "^10", + "@types/sinon": "^17", + busboy: "^1", + c8: "^10.1.2", + chai: "^4", + mocha: "^11", + "mocha-junit-reporter": "^2.2.1", + "mocha-multi-reporters": "^1.5.1", + nock: "^14", + shx: "^0.4.0", + sinon: "^20", + "source-map-support": "^0.5.21", + "ts-node": "^10", + tsd: "^0.32.0", + typescript: "5.8.3" + }, + tsd: { + directory: "test/types" + } + }; + } +}); + +// node_modules/@slack/web-api/dist/instrument.js +var require_instrument = __commonJS({ + "node_modules/@slack/web-api/dist/instrument.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; + } + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar2 = []; + for (var k2 in o2) if (Object.prototype.hasOwnProperty.call(o2, k2)) ar2[ar2.length] = k2; + return ar2; + }; + return ownKeys(o); + }; + return function(mod2) { + if (mod2 && mod2.__esModule) return mod2; + var result = {}; + if (mod2 != null) { + for (var k2 = ownKeys(mod2), i = 0; i < k2.length; i++) if (k2[i] !== "default") __createBinding(result, mod2, k2[i]); + } + __setModuleDefault(result, mod2); + return result; + }; + }(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.addAppMetadata = addAppMetadata; + exports2.getUserAgent = getUserAgent; + var os2 = __importStar(__require("node:os")); + var node_path_1 = __require("node:path"); + var packageJson = require_package3(); + function replaceSlashes(s) { + return s.replace("/", ":"); + } + var baseUserAgent = `${replaceSlashes(packageJson.name)}/${packageJson.version} ${(0, node_path_1.basename)(process.title)}/${process.version.replace("v", "")} ${os2.platform()}/${os2.release()}`; + var appMetadata = {}; + function addAppMetadata({ name, version: version4 }) { + appMetadata[replaceSlashes(name)] = version4; + } + function getUserAgent() { + const appIdentifier = Object.entries(appMetadata).map(([name, version4]) => `${name}/${version4}`).join(" "); + return (appIdentifier.length > 0 ? `${appIdentifier} ` : "") + baseUserAgent; + } + } +}); + +// node_modules/@slack/logger/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/@slack/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ConsoleLogger = exports2.LogLevel = void 0; + var LogLevel; + (function(LogLevel2) { + LogLevel2["ERROR"] = "error"; + LogLevel2["WARN"] = "warn"; + LogLevel2["INFO"] = "info"; + LogLevel2["DEBUG"] = "debug"; + })(LogLevel = exports2.LogLevel || (exports2.LogLevel = {})); + var ConsoleLogger = class _ConsoleLogger { + constructor() { + this.level = LogLevel.INFO; + this.name = ""; + } + getLevel() { + return this.level; + } + /** + * Sets the instance's log level so that only messages which are equal or more severe are output to the console. + */ + setLevel(level) { + this.level = level; + } + /** + * Set the instance's name, which will appear on each log line before the message. + */ + setName(name) { + this.name = name; + } + /** + * Log a debug message + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + debug(...msg) { + if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.DEBUG, this.level)) { + console.debug(_ConsoleLogger.labels.get(LogLevel.DEBUG), this.name, ...msg); + } + } + /** + * Log an info message + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + info(...msg) { + if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.INFO, this.level)) { + console.info(_ConsoleLogger.labels.get(LogLevel.INFO), this.name, ...msg); + } + } + /** + * Log a warning message + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + warn(...msg) { + if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.WARN, this.level)) { + console.warn(_ConsoleLogger.labels.get(LogLevel.WARN), this.name, ...msg); + } + } + /** + * Log an error message + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error(...msg) { + if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.ERROR, this.level)) { + console.error(_ConsoleLogger.labels.get(LogLevel.ERROR), this.name, ...msg); + } + } + /** + * Helper to compare two log levels and determine if a is equal or more severe than b + */ + static isMoreOrEqualSevere(a, b2) { + return _ConsoleLogger.severity[a] >= _ConsoleLogger.severity[b2]; + } + }; + exports2.ConsoleLogger = ConsoleLogger; + ConsoleLogger.labels = (() => { + const entries = Object.entries(LogLevel); + const map = entries.map(([key, value]) => [value, `[${key}] `]); + return new Map(map); + })(); + ConsoleLogger.severity = { + [LogLevel.ERROR]: 400, + [LogLevel.WARN]: 300, + [LogLevel.INFO]: 200, + [LogLevel.DEBUG]: 100 + }; + } +}); + +// node_modules/@slack/web-api/dist/logger.js +var require_logger2 = __commonJS({ + "node_modules/@slack/web-api/dist/logger.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.LogLevel = void 0; + exports2.getLogger = getLogger; + var logger_1 = require_dist2(); + var logger_2 = require_dist2(); + Object.defineProperty(exports2, "LogLevel", { enumerable: true, get: function() { + return logger_2.LogLevel; + } }); + var instanceCount = 0; + function getLogger(name, level, existingLogger) { + const instanceId = instanceCount; + instanceCount += 1; + const logger = (() => { + if (existingLogger !== void 0) { + return existingLogger; + } + return new logger_1.ConsoleLogger(); + })(); + logger.setName(`web-api:${name}:${instanceId}`); + if (level !== void 0) { + logger.setLevel(level); + } + return logger; + } + } +}); + +// node_modules/eventemitter3/index.js +var require_eventemitter32 = __commonJS({ + "node_modules/eventemitter3/index.js"(exports2, module2) { + "use strict"; + var has = Object.prototype.hasOwnProperty; + var prefix = "~"; + function Events() { + } + if (Object.create) { + Events.prototype = /* @__PURE__ */ Object.create(null); + if (!new Events().__proto__) prefix = false; + } + function EE(fn2, context, once) { + this.fn = fn2; + this.context = context; + this.once = once || false; + } + function addListener(emitter, event, fn2, context, once) { + if (typeof fn2 !== "function") { + throw new TypeError("The listener must be a function"); + } + var listener = new EE(fn2, context || emitter, once), evt = prefix ? prefix + event : event; + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + return emitter; + } + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + function EventEmitter3() { + this._events = new Events(); + this._eventsCount = 0; + } + EventEmitter3.prototype.eventNames = function eventNames() { + var names = [], events, name; + if (this._eventsCount === 0) return names; + for (name in events = this._events) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + return names; + }; + EventEmitter3.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event, handlers = this._events[evt]; + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + for (var i = 0, l = handlers.length, ee2 = new Array(l); i < l; i++) { + ee2[i] = handlers[i].fn; + } + return ee2; + }; + EventEmitter3.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event, listeners = this._events[evt]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + EventEmitter3.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return false; + var listeners = this._events[evt], len = arguments.length, args, i; + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); + switch (len) { + case 1: + return listeners.fn.call(listeners.context), true; + case 2: + return listeners.fn.call(listeners.context, a1), true; + case 3: + return listeners.fn.call(listeners.context, a1, a2), true; + case 4: + return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: + return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: + return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + for (i = 1, args = new Array(len - 1); i < len; i++) { + args[i - 1] = arguments[i]; + } + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length, j2; + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); + switch (len) { + case 1: + listeners[i].fn.call(listeners[i].context); + break; + case 2: + listeners[i].fn.call(listeners[i].context, a1); + break; + case 3: + listeners[i].fn.call(listeners[i].context, a1, a2); + break; + case 4: + listeners[i].fn.call(listeners[i].context, a1, a2, a3); + break; + default: + if (!args) for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) { + args[j2 - 1] = arguments[j2]; + } + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + return true; + }; + EventEmitter3.prototype.on = function on2(event, fn2, context) { + return addListener(this, event, fn2, context, false); + }; + EventEmitter3.prototype.once = function once(event, fn2, context) { + return addListener(this, event, fn2, context, true); + }; + EventEmitter3.prototype.removeListener = function removeListener(event, fn2, context, once) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return this; + if (!fn2) { + clearEvent(this, evt); + return this; + } + var listeners = this._events[evt]; + if (listeners.fn) { + if (listeners.fn === fn2 && (!once || listeners.once) && (!context || listeners.context === context)) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if (listeners[i].fn !== fn2 || once && !listeners[i].once || context && listeners[i].context !== context) { + events.push(listeners[i]); + } + } + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + return this; + }; + EventEmitter3.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + return this; + }; + EventEmitter3.prototype.off = EventEmitter3.prototype.removeListener; + EventEmitter3.prototype.addListener = EventEmitter3.prototype.on; + EventEmitter3.prefixed = prefix; + EventEmitter3.EventEmitter = EventEmitter3; + if ("undefined" !== typeof module2) { + module2.exports = EventEmitter3; + } + } +}); + +// node_modules/@slack/types/dist/calls.js +var require_calls = __commonJS({ + "node_modules/@slack/types/dist/calls.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/dialog.js +var require_dialog = __commonJS({ + "node_modules/@slack/types/dist/dialog.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/app.js +var require_app = __commonJS({ + "node_modules/@slack/types/dist/events/app.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/assistant.js +var require_assistant = __commonJS({ + "node_modules/@slack/types/dist/events/assistant.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/call.js +var require_call = __commonJS({ + "node_modules/@slack/types/dist/events/call.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/channel.js +var require_channel = __commonJS({ + "node_modules/@slack/types/dist/events/channel.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/dnd.js +var require_dnd = __commonJS({ + "node_modules/@slack/types/dist/events/dnd.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/email.js +var require_email = __commonJS({ + "node_modules/@slack/types/dist/events/email.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/emoji.js +var require_emoji = __commonJS({ + "node_modules/@slack/types/dist/events/emoji.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/file.js +var require_file2 = __commonJS({ + "node_modules/@slack/types/dist/events/file.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/function.js +var require_function = __commonJS({ + "node_modules/@slack/types/dist/events/function.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/grid-migration.js +var require_grid_migration = __commonJS({ + "node_modules/@slack/types/dist/events/grid-migration.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/group.js +var require_group = __commonJS({ + "node_modules/@slack/types/dist/events/group.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/im.js +var require_im = __commonJS({ + "node_modules/@slack/types/dist/events/im.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/invite.js +var require_invite = __commonJS({ + "node_modules/@slack/types/dist/events/invite.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/link-shared.js +var require_link_shared = __commonJS({ + "node_modules/@slack/types/dist/events/link-shared.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/member.js +var require_member = __commonJS({ + "node_modules/@slack/types/dist/events/member.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/message.js +var require_message = __commonJS({ + "node_modules/@slack/types/dist/events/message.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/message-metadata.js +var require_message_metadata = __commonJS({ + "node_modules/@slack/types/dist/events/message-metadata.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/pin.js +var require_pin = __commonJS({ + "node_modules/@slack/types/dist/events/pin.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/reaction.js +var require_reaction = __commonJS({ + "node_modules/@slack/types/dist/events/reaction.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/shared-channel.js +var require_shared_channel = __commonJS({ + "node_modules/@slack/types/dist/events/shared-channel.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/star.js +var require_star = __commonJS({ + "node_modules/@slack/types/dist/events/star.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/subteam.js +var require_subteam = __commonJS({ + "node_modules/@slack/types/dist/events/subteam.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/team.js +var require_team = __commonJS({ + "node_modules/@slack/types/dist/events/team.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/token.js +var require_token = __commonJS({ + "node_modules/@slack/types/dist/events/token.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/user.js +var require_user = __commonJS({ + "node_modules/@slack/types/dist/events/user.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/steps-from-apps.js +var require_steps_from_apps = __commonJS({ + "node_modules/@slack/types/dist/events/steps-from-apps.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/index.js +var require_events = __commonJS({ + "node_modules/@slack/types/dist/events/index.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; + } + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { + for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar(require_app(), exports2); + __exportStar(require_assistant(), exports2); + __exportStar(require_call(), exports2); + __exportStar(require_channel(), exports2); + __exportStar(require_dnd(), exports2); + __exportStar(require_email(), exports2); + __exportStar(require_emoji(), exports2); + __exportStar(require_file2(), exports2); + __exportStar(require_function(), exports2); + __exportStar(require_grid_migration(), exports2); + __exportStar(require_group(), exports2); + __exportStar(require_im(), exports2); + __exportStar(require_invite(), exports2); + __exportStar(require_link_shared(), exports2); + __exportStar(require_member(), exports2); + __exportStar(require_message(), exports2); + __exportStar(require_message_metadata(), exports2); + __exportStar(require_pin(), exports2); + __exportStar(require_reaction(), exports2); + __exportStar(require_shared_channel(), exports2); + __exportStar(require_star(), exports2); + __exportStar(require_subteam(), exports2); + __exportStar(require_team(), exports2); + __exportStar(require_token(), exports2); + __exportStar(require_user(), exports2); + __exportStar(require_steps_from_apps(), exports2); + } +}); + +// node_modules/@slack/types/dist/message-metadata.js +var require_message_metadata2 = __commonJS({ + "node_modules/@slack/types/dist/message-metadata.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/message-attachments.js +var require_message_attachments = __commonJS({ + "node_modules/@slack/types/dist/message-attachments.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/views.js +var require_views = __commonJS({ + "node_modules/@slack/types/dist/views.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/block-kit/blocks.js +var require_blocks = __commonJS({ + "node_modules/@slack/types/dist/block-kit/blocks.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/block-kit/composition-objects.js +var require_composition_objects = __commonJS({ + "node_modules/@slack/types/dist/block-kit/composition-objects.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/block-kit/block-elements.js +var require_block_elements = __commonJS({ + "node_modules/@slack/types/dist/block-kit/block-elements.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/block-kit/extensions.js +var require_extensions = __commonJS({ + "node_modules/@slack/types/dist/block-kit/extensions.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/index.js +var require_dist3 = __commonJS({ + "node_modules/@slack/types/dist/index.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; + } + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { + for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar(require_calls(), exports2); + __exportStar(require_dialog(), exports2); + __exportStar(require_events(), exports2); + __exportStar(require_message_metadata2(), exports2); + __exportStar(require_message_attachments(), exports2); + __exportStar(require_views(), exports2); + __exportStar(require_blocks(), exports2); + __exportStar(require_composition_objects(), exports2); + __exportStar(require_block_elements(), exports2); + __exportStar(require_extensions(), exports2); + } +}); + +// node_modules/@slack/web-api/dist/methods.js +var require_methods = __commonJS({ + "node_modules/@slack/web-api/dist/methods.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; + } + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { + for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Methods = void 0; + var eventemitter3_1 = require_eventemitter32(); + var WebClient_1 = require_WebClient(); + function bindApiCall(self2, method) { + const apiMethod = self2.apiCall.bind(self2, method); + return apiMethod; + } + function bindApiCallWithOptionalArgument(self2, method) { + const apiMethod = self2.apiCall.bind(self2, method); + return apiMethod; + } + function bindFilesUploadV2(self2) { + return self2.filesUploadV2.bind(self2); + } + var Methods = class extends eventemitter3_1.EventEmitter { + constructor() { + super(); + this.admin = { + analytics: { + /** + * @description Retrieve analytics data for a given date, presented as a compressed JSON file. + * @see {@link https://api.slack.com/methods/api.test `api.test` API reference}. + */ + getFile: bindApiCall(this, "admin.analytics.getFile") + }, + apps: { + activities: { + /** + * @description Get logs for a specified team/org. + * @see {@link https://api.slack.com/methods/admin.apps.activities.list `admin.apps.activities.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.apps.activities.list") + }, + /** + * @description Approve an app for installation on a workspace. + * @see {@link https://api.slack.com/methods/admin.apps.approve `admin.apps.approve` API reference}. + */ + approve: bindApiCall(this, "admin.apps.approve"), + approved: { + /** + * @description List approved apps for an org or workspace. + * @see {@link https://api.slack.com/methods/admin.apps.approved.list `admin.apps.approved.list` API reference}. + */ + list: bindApiCall(this, "admin.apps.approved.list") + }, + /** + * @description Clear an app resolution. + * @see {@link https://api.slack.com/methods/admin.apps.clearResolution `admin.apps.clearResolution` API reference}. + */ + clearResolution: bindApiCall(this, "admin.apps.clearResolution"), + config: { + /** + * @description Look up the app config for connectors by their IDs. + * @see {@link https://api.slack.com/methods/admin.apps.config.lookup `admin.apps.config.lookup` API reference}. + */ + lookup: bindApiCall(this, "admin.apps.config.lookup"), + /** + * @description Set the app config for a connector. + * @see {@link https://api.slack.com/methods/admin.apps.config.set `admin.apps.config.set` API reference}. + */ + set: bindApiCall(this, "admin.apps.config.set") + }, + requests: { + /** + * @description Cancel app request for team. + * @see {@link https://api.slack.com/methods/admin.apps.requests.cancel `admin.apps.requests.cancel` API reference}. + */ + cancel: bindApiCall(this, "admin.apps.requests.cancel"), + /** + * @description List app requests for a team/workspace. + * @see {@link https://api.slack.com/methods/admin.apps.requests.list `admin.apps.requests.list` API reference}. + */ + list: bindApiCall(this, "admin.apps.requests.list") + }, + /** + * @description Restrict an app for installation on a workspace. + * @see {@link https://api.slack.com/methods/admin.apps.restrict `admin.apps.restrict` API reference}. + */ + restrict: bindApiCall(this, "admin.apps.restrict"), + restricted: { + /** + * @description List restricted apps for an org or workspace. + * @see {@link https://api.slack.com/methods/admin.apps.restricted.list `admin.apps.restricted.list` API reference}. + */ + list: bindApiCall(this, "admin.apps.restricted.list") + }, + /** + * @description Uninstall an app from one or many workspaces, or an entire enterprise organization. + * @see {@link https://api.slack.com/methods/admin.apps.uninstall `admin.apps.uninstall` API reference}. + */ + uninstall: bindApiCall(this, "admin.apps.uninstall") + }, + auth: { + policy: { + /** + * @description Assign entities to a particular authentication policy. + * @see {@link https://api.slack.com/methods/admin.auth.policy.assignEntities `admin.auth.policy.assignEntities` API reference}. + */ + assignEntities: bindApiCall(this, "admin.auth.policy.assignEntities"), + /** + * @description Fetch all the entities assigned to a particular authentication policy by name. + * @see {@link https://api.slack.com/methods/admin.auth.policy.getEntities `admin.auth.policy.getEntities` API reference}. + */ + getEntities: bindApiCall(this, "admin.auth.policy.getEntities"), + /** + * @description Remove specified entities from a specified authentication policy. + * @see {@link https://api.slack.com/methods/admin.auth.policy.removeEntities `admin.auth.policy.removeEntities` API reference}. + */ + removeEntities: bindApiCall(this, "admin.auth.policy.removeEntities") + } + }, + barriers: { + /** + * @description Create an Information Barrier. + * @see {@link https://api.slack.com/methods/admin.barriers.create `admin.barriers.create` API reference}. + */ + create: bindApiCall(this, "admin.barriers.create"), + /** + * @description Delete an existing Information Barrier. + * @see {@link https://api.slack.com/methods/admin.barriers.delete `admin.barriers.delete` API reference}. + */ + delete: bindApiCall(this, "admin.barriers.delete"), + /** + * @description Get all Information Barriers for your organization. + * @see {@link https://api.slack.com/methods/admin.barriers.list `admin.barriers.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.barriers.list"), + /** + * @description Update an existing Information Barrier. + * @see {@link https://api.slack.com/methods/admin.barriers.update `admin.barriers.update` API reference}. + */ + update: bindApiCall(this, "admin.barriers.update") + }, + conversations: { + /** + * @description Archive a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.archive `admin.conversations.archive` API reference}. + */ + archive: bindApiCall(this, "admin.conversations.archive"), + /** + * @description Archive public or private channels in bulk. + * @see {@link https://api.slack.com/methods/admin.conversations.bulkArchive `admin.conversations.bulkArchive` API reference}. + */ + bulkArchive: bindApiCall(this, "admin.conversations.bulkArchive"), + /** + * @description Delete public or private channels in bulk. + * @see {@link https://api.slack.com/methods/admin.conversations.bulkDelet `admin.conversations.bulkDelete` API reference}. + */ + bulkDelete: bindApiCall(this, "admin.conversations.bulkDelete"), + /** + * @description Move public or private channels in bulk. + * @see {@link https://api.slack.com/methods/admin.conversations.bulkMove `admin.conversations.bulkMove` API reference}. + */ + bulkMove: bindApiCall(this, "admin.conversations.bulkMove"), + /** + * @description Convert a public channel to a private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.convertToPrivate `admin.conversations.convertToPrivate` API reference}. + */ + convertToPrivate: bindApiCall(this, "admin.conversations.convertToPrivate"), + /** + * @description Convert a private channel to a public channel. + * @see {@link https://api.slack.com/methods/admin.conversations.convertToPublic `admin.conversations.convertToPublic` API reference}. + */ + convertToPublic: bindApiCall(this, "admin.conversations.convertToPublic"), + /** + * @description Create a public or private channel-based conversation. + * @see {@link https://api.slack.com/methods/admin.conversations.create `admin.conversations.create` API reference}. + */ + create: bindApiCall(this, "admin.conversations.create"), + /** + * @description Delete a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.delete `admin.conversations.delete` API reference}. + */ + delete: bindApiCall(this, "admin.conversations.delete"), + /** + * @description Disconnect a connected channel from one or more workspaces. + * @see {@link https://api.slack.com/methods/admin.conversations.disconnectShared `admin.conversations.disconnectShared` API reference}. + */ + disconnectShared: bindApiCall(this, "admin.conversations.disconnectShared"), + ekm: { + /** + * @description List all disconnected channels — i.e., channels that were once connected to other workspaces + * and then disconnected — and the corresponding original channel IDs for key revocation with EKM. + * @see {@link https://api.slack.com/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo `admin.conversations.ekm.listOriginalConnectedChannelInfo` API reference}. + */ + listOriginalConnectedChannelInfo: bindApiCallWithOptionalArgument(this, "admin.conversations.ekm.listOriginalConnectedChannelInfo") + }, + /** + * @description Get conversation preferences for a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.getConversationPrefs `admin.conversations.getConversationPrefs` API reference}. + */ + getConversationPrefs: bindApiCall(this, "admin.conversations.getConversationPrefs"), + /** + * @description Get a conversation's retention policy. + * @see {@link https://api.slack.com/methods/admin.conversations.getCustomRetention `admin.conversations.getCustomRetention` API reference}. + */ + getCustomRetention: bindApiCall(this, "admin.conversations.getCustomRetention"), + /** + * @description Get all the workspaces a given public or private channel is connected to within + * this Enterprise org. + * @see {@link https://api.slack.com/methods/admin.conversations.getTeams `admin.conversations.getTeams` API reference}. + */ + getTeams: bindApiCall(this, "admin.conversations.getTeams"), + /** + * @description Invite a user to a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.invite `admin.conversations.invite` API reference}. + */ + invite: bindApiCall(this, "admin.conversations.invite"), + /** + * @description Returns channels on the given team using the filters. + * @see {@link https://api.slack.com/methods/admin.conversations.lookup `admin.conversations.lookup` API reference}. + */ + lookup: bindApiCall(this, "admin.conversations.lookup"), + /** + * @description Remove a conversation's retention policy. + * @see {@link https://api.slack.com/methods/admin.conversations.removeCustomRetention `admin.conversations.removeCustomRetention` API reference}. + */ + removeCustomRetention: bindApiCall(this, "admin.conversations.removeCustomRetention"), + /** + * @description Rename a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.rename `admin.conversations.rename` API reference}. + */ + rename: bindApiCall(this, "admin.conversations.rename"), + restrictAccess: { + /** + * @description Add an allowlist of IDP groups for accessing a channel. + * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.addGroup `admin.conversations.restrictAccess.addGroup` API reference}. + */ + addGroup: bindApiCall(this, "admin.conversations.restrictAccess.addGroup"), + /** + * @description List all IDP Groups linked to a channel. + * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.listGroups `admin.conversations.restrictAccess.listGroups` API reference}. + */ + listGroups: bindApiCall(this, "admin.conversations.restrictAccess.listGroups"), + /** + * @description Remove a linked IDP group linked from a private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.removeGroup `admin.conversations.restrictAccess.removeGroup` API reference}. + */ + removeGroup: bindApiCall(this, "admin.conversations.restrictAccess.removeGroup") + }, + /** + * @description Search for public or private channels in an Enterprise organization. + * @see {@link https://api.slack.com/methods/admin.conversations.search `admin.conversations.search` API reference}. + */ + search: bindApiCallWithOptionalArgument(this, "admin.conversations.search"), + /** + * @description Set the posting permissions for a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.setConversationPrefs `admin.conversations.setConversationPrefs` API reference}. + */ + setConversationPrefs: bindApiCall(this, "admin.conversations.setConversationPrefs"), + /** + * @description Set a conversation's retention policy. + * @see {@link https://api.slack.com/methods/admin.conversations.setCustomRetention `admin.conversations.setCustomRetention` API reference}. + */ + setCustomRetention: bindApiCall(this, "admin.conversations.setCustomRetention"), + /** + * @description Set the workspaces in an Enterprise grid org that connect to a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.setTeams `admin.conversations.setTeams` API reference}. + */ + setTeams: bindApiCall(this, "admin.conversations.setTeams"), + /** + * @description Unarchive a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.unarchive `admin.conversations.unarchive` API reference}. + */ + unarchive: bindApiCall(this, "admin.conversations.unarchive") + }, + emoji: { + /** + * @description Add an emoji. + * @see {@link https://api.slack.com/methods/admin.emoji.add `admin.emoji.add` API reference}. + */ + add: bindApiCall(this, "admin.emoji.add"), + /** + * @description Add an emoji alias. + * @see {@link https://api.slack.com/methods/admin.emoji.addAlias `admin.emoji.addAlias` API reference}. + */ + addAlias: bindApiCall(this, "admin.emoji.addAlias"), + /** + * @description List emoji for an Enterprise Grid organization. + * @see {@link https://api.slack.com/methods/admin.emoji.list `admin.emoji.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.emoji.list"), + /** + * @description Remove an emoji across an Enterprise Grid organization. + * @see {@link https://api.slack.com/methods/admin.emoji.remove `admin.emoji.remove` API reference}. + */ + remove: bindApiCall(this, "admin.emoji.remove"), + /** + * @description Rename an emoji. + * @see {@link https://api.slack.com/methods/admin.emoji.rename `admin.emoji.rename` API reference}. + */ + rename: bindApiCall(this, "admin.emoji.rename") + }, + functions: { + /** + * @description Look up functions by a set of apps. + * @see {@link https://api.slack.com/methods/admin.functions.list `admin.functions.list` API reference}. + */ + list: bindApiCall(this, "admin.functions.list"), + permissions: { + /** + * @description Lookup the visibility of multiple Slack functions and include the users if + * it is limited to particular named entities. + * @see {@link https://api.slack.com/methods/admin.functions.permissions.lookup `admin.functions.permissions.lookup` API reference}. + */ + lookup: bindApiCall(this, "admin.functions.permissions.lookup"), + /** + * @description Set the visibility of a Slack function and define the users or workspaces if + * it is set to named_entities. + * @see {@link https://api.slack.com/methods/admin.functions.permissions.set `admin.functions.permissions.set` API reference}. + */ + set: bindApiCall(this, "admin.functions.permissions.set") + } + }, + inviteRequests: { + /** + * @description Approve a workspace invite request. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.approve `admin.inviteRequests.approve` API reference}. + */ + approve: bindApiCall(this, "admin.inviteRequests.approve"), + approved: { + /** + * @description List all approved workspace invite requests. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.approved.list `admin.inviteRequests.approved.list` API reference}. + */ + list: bindApiCall(this, "admin.inviteRequests.approved.list") + }, + denied: { + /** + * @description List all denied workspace invite requests. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.denied.list `admin.inviteRequests.denied.list` API reference}. + */ + list: bindApiCall(this, "admin.inviteRequests.denied.list") + }, + /** + * @description Deny a workspace invite request. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.deny `admin.inviteRequests.deny` API reference}. + */ + deny: bindApiCall(this, "admin.inviteRequests.deny"), + /** + * @description List all pending workspace invite requests. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.list `admin.inviteRequests.list` API reference}. + */ + list: bindApiCall(this, "admin.inviteRequests.list") + }, + roles: { + /** + * @description Adds members to the specified role with the specified scopes. + * @see {@link https://api.slack.com/methods/admin.roles.addAssignments `admin.roles.addAssignments` API reference}. + */ + addAssignments: bindApiCall(this, "admin.roles.addAssignments"), + /** + * @description Lists assignments for all roles across entities. + * Options to scope results by any combination of roles or entities. + * @see {@link https://api.slack.com/methods/admin.roles.listAssignments `admin.roles.listAssignments` API reference}. + */ + listAssignments: bindApiCallWithOptionalArgument(this, "admin.roles.listAssignments"), + /** + * @description Removes a set of users from a role for the given scopes and entities. + * @see {@link https://api.slack.com/methods/admin.roles.removeAssignments `admin.roles.removeAssignments` API reference}. + */ + removeAssignments: bindApiCall(this, "admin.roles.removeAssignments") + }, + teams: { + admins: { + /** + * @description List all of the admins on a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.admins.list `admin.teams.admins.list` API reference}. + */ + list: bindApiCall(this, "admin.teams.admins.list") + }, + /** + * @description Create an Enterprise team. + * @see {@link https://api.slack.com/methods/admin.teams.create `admin.teams.create` API reference}. + */ + create: bindApiCall(this, "admin.teams.create"), + /** + * @description List all teams on an Enterprise organization. + * @see {@link https://api.slack.com/methods/admin.teams.list `admin.teams.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.teams.list"), + owners: { + /** + * @description List all of the owners on a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.owners.list `admin.teams.owners.list` API reference}. + */ + list: bindApiCall(this, "admin.teams.owners.list") + }, + settings: { + /** + * @description Fetch information about settings in a workspace. + * @see {@link https://api.slack.com/methods/admin.teams.owners.list `admin.teams.owners.list` API reference}. + */ + info: bindApiCall(this, "admin.teams.settings.info"), + /** + * @description Set the default channels of a workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setDefaultChannels `admin.teams.settings.setDefaultChannels` API reference}. + */ + setDefaultChannels: bindApiCall(this, "admin.teams.settings.setDefaultChannels"), + /** + * @description Set the description of a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setDescription `admin.teams.settings.setDescription` API reference}. + */ + setDescription: bindApiCall(this, "admin.teams.settings.setDescription"), + /** + * @description Set the discoverability of a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setDiscoverability `admin.teams.settings.setDiscoverability` API reference}. + */ + setDiscoverability: bindApiCall(this, "admin.teams.settings.setDiscoverability"), + /** + * @description Sets the icon of a workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setIcon `admin.teams.settings.setIcon` API reference}. + */ + setIcon: bindApiCall(this, "admin.teams.settings.setIcon"), + /** + * @description Set the name of a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setName `admin.teams.settings.setName` API reference}. + */ + setName: bindApiCall(this, "admin.teams.settings.setName") + } + }, + usergroups: { + /** + * @description Add up to one hundred default channels to an IDP group. + * @see {@link https://api.slack.com/methods/admin.usergroups.addChannels `admin.teams.usergroups.addChannels` API reference}. + */ + addChannels: bindApiCall(this, "admin.usergroups.addChannels"), + /** + * @description Associate one or more default workspaces with an organization-wide IDP group. + * @see {@link https://api.slack.com/methods/admin.usergroups.addTeams `admin.teams.usergroups.addTeams` API reference}. + */ + addTeams: bindApiCall(this, "admin.usergroups.addTeams"), + /** + * @description List the channels linked to an org-level IDP group (user group). + * @see {@link https://api.slack.com/methods/admin.usergroups.listChannels `admin.teams.usergroups.listChannels` API reference}. + */ + listChannels: bindApiCall(this, "admin.usergroups.listChannels"), + /** + * @description Remove one or more default channels from an org-level IDP group (user group). + * @see {@link https://api.slack.com/methods/admin.usergroups.removeChannels `admin.teams.usergroups.removeChannels` API reference}. + */ + removeChannels: bindApiCall(this, "admin.usergroups.removeChannels") + }, + users: { + /** + * @description Add an Enterprise user to a workspace. + * @see {@link https://api.slack.com/methods/admin.users.assign `admin.users.assign` API reference}. + */ + assign: bindApiCall(this, "admin.users.assign"), + /** + * @description Invite a user to a workspace. + * @see {@link https://api.slack.com/methods/admin.users.invite `admin.users.invite` API reference}. + */ + invite: bindApiCall(this, "admin.users.invite"), + /** + * @description List users on a workspace. + * @see {@link https://api.slack.com/methods/admin.users.list `admin.users.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.users.list"), + /** + * @description Remove a user from a workspace. + * @see {@link https://api.slack.com/methods/admin.users.remove `admin.users.remove` API reference}. + */ + remove: bindApiCall(this, "admin.users.remove"), + session: { + /** + * @description Clear user-specific session settings—the session duration and what happens when the client + * closes—for a list of users. + * @see {@link https://api.slack.com/methods/admin.users.session.clearSettings `admin.users.session.clearSettings` API reference}. + */ + clearSettings: bindApiCall(this, "admin.users.session.clearSettings"), + /** + * @description Get user-specific session settings—the session duration and what happens when the client + * closes—given a list of users. + * @see {@link https://api.slack.com/methods/admin.users.session.getSettings `admin.users.session.getSettings` API reference}. + */ + getSettings: bindApiCall(this, "admin.users.session.getSettings"), + /** + * @description Revoke a single session for a user. The user will be forced to login to Slack. + * @see {@link https://api.slack.com/methods/admin.users.session.invalidate `admin.users.session.invalidate` API reference}. + */ + invalidate: bindApiCall(this, "admin.users.session.invalidate"), + /** + * @description List active user sessions for an organization. + * @see {@link https://api.slack.com/methods/admin.users.session.list `admin.users.session.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.users.session.list"), + /** + * @description Wipes all valid sessions on all devices for a given user. + * @see {@link https://api.slack.com/methods/admin.users.session.reset `admin.users.session.reset` API reference}. + */ + reset: bindApiCall(this, "admin.users.session.reset"), + /** + * @description Enqueues an asynchronous job to wipe all valid sessions on all devices for a given user list. + * @see {@link https://api.slack.com/methods/admin.users.session.resetBulk `admin.users.session.resetBulk` API reference}. + */ + resetBulk: bindApiCall(this, "admin.users.session.resetBulk"), + /** + * @description Configure the user-level session settings—the session duration and what happens when the client + * closes—for one or more users. + * @see {@link https://api.slack.com/methods/admin.users.session.setSettings `admin.users.session.setSettings` API reference}. + */ + setSettings: bindApiCall(this, "admin.users.session.setSettings") + }, + /** + * @description Set an existing guest, regular user, or owner to be an admin user. + * @see {@link https://api.slack.com/methods/admin.users.setAdmin `admin.users.setAdmin` API reference}. + */ + setAdmin: bindApiCall(this, "admin.users.setAdmin"), + /** + * @description Set an expiration for a guest user. + * @see {@link https://api.slack.com/methods/admin.users.setExpiration `admin.users.setExpiration` API reference}. + */ + setExpiration: bindApiCall(this, "admin.users.setExpiration"), + /** + * @description Set an existing guest, regular user, or admin user to be a workspace owner. + * @see {@link https://api.slack.com/methods/admin.users.setOwner `admin.users.setOwner` API reference}. + */ + setOwner: bindApiCall(this, "admin.users.setOwner"), + /** + * @description Set an existing guest user, admin user, or owner to be a regular user. + * @see {@link https://api.slack.com/methods/admin.users.setRegular `admin.users.setRegular` API reference}. + */ + setRegular: bindApiCall(this, "admin.users.setRegular"), + unsupportedVersions: { + /** + * @description Ask Slackbot to send you an export listing all workspace members using unsupported software, + * presented as a zipped CSV file. + * @see {@link https://api.slack.com/methods/admin.users.unsupportedVersions.export `admin.users.unsupportedVersions.export` API reference}. + */ + export: bindApiCall(this, "admin.users.unsupportedVersions.export") + } + }, + workflows: { + collaborators: { + /** + * @description Add collaborators to workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.collaborators.add `admin.workflows.collaborators.add` API reference}. + */ + add: bindApiCall(this, "admin.workflows.collaborators.add"), + /** + * @description Remove collaborators from workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.collaborators.remove `admin.workflows.collaborators.remove` API reference}. + */ + remove: bindApiCall(this, "admin.workflows.collaborators.remove") + }, + permissions: { + /** + * @description Look up the permissions for a set of workflows. + * @see {@link https://api.slack.com/methods/admin.workflows.permissions.lookup `admin.workflows.permissions.lookup` API reference}. + */ + lookup: bindApiCall(this, "admin.workflows.permissions.lookup") + }, + /** + * @description Search workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.search `admin.workflows.search` API reference}. + */ + search: bindApiCallWithOptionalArgument(this, "admin.workflows.search"), + /** + * @description Unpublish workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.unpublish `admin.workflows.unpublish` API reference}. + */ + unpublish: bindApiCall(this, "admin.workflows.unpublish") + } + }; + this.api = { + /** + * @description Checks API calling code. + * @see {@link https://api.slack.com/methods/api.test `api.test` API reference}. + */ + test: bindApiCallWithOptionalArgument(this, "api.test") + }; + this.assistant = { + threads: { + /** + * @description Set loading status to indicate that the app is building a response. + * @see {@link https://api.slack.com/methods/assistant.threads.setStatus `assistant.threads.setStatus` API reference}. + */ + setStatus: bindApiCall(this, "assistant.threads.setStatus"), + /** + * @description Set suggested prompts for the user. Can suggest up to four prompts. + * @see {@link https://api.slack.com/methods/assistant.threads.setSuggestedPrompts `assistant.threads.setSuggestedPrompts` API reference}. + */ + setSuggestedPrompts: bindApiCall(this, "assistant.threads.setSuggestedPrompts"), + /** + * @description Set the title of the thread. This is shown when a user views the app's chat history. + * @see {@link https://api.slack.com/methods/assistant.threads.setTitle `assistant.threads.setTitle` API reference}. + */ + setTitle: bindApiCall(this, "assistant.threads.setTitle") + } + }; + this.apps = { + connections: { + /** + * @description Generate a temporary Socket Mode WebSocket URL that your app can connect to in order to receive + * events and interactive payloads over. + * @see {@link https://api.slack.com/methods/apps.connections.open `apps.connections.open` API reference}. + */ + open: bindApiCallWithOptionalArgument(this, "apps.connections.open") + }, + event: { + authorizations: { + /** + * @description Get a list of authorizations for the given event context. + * Each authorization represents an app installation that the event is visible to. + * @see {@link https://api.slack.com/methods/apps.event.authorizations.list `apps.event.authorizations.list` API reference}. + */ + list: bindApiCall(this, "apps.event.authorizations.list") + } + }, + manifest: { + /** + * @description Create an app from an app manifest. + * @see {@link https://api.slack.com/methods/apps.manifest.create `apps.manifest.create` API reference}. + */ + create: bindApiCall(this, "apps.manifest.create"), + /** + * @description Permanently deletes an app created through app manifests. + * @see {@link https://api.slack.com/methods/apps.manifest.delete `apps.manifest.delete` API reference}. + */ + delete: bindApiCall(this, "apps.manifest.delete"), + /** + * @description Export an app manifest from an existing app. + * @see {@link https://api.slack.com/methods/apps.manifest.export `apps.manifest.export` API reference}. + */ + export: bindApiCall(this, "apps.manifest.export"), + /** + * @description Update an app from an app manifest. + * @see {@link https://api.slack.com/methods/apps.manifest.update `apps.manifest.update` API reference}. + */ + update: bindApiCall(this, "apps.manifest.update"), + /** + * @description Validate an app manifest. + * @see {@link https://api.slack.com/methods/apps.manifest.validate `apps.manifest.validate` API reference}. + */ + validate: bindApiCall(this, "apps.manifest.validate") + }, + /** + * @description Uninstalls your app from a workspace. + * @see {@link https://api.slack.com/methods/apps.uninstall `apps.uninstall` API reference}. + */ + uninstall: bindApiCall(this, "apps.uninstall") + }; + this.auth = { + /** + * @description Revokes a token. + * @see {@link https://api.slack.com/methods/auth.revoke `auth.revoke` API reference}. + */ + revoke: bindApiCallWithOptionalArgument(this, "auth.revoke"), + teams: { + /** + * @description Obtain a full list of workspaces your org-wide app has been approved for. + * @see {@link https://api.slack.com/methods/auth.teams.list `auth.teams.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "auth.teams.list") + }, + test: bindApiCallWithOptionalArgument(this, "auth.test") + }; + this.bookmarks = { + /** + * @description Add bookmark to a channel. + * @see {@link https://api.slack.com/methods/bookmarks.add `bookmarks.add` API reference}. + */ + add: bindApiCall(this, "bookmarks.add"), + /** + * @description Edit bookmark. + * @see {@link https://api.slack.com/methods/bookmarks.edit `bookmarks.edit` API reference}. + */ + edit: bindApiCall(this, "bookmarks.edit"), + /** + * @description List bookmarks for a channel. + * @see {@link https://api.slack.com/methods/bookmarks.list `bookmarks.list` API reference}. + */ + list: bindApiCall(this, "bookmarks.list"), + /** + * @description Remove bookmark from a channel. + * @see {@link https://api.slack.com/methods/bookmarks.remove `bookmarks.remove` API reference}. + */ + remove: bindApiCall(this, "bookmarks.remove") + }; + this.bots = { + /** + * @description Gets information about a bot user. + * @see {@link https://api.slack.com/methods/bots.info `bots.info` API reference}. + */ + info: bindApiCallWithOptionalArgument(this, "bots.info") + }; + this.calls = { + /** + * @description Registers a new Call. + * @see {@link https://api.slack.com/methods/calls.add `calls.add` API reference}. + */ + add: bindApiCall(this, "calls.add"), + /** + * @description Ends a Call. + * @see {@link https://api.slack.com/methods/calls.end `calls.end` API reference}. + */ + end: bindApiCall(this, "calls.end"), + /** + * @description Returns information about a Call. + * @see {@link https://api.slack.com/methods/calls.info `calls.info` API reference}. + */ + info: bindApiCall(this, "calls.info"), + /** + * @description Updates information about a Call. + * @see {@link https://api.slack.com/methods/calls.info `calls.info` API reference}. + */ + update: bindApiCall(this, "calls.update"), + participants: { + /** + * @description Registers new participants added to a Call. + * @see {@link https://api.slack.com/methods/calls.participants.add `calls.participants.add` API reference}. + */ + add: bindApiCall(this, "calls.participants.add"), + remove: bindApiCall(this, "calls.participants.remove") + } + }; + this.canvases = { + access: { + /** + * @description Remove access to a canvas for specified entities. + * @see {@link https://api.slack.com/methods/canvases.access.delete `canvases.access.delete` API reference}. + */ + delete: bindApiCall(this, "canvases.access.delete"), + /** + * @description Sets the access level to a canvas for specified entities. + * @see {@link https://api.slack.com/methods/canvases.access.set `canvases.access.set` API reference}. + */ + set: bindApiCall(this, "canvases.access.set") + }, + /** + * @description Create Canvas for a user. + * @see {@link https://api.slack.com/methods/canvases.create `canvases.create` API reference}. + */ + create: bindApiCallWithOptionalArgument(this, "canvases.create"), + /** + * @description Deletes a canvas. + * @see {@link https://api.slack.com/methods/canvases.delete `canvases.delete` API reference}. + */ + delete: bindApiCall(this, "canvases.delete"), + /** + * @description Update an existing canvas. + * @see {@link https://api.slack.com/methods/canvases.edit `canvases.edit` API reference}. + */ + edit: bindApiCall(this, "canvases.edit"), + sections: { + /** + * @description Find sections matching the provided criteria. + * @see {@link https://api.slack.com/methods/canvases.sections.lookup `canvases.sections.lookup` API reference}. + */ + lookup: bindApiCall(this, "canvases.sections.lookup") + } + }; + this.chat = { + /** + * @description Deletes a message. + * @see {@link https://api.slack.com/methods/chat.delete `chat.delete` API reference}. + */ + delete: bindApiCall(this, "chat.delete"), + /** + * @description Deletes a pending scheduled message from the queue. + * @see {@link https://api.slack.com/methods/chat.deleteScheduledMessage `chat.deleteScheduledMessage` API reference}. + */ + deleteScheduledMessage: bindApiCall(this, "chat.deleteScheduledMessage"), + /** + * @description Retrieve a permalink URL for a specific extant message. + * @see {@link https://api.slack.com/methods/chat.getPermalink `chat.getPermalink` API reference}. + */ + getPermalink: bindApiCall(this, "chat.getPermalink"), + /** + * @description Share a me message into a channel. + * @see {@link https://api.slack.com/methods/chat.meMessage `chat.meMessage` API reference}. + */ + meMessage: bindApiCall(this, "chat.meMessage"), + /** + * @description Sends an ephemeral message to a user in a channel. + * @see {@link https://api.slack.com/methods/chat.postEphemeral `chat.postEphemeral` API reference}. + */ + postEphemeral: bindApiCall(this, "chat.postEphemeral"), + /** + * @description Sends a message to a channel. + * @see {@link https://api.slack.com/methods/chat.postMessage `chat.postMessage` API reference}. + */ + postMessage: bindApiCall(this, "chat.postMessage"), + /** + * @description Schedules a message to be sent to a channel. + * @see {@link https://api.slack.com/methods/chat.scheduleMessage `chat.scheduleMessage` API reference}. + */ + scheduleMessage: bindApiCall(this, "chat.scheduleMessage"), + scheduledMessages: { + /** + * @description Returns a list of scheduled messages. + * @see {@link https://api.slack.com/methods/chat.scheduledMessages.list `chat.scheduledMessages.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "chat.scheduledMessages.list") + }, + /** + * @description Provide custom unfurl behavior for user-posted URLs. + * @see {@link https://api.slack.com/methods/chat.unfurl `chat.unfurl` API reference}. + */ + unfurl: bindApiCall(this, "chat.unfurl"), + /** + * @description Updates a message. + * @see {@link https://api.slack.com/methods/chat.update `chat.update` API reference}. + */ + update: bindApiCall(this, "chat.update") + }; + this.conversations = { + /** + * @description Accepts an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.acceptSharedInvite `conversations.acceptSharedInvite` API reference}. + */ + acceptSharedInvite: bindApiCall(this, "conversations.acceptSharedInvite"), + /** + * @description Approves an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.approveSharedInvite `conversations.approveSharedInvite` API reference}. + */ + approveSharedInvite: bindApiCall(this, "conversations.approveSharedInvite"), + /** + * @description Archives a conversation. + * @see {@link https://api.slack.com/methods/conversations.archive `conversations.archive` API reference}. + */ + archive: bindApiCall(this, "conversations.archive"), + canvases: { + /** + * @description Create a Channel Canvas for a channel. + * @see {@link https://api.slack.com/methods/conversations.canvases.create `conversations.canvases.create` API reference}. + */ + create: bindApiCall(this, "conversations.canvases.create") + }, + /** + * @description Closes a direct message or multi-person direct message. + * @see {@link https://api.slack.com/methods/conversations.close `conversations.close` API reference}. + */ + close: bindApiCall(this, "conversations.close"), + /** + * @description Initiates a public or private channel-based conversation. + * @see {@link https://api.slack.com/methods/conversations.create `conversations.create` API reference}. + */ + create: bindApiCall(this, "conversations.create"), + /** + * @description Declines an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.declineSharedInvite `conversations.declineSharedInvite` API reference}. + */ + declineSharedInvite: bindApiCall(this, "conversations.declineSharedInvite"), + externalInvitePermissions: { + /** + * @description Convert a team in a shared channel from an External Limited channel to a fully shared Slack + * Connect channel or vice versa. + * @see {@link https://api.slack.com/methods/conversations.externalInvitePermissions.set `conversations.externalInvitePermissions.set` API reference}. + */ + set: bindApiCall(this, "conversations.externalInvitePermissions.set") + }, + /** + * @description Fetches a conversation's history of messages and events. + * @see {@link https://api.slack.com/methods/conversations.history `conversations.history` API reference}. + */ + history: bindApiCall(this, "conversations.history"), + /** + * @description Retrieve information about a conversation. + * @see {@link https://api.slack.com/methods/conversations.info `conversations.info` API reference}. + */ + info: bindApiCall(this, "conversations.info"), + /** + * @description Invites users to a channel. + * @see {@link https://api.slack.com/methods/conversations.invite `conversations.invite` API reference}. + */ + invite: bindApiCall(this, "conversations.invite"), + /** + * @description Sends an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.inviteShared `conversations.inviteShared` API reference}. + */ + inviteShared: bindApiCall(this, "conversations.inviteShared"), + /** + * @description Joins an existing conversation. + * @see {@link https://api.slack.com/methods/conversations.join `conversations.join` API reference}. + */ + join: bindApiCall(this, "conversations.join"), + /** + * @description Removes a user from a conversation. + * @see {@link https://api.slack.com/methods/conversations.kick `conversations.kick` API reference}. + */ + kick: bindApiCall(this, "conversations.kick"), + /** + * @description Leaves a conversation. + * @see {@link https://api.slack.com/methods/conversations.leave `conversations.leave` API reference}. + */ + leave: bindApiCall(this, "conversations.leave"), + /** + * @description List all channels in a Slack team. + * @see {@link https://api.slack.com/methods/conversations.list `conversations.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "conversations.list"), + /** + * @description Lists shared channel invites that have been generated or received but have not been approved by + * all parties. + * @see {@link https://api.slack.com/methods/conversations.listConnectInvites `conversations.listConnectInvites` API reference}. + */ + listConnectInvites: bindApiCallWithOptionalArgument(this, "conversations.listConnectInvites"), + /** + * @description Sets the read cursor in a channel. + * @see {@link https://api.slack.com/methods/conversations.mark `conversations.mark` API reference}. + */ + mark: bindApiCall(this, "conversations.mark"), + /** + * @description Retrieve members of a conversation. + * @see {@link https://api.slack.com/methods/conversations.members `conversations.members` API reference}. + */ + members: bindApiCall(this, "conversations.members"), + /** + * @description Opens or resumes a direct message or multi-person direct message. + * @see {@link https://api.slack.com/methods/conversations.open `conversations.open` API reference}. + */ + open: bindApiCall(this, "conversations.open"), + /** + * @description Renames a conversation. + * @see {@link https://api.slack.com/methods/conversations.rename `conversations.rename` API reference}. + */ + rename: bindApiCall(this, "conversations.rename"), + /** + * @description Retrieve a thread of messages posted to a conversation. + * @see {@link https://api.slack.com/methods/conversations.replies `conversations.replies` API reference}. + */ + replies: bindApiCall(this, "conversations.replies"), + requestSharedInvite: { + /** + * @description Approves a request to add an external user to a channel and sends them a Slack Connect invite. + * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.approve `conversations.requestSharedInvite.approve` API reference}. + */ + approve: bindApiCall(this, "conversations.requestSharedInvite.approve"), + /** + * @description Denies a request to invite an external user to a channel. + * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.deny `conversations.requestSharedInvite.deny` API reference}. + */ + deny: bindApiCall(this, "conversations.requestSharedInvite.deny"), + /** + * @description Lists requests to add external users to channels with ability to filter. + * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.list `conversations.requestSharedInvite.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "conversations.requestSharedInvite.list") + }, + /** + * @description Sets the purpose for a conversation. + * @see {@link https://api.slack.com/methods/conversations.setPurpose `conversations.setPurpose` API reference}. + */ + setPurpose: bindApiCall(this, "conversations.setPurpose"), + /** + * @description Sets the topic for a conversation. + * @see {@link https://api.slack.com/methods/conversations.setTopic `conversations.setTopic` API reference}. + */ + setTopic: bindApiCall(this, "conversations.setTopic"), + /** + * @description Reverses conversation archival. + * @see {@link https://api.slack.com/methods/conversations.unarchive `conversations.unarchive` API reference}. + */ + unarchive: bindApiCall(this, "conversations.unarchive") + }; + this.dialog = { + /** + * @description Open a dialog with a user. + * @see {@link https://api.slack.com/methods/dialog.open `dialog.open` API reference}. + */ + open: bindApiCall(this, "dialog.open") + }; + this.dnd = { + /** + * @description Ends the current user's Do Not Disturb session immediately. + * @see {@link https://api.slack.com/methods/dnd.endDnd `dnd.endDnd` API reference}. + */ + endDnd: bindApiCallWithOptionalArgument(this, "dnd.endDnd"), + /** + * @description Ends the current user's snooze mode immediately. + * @see {@link https://api.slack.com/methods/dnd.endSnooze `dnd.endSnooze` API reference}. + */ + endSnooze: bindApiCallWithOptionalArgument(this, "dnd.endSnooze"), + /** + * @description Retrieves a user's current Do Not Disturb status. + * @see {@link https://api.slack.com/methods/dnd.info `dnd.info` API reference}. + */ + info: bindApiCallWithOptionalArgument(this, "dnd.info"), + /** + * @description Turns on Do Not Disturb mode for the current user, or changes its duration. + * @see {@link https://api.slack.com/methods/dnd.setSnooze `dnd.setSnooze` API reference}. + */ + setSnooze: bindApiCall(this, "dnd.setSnooze"), + /** + * @description Retrieves the Do Not Disturb status for up to 50 users on a team. + * @see {@link https://api.slack.com/methods/dnd.teamInfo `dnd.teamInfo` API reference}. + */ + teamInfo: bindApiCall(this, "dnd.teamInfo") + }; + this.emoji = { + /** + * @description Lists custom emoji for a team. + * @see {@link https://api.slack.com/methods/emoji.list `emoji.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "emoji.list") + }; + this.files = { + /** + * @description Finishes an upload started with {@link https://api.slack.com/methods/files.getUploadURLExternal `files.getUploadURLExternal`}. + * @see {@link https://api.slack.com/methods/files.completeUploadExternal `files.completeUploadExternal` API reference}. + */ + completeUploadExternal: bindApiCall(this, "files.completeUploadExternal"), + /** + * @description Deletes a file. + * @see {@link https://api.slack.com/methods/files.delete `files.delete` API reference}. + */ + delete: bindApiCall(this, "files.delete"), + /** + * @description Gets a URL for an edge external file upload. + * @see {@link https://api.slack.com/methods/files.getUploadURLExternal `files.getUploadURLExternal` API reference}. + */ + getUploadURLExternal: bindApiCall(this, "files.getUploadURLExternal"), + /** + * @description Gets information about a file. + * @see {@link https://api.slack.com/methods/files.info `files.info` API reference}. + */ + info: bindApiCall(this, "files.info"), + /** + * @description List files for a team, in a channel, or from a user with applied filters. + * @see {@link https://api.slack.com/methods/files.list `files.list` API reference}. + */ + list: bindApiCall(this, "files.list"), + /** + * @description Revokes public/external sharing access for a file. + * @see {@link https://api.slack.com/methods/files.revokePublicURL `files.revokePublicURL` API reference}. + */ + revokePublicURL: bindApiCall(this, "files.revokePublicURL"), + /** + * @description Enables a file for public/external sharing. + * @see {@link https://api.slack.com/methods/files.revokePublicURL `files.revokePublicURL` API reference}. + */ + sharedPublicURL: bindApiCall(this, "files.sharedPublicURL"), + /** + * @description Uploads or creates a file. + * @deprecated Use `uploadV2` instead. See {@link https://api.slack.com/changelog/2024-04-a-better-way-to-upload-files-is-here-to-stay our post on retiring `files.upload`}. + * @see {@link https://api.slack.com/methods/files.upload `files.upload` API reference}. + */ + upload: bindApiCall(this, "files.upload"), + /** + * @description Custom method to support a new way of uploading files to Slack. + * Supports a single file upload + * Supply: + * - (required) single file or content + * - (optional) channel, alt_text, snippet_type, + * Supports multiple file uploads + * Supply: + * - multiple upload_files + * Will try to honor both single file or content data supplied as well + * as multiple file uploads property. + * @see {@link https://tools.slack.dev/node-slack-sdk/web-api#upload-a-file `@slack/web-api` Upload a file documentation}. + */ + uploadV2: bindFilesUploadV2(this), + comments: { + /** + * @description Deletes an existing comment on a file. + * @see {@link https://api.slack.com/methods/files.comments.delete `files.comments.delete` API reference}. + */ + delete: bindApiCall(this, "files.comments.delete") + }, + remote: { + /** + * @description Adds a file from a remote service. + * @see {@link https://api.slack.com/methods/files.remote.add `files.remote.add` API reference}. + */ + add: bindApiCall(this, "files.remote.add"), + /** + * @description Retrieve information about a remote file added to Slack. + * @see {@link https://api.slack.com/methods/files.remote.info `files.remote.info` API reference}. + */ + info: bindApiCall(this, "files.remote.info"), + /** + * @description List remote files added to Slack. + * @see {@link https://api.slack.com/methods/files.remote.list `files.remote.list` API reference}. + */ + list: bindApiCall(this, "files.remote.list"), + /** + * @description Remove a remote file. + * @see {@link https://api.slack.com/methods/files.remote.remove `files.remote.remove` API reference}. + */ + remove: bindApiCall(this, "files.remote.remove"), + /** + * @description Share a remote file into a channel. + * @see {@link https://api.slack.com/methods/files.remote.share `files.remote.share` API reference}. + */ + share: bindApiCall(this, "files.remote.share"), + /** + * @description Updates an existing remote file. + * @see {@link https://api.slack.com/methods/files.remote.update `files.remote.update` API reference}. + */ + update: bindApiCall(this, "files.remote.update") + } + }; + this.functions = { + /** + * @description Signal the failure to execute a Custom Function. + * @see {@link https://api.slack.com/methods/functions.completeError `functions.completeError` API reference}. + */ + completeError: bindApiCall(this, "functions.completeError"), + /** + * @description Signal the successful completion of a Custom Function. + * @see {@link https://api.slack.com/methods/functions.completeSuccess `functions.completeSuccess` API reference}. + */ + completeSuccess: bindApiCall(this, "functions.completeSuccess") + }; + this.migration = { + /** + * @description For Enterprise Grid workspaces, map local user IDs to global user IDs. + * @see {@link https://api.slack.com/methods/migration.exchange `migration.exchange` API reference}. + */ + exchange: bindApiCall(this, "migration.exchange") + }; + this.oauth = { + /** + * @description Exchanges a temporary OAuth verifier code for an access token. + * @deprecated This is a legacy method only used by classic Slack apps. Use `oauth.v2.access` for new Slack apps. + * @see {@link https://api.slack.com/methods/oauth.access `oauth.access` API reference}. + */ + access: bindApiCall(this, "oauth.access"), + v2: { + /** + * @description Exchanges a temporary OAuth verifier code for an access token. + * @see {@link https://api.slack.com/methods/oauth.v2.access `oauth.v2.access` API reference}. + */ + access: bindApiCall(this, "oauth.v2.access"), + /** + * @description Exchanges a legacy access token for a new expiring access token and refresh token. + * @see {@link https://api.slack.com/methods/oauth.v2.exchange `oauth.v2.exchange` API reference}. + */ + exchange: bindApiCall(this, "oauth.v2.exchange") + } + }; + this.openid = { + connect: { + /** + * @description Exchanges a temporary OAuth verifier code for an access token for {@link https://api.slack.com/authentication/sign-in-with-slack Sign in with Slack}. + * @see {@link https://api.slack.com/methods/openid.connect.token `openid.connect.token` API reference}. + */ + token: bindApiCall(this, "openid.connect.token"), + /** + * @description Get the identity of a user who has authorized {@link https://api.slack.com/authentication/sign-in-with-slack Sign in with Slack}. + * @see {@link https://api.slack.com/methods/openid.connect.userInfo `openid.connect.userInfo` API reference}. + */ + userInfo: bindApiCallWithOptionalArgument(this, "openid.connect.userInfo") + } + }; + this.pins = { + /** + * @description Pins an item to a channel. + * @see {@link https://api.slack.com/methods/pins.add `pins.add` API reference}. + */ + add: bindApiCall(this, "pins.add"), + /** + * @description Lists items pinned to a channel. + * @see {@link https://api.slack.com/methods/pins.list `pins.list` API reference}. + */ + list: bindApiCall(this, "pins.list"), + /** + * @description Un-pins an item from a channel. + * @see {@link https://api.slack.com/methods/pins.remove `pins.remove` API reference}. + */ + remove: bindApiCall(this, "pins.remove") + }; + this.reactions = { + /** + * @description Adds a reaction to an item. + * @see {@link https://api.slack.com/methods/reactions.add `reactions.add` API reference}. + */ + add: bindApiCall(this, "reactions.add"), + /** + * @description Gets reactions for an item. + * @see {@link https://api.slack.com/methods/reactions.get `reactions.get` API reference}. + */ + get: bindApiCall(this, "reactions.get"), + /** + * @description List reactions made by a user. + * @see {@link https://api.slack.com/methods/reactions.list `reactions.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "reactions.list"), + /** + * @description Removes a reaction from an item. + * @see {@link https://api.slack.com/methods/reactions.remove `reactions.remove` API reference}. + */ + remove: bindApiCall(this, "reactions.remove") + }; + this.reminders = { + /** + * @description Creates a reminder. + * @see {@link https://api.slack.com/methods/reminders.add `reminders.add` API reference}. + */ + add: bindApiCall(this, "reminders.add"), + /** + * @description Marks a reminder as complete. + * @see {@link https://api.slack.com/methods/reminders.complete `reminders.complete` API reference}. + */ + complete: bindApiCall(this, "reminders.complete"), + /** + * @description Deletes a reminder. + * @see {@link https://api.slack.com/methods/reminders.delete `reminders.delete` API reference}. + */ + delete: bindApiCall(this, "reminders.delete"), + /** + * @description Gets information about a reminder. + * @see {@link https://api.slack.com/methods/reminders.info `reminders.info` API reference}. + */ + info: bindApiCall(this, "reminders.info"), + /** + * @description Lists all reminders created by or for a given user. + * @see {@link https://api.slack.com/methods/reminders.list `reminders.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "reminders.list") + }; + this.rtm = { + /** + * @description Starts a Real Time Messaging session. + * @see {@link https://api.slack.com/methods/rtm.connect `rtm.connect` API reference}. + */ + connect: bindApiCallWithOptionalArgument(this, "rtm.connect"), + /** + * @description Starts a Real Time Messaging session. + * @deprecated Use `rtm.connect` instead. See {@link https://api.slack.com/changelog/2021-10-rtm-start-to-stop our post on retiring `rtm.start`}. + * @see {@link https://api.slack.com/methods/rtm.start `rtm.start` API reference}. + */ + start: bindApiCallWithOptionalArgument(this, "rtm.start") + }; + this.search = { + /** + * @description Searches for messages and files matching a query. + * @see {@link https://api.slack.com/methods/search.all search.all` API reference}. + */ + all: bindApiCall(this, "search.all"), + /** + * @description Searches for files matching a query. + * @see {@link https://api.slack.com/methods/search.files search.files` API reference}. + */ + files: bindApiCall(this, "search.files"), + /** + * @description Searches for messages matching a query. + * @see {@link https://api.slack.com/methods/search.messages search.messages` API reference}. + */ + messages: bindApiCall(this, "search.messages") + }; + this.team = { + /** + * @description Gets the access logs for the current team. + * @see {@link https://api.slack.com/methods/team.accessLogs `team.accessLogs` API reference}. + */ + accessLogs: bindApiCallWithOptionalArgument(this, "team.accessLogs"), + /** + * @description Gets billable users information for the current team. + * @see {@link https://api.slack.com/methods/team.billableInfo `team.billableInfo` API reference}. + */ + billableInfo: bindApiCallWithOptionalArgument(this, "team.billableInfo"), + billing: { + /** + * @description Reads a workspace's billing plan information. + * @see {@link https://api.slack.com/methods/team.billing.info `team.billing.info` API reference}. + */ + info: bindApiCall(this, "team.billing.info") + }, + externalTeams: { + /** + * @description Disconnect an external organization. + * @see {@link https://api.slack.com/methods/team.externalTeams.disconnect `team.externalTeams.disconnect` API reference}. + */ + disconnect: bindApiCall(this, "team.externalTeams.disconnect"), + /** + * @description Returns a list of all the external teams connected and details about the connection. + * @see {@link https://api.slack.com/methods/team.externalTeams.list `team.externalTeams.list` API reference}. + */ + list: bindApiCall(this, "team.externalTeams.list") + }, + /** + * @description Gets information about the current team. + * @see {@link https://api.slack.com/methods/team.info `team.info` API reference}. + */ + info: bindApiCallWithOptionalArgument(this, "team.info"), + /** + * @description Gets the integration logs for the current team. + * @see {@link https://api.slack.com/methods/team.integrationLogs `team.integrationLogs` API reference}. + */ + integrationLogs: bindApiCallWithOptionalArgument(this, "team.integrationLogs"), + preferences: { + /** + * @description Retrieve a list of a workspace's team preferences. + * @see {@link https://api.slack.com/methods/team.preferences.list `team.preferences.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "team.preferences.list") + }, + profile: { + /** + * @description Retrieve a team's profile. + * @see {@link https://api.slack.com/methods/team.profile.get `team.profile.get` API reference}. + */ + get: bindApiCallWithOptionalArgument(this, "team.profile.get") + } + }; + this.tooling = { + tokens: { + /** + * @description Exchanges a refresh token for a new app configuration token. + * @see {@link https://api.slack.com/methods/tooling.tokens.rotate `tooling.tokens.rotate` API reference}. + */ + rotate: bindApiCall(this, "tooling.tokens.rotate") + } + }; + this.usergroups = { + /** + * @description Create a User Group. + * @see {@link https://api.slack.com/methods/usergroups.create `usergroups.create` API reference}. + */ + create: bindApiCall(this, "usergroups.create"), + /** + * @description Disable an existing User Group. + * @see {@link https://api.slack.com/methods/usergroups.disable `usergroups.disable` API reference}. + */ + disable: bindApiCall(this, "usergroups.disable"), + /** + * @description Enable an existing User Group. + * @see {@link https://api.slack.com/methods/usergroups.enable `usergroups.enable` API reference}. + */ + enable: bindApiCall(this, "usergroups.enable"), + /** + * @description List all User Groups for a team. + * @see {@link https://api.slack.com/methods/usergroups.list `usergroups.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "usergroups.list"), + /** + * @description Update an existing User Group. + * @see {@link https://api.slack.com/methods/usergroups.update `usergroups.update` API reference}. + */ + update: bindApiCall(this, "usergroups.update"), + users: { + /** + * @description List all users in a User Group. + * @see {@link https://api.slack.com/methods/usergroups.users.list `usergroups.users.list` API reference}. + */ + list: bindApiCall(this, "usergroups.users.list"), + /** + * @description Update the list of users in a User Group. + * @see {@link https://api.slack.com/methods/usergroups.users.update `usergroups.users.update` API reference}. + */ + update: bindApiCall(this, "usergroups.users.update") + } + }; + this.users = { + /** + * @description List conversations the calling user may access. + * @see {@link https://api.slack.com/methods/users.conversations `users.conversations` API reference}. + */ + conversations: bindApiCall(this, "users.conversations"), + /** + * @description Delete the user profile photo. + * @see {@link https://api.slack.com/methods/users.deletePhoto `users.deletePhoto` API reference}. + */ + deletePhoto: bindApiCall(this, "users.deletePhoto"), + discoverableContacts: { + /** + * @description Lookup an email address to see if someone is on Slack. + * @see {@link https://api.slack.com/methods/users.discoverableContacts.lookup `users.discoverableContacts.lookup` API reference}. + */ + lookup: bindApiCall(this, "users.discoverableContacts.lookup") + }, + /** + * @description Gets user presence information. + * @see {@link https://api.slack.com/methods/users.getPresence `users.getPresence` API reference}. + */ + getPresence: bindApiCall(this, "users.getPresence"), + /** + * @description Get a user's identity. + * @see {@link https://api.slack.com/methods/users.identity `users.identity` API reference}. + */ + identity: bindApiCall(this, "users.identity"), + /** + * @description Gets information about a user. + * @see {@link https://api.slack.com/methods/users.info `users.info` API reference}. + */ + info: bindApiCall(this, "users.info"), + /** + * @description Lists all users in a Slack team. + * @see {@link https://api.slack.com/methods/users.list `users.list` API reference}. + */ + list: bindApiCall(this, "users.list"), + /** + * @description Find a user with an email address. + * @see {@link https://api.slack.com/methods/users.lookupByEmail `users.lookupByEmail` API reference}. + */ + lookupByEmail: bindApiCall(this, "users.lookupByEmail"), + /** + * @description Set the user profile photo. + * @see {@link https://api.slack.com/methods/users.setPhoto `users.setPhoto` API reference}. + */ + setPhoto: bindApiCall(this, "users.setPhoto"), + /** + * @description Manually sets user presence. + * @see {@link https://api.slack.com/methods/users.setPresence `users.setPresence` API reference}. + */ + setPresence: bindApiCall(this, "users.setPresence"), + profile: { + /** + * @description Retrieve a user's profile information, including their custom status. + * @see {@link https://api.slack.com/methods/users.profile.get `users.profile.get` API reference}. + */ + get: bindApiCall(this, "users.profile.get"), + /** + * @description Set a user's profile information, including custom status. + * @see {@link https://api.slack.com/methods/users.profile.set `users.profile.set` API reference}. + */ + set: bindApiCall(this, "users.profile.set") + } + }; + this.views = { + /** + * @description Open a view for a user. + * @see {@link https://api.slack.com/methods/views.open `views.open` API reference}. + */ + open: bindApiCall(this, "views.open"), + /** + * @description Publish a static view for a user. + * @see {@link https://api.slack.com/methods/views.publish `views.publish` API reference}. + */ + publish: bindApiCall(this, "views.publish"), + /** + * @description Push a view onto the stack of a root view. + * @see {@link https://api.slack.com/methods/views.push `views.push` API reference}. + */ + push: bindApiCall(this, "views.push"), + /** + * @description Update an existing view. + * @see {@link https://api.slack.com/methods/views.update `views.update` API reference}. + */ + update: bindApiCall(this, "views.update") + }; + this.stars = { + /** + * @description Save an item for later. Formerly known as adding a star. + * @deprecated Stars can still be added but they can no longer be viewed or interacted with by end-users. + * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. + * @see {@link https://api.slack.com/methods/stars.add `stars.add` API reference}. + */ + add: bindApiCall(this, "stars.add"), + /** + * @description List a user's saved items, formerly known as stars. + * @deprecated Stars can still be listed but they can no longer be viewed or interacted with by end-users. + * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. + * @see {@link https://api.slack.com/methods/stars.list `stars.list` API reference}. + */ + list: bindApiCall(this, "stars.list"), + /** + * @description Remove a saved item from a user's saved items, formerly known as stars. + * @deprecated Stars can still be removed but they can no longer be viewed or interacted with by end-users. + * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. + * @see {@link https://api.slack.com/methods/stars.remove `stars.remove` API reference}. + */ + remove: bindApiCall(this, "stars.remove") + }; + this.workflows = { + /** + * @description Indicate that an app's step in a workflow completed execution. + * @deprecated Steps from Apps is deprecated. + * We're retiring all Slack app functionality around Steps from Apps in September 2024. + * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. + * @see {@link https://api.slack.com/methods/workflows.stepCompleted `workflows.stepCompleted` API reference}. + */ + stepCompleted: bindApiCall(this, "workflows.stepCompleted"), + /** + * @description Indicate that an app's step in a workflow failed to execute. + * @deprecated Steps from Apps is deprecated. + * We're retiring all Slack app functionality around Steps from Apps in September 2024. + * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. + * @see {@link https://api.slack.com/methods/workflows.stepFailed `workflows.stepFailed` API reference}. + */ + stepFailed: bindApiCall(this, "workflows.stepFailed"), + /** + * @description Update the configuration for a workflow step. + * @deprecated Steps from Apps is deprecated. + * We're retiring all Slack app functionality around Steps from Apps in September 2024. + * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. + * @see {@link https://api.slack.com/methods/workflows.updateStep `workflows.updateStep` API reference}. + */ + updateStep: bindApiCall(this, "workflows.updateStep") + }; + if (new.target !== WebClient_1.WebClient && !(new.target.prototype instanceof WebClient_1.WebClient)) { + throw new Error("Attempt to inherit from WebClient methods without inheriting from WebClient"); + } + } + }; + exports2.Methods = Methods; + __exportStar(require_dist3(), exports2); + } +}); + +// node_modules/@slack/web-api/dist/retry-policies.js +var require_retry_policies = __commonJS({ + "node_modules/@slack/web-api/dist/retry-policies.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.rapidRetryPolicy = exports2.fiveRetriesInFiveMinutes = exports2.tenRetriesInAboutThirtyMinutes = void 0; + exports2.tenRetriesInAboutThirtyMinutes = { + retries: 10, + factor: 1.96821, + randomize: true + }; + exports2.fiveRetriesInFiveMinutes = { + retries: 5, + factor: 3.86 + }; + exports2.rapidRetryPolicy = { + minTimeout: 0, + maxTimeout: 1 + }; + var policies = { + tenRetriesInAboutThirtyMinutes: exports2.tenRetriesInAboutThirtyMinutes, + fiveRetriesInFiveMinutes: exports2.fiveRetriesInFiveMinutes, + rapidRetryPolicy: exports2.rapidRetryPolicy + }; + exports2.default = policies; + } +}); + +// node_modules/@slack/web-api/dist/WebClient.js +var require_WebClient = __commonJS({ + "node_modules/@slack/web-api/dist/WebClient.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; + } + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar2 = []; + for (var k2 in o2) if (Object.prototype.hasOwnProperty.call(o2, k2)) ar2[ar2.length] = k2; + return ar2; + }; + return ownKeys(o); + }; + return function(mod2) { + if (mod2 && mod2.__esModule) return mod2; + var result = {}; + if (mod2 != null) { + for (var k2 = ownKeys(mod2), i = 0; i < k2.length; i++) if (k2[i] !== "default") __createBinding(result, mod2, k2[i]); + } + __setModuleDefault(result, mod2); + return result; + }; + }(); + var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __await = exports2 && exports2.__await || function(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + var __asyncGenerator = exports2 && exports2.__asyncGenerator || function(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q2 = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b2) { + q2.push([n, v, a, b2]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle2(q2[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle2(q2[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle2(f, v) { + if (f(v), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]); + } + }; + var __asyncValues = exports2 && exports2.__asyncValues || function(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m2 = o[Symbol.asyncIterator], i; + return m2 ? m2.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve, reject) { + v = o[n](v), settle2(resolve, reject, v.done, v.value); + }); + }; + } + function settle2(resolve, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve({ value: v2, done: d }); + }, reject); + } + }; + var __importDefault = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WebClient = exports2.WebClientEvent = void 0; + exports2.buildThreadTsWarningMessage = buildThreadTsWarningMessage; + var node_path_1 = __require("node:path"); + var node_querystring_1 = __require("node:querystring"); + var node_util_1 = __require("node:util"); + var node_zlib_1 = __importDefault(__require("node:zlib")); + var axios_1 = __importDefault(require_axios()); + var form_data_1 = __importDefault(require_form_data()); + var is_electron_1 = __importDefault(require_is_electron()); + var is_stream_1 = __importDefault(require_is_stream()); + var p_queue_1 = __importDefault(require_dist()); + var p_retry_1 = __importStar(require_p_retry()); + var errors_1 = require_errors3(); + var file_upload_1 = require_file_upload(); + var helpers_1 = __importDefault(require_helpers()); + var instrument_1 = require_instrument(); + var logger_1 = require_logger2(); + var methods_1 = require_methods(); + var retry_policies_1 = require_retry_policies(); + var axiosHeaderPropsToIgnore = [ + "delete", + "common", + "get", + "put", + "head", + "post", + "link", + "patch", + "purge", + "unlink", + "options" + ]; + var defaultFilename = "Untitled"; + var defaultPageSize = 200; + var noopPageReducer = () => void 0; + var WebClientEvent; + (function(WebClientEvent2) { + WebClientEvent2["RATE_LIMITED"] = "rate_limited"; + })(WebClientEvent || (exports2.WebClientEvent = WebClientEvent = {})); + var WebClient2 = class _WebClient extends methods_1.Methods { + /** + * @param token - An API token to authenticate/authorize with Slack (usually start with `xoxp`, `xoxb`) + * @param {Object} [webClientOptions] - Configuration options. + * @param {Function} [webClientOptions.requestInterceptor] - An interceptor to mutate outgoing requests. See {@link https://axios-http.com/docs/interceptors Axios interceptors} + * @param {Function} [webClientOptions.adapter] - An adapter to allow custom handling of requests. Useful if you would like to use a pre-configured http client. See {@link https://github.com/axios/axios/blob/v1.x/README.md?plain=1#L586 Axios adapter} + */ + constructor(token, { slackApiUrl = "https://slack.com/api/", logger = void 0, logLevel = void 0, maxRequestConcurrency = 100, retryConfig = retry_policies_1.tenRetriesInAboutThirtyMinutes, agent = void 0, tls = void 0, timeout = 0, rejectRateLimitedCalls = false, headers = {}, teamId = void 0, allowAbsoluteUrls = true, attachOriginalToWebAPIRequestError = true, requestInterceptor = void 0, adapter = void 0 } = {}) { + super(); + this.token = token; + this.slackApiUrl = slackApiUrl; + if (!this.slackApiUrl.endsWith("/")) { + this.slackApiUrl += "/"; + } + this.retryConfig = retryConfig; + this.requestQueue = new p_queue_1.default({ concurrency: maxRequestConcurrency }); + this.tlsConfig = tls !== void 0 ? tls : {}; + this.rejectRateLimitedCalls = rejectRateLimitedCalls; + this.teamId = teamId; + this.allowAbsoluteUrls = allowAbsoluteUrls; + this.attachOriginalToWebAPIRequestError = attachOriginalToWebAPIRequestError; + if (typeof logger !== "undefined") { + this.logger = logger; + if (typeof logLevel !== "undefined") { + this.logger.debug("The logLevel given to WebClient was ignored as you also gave logger"); + } + } else { + this.logger = (0, logger_1.getLogger)(_WebClient.loggerName, logLevel !== null && logLevel !== void 0 ? logLevel : logger_1.LogLevel.INFO, logger); + } + if (this.token && !headers.Authorization) + headers.Authorization = `Bearer ${this.token}`; + this.axios = axios_1.default.create({ + adapter: adapter ? (config3) => adapter(Object.assign(Object.assign({}, config3), { adapter: void 0 })) : void 0, + timeout, + baseURL: this.slackApiUrl, + headers: (0, is_electron_1.default)() ? headers : Object.assign({ "User-Agent": (0, instrument_1.getUserAgent)() }, headers), + httpAgent: agent, + httpsAgent: agent, + validateStatus: () => true, + // all HTTP status codes should result in a resolved promise (as opposed to only 2xx) + maxRedirects: 0, + // disabling axios' automatic proxy support: + // axios would read from envvars to configure a proxy automatically, but it doesn't support TLS destinations. + // for compatibility with https://api.slack.com, and for a larger set of possible proxies (SOCKS or other + // protocols), users of this package should use the `agent` option to configure a proxy. + proxy: false + }); + this.axios.defaults.headers.post["Content-Type"] = void 0; + if (requestInterceptor) { + this.axios.interceptors.request.use(requestInterceptor, null); + } + this.axios.interceptors.request.use(this.serializeApiCallData.bind(this), null); + this.logger.debug("initialized"); + } + /** + * Generic method for calling a Web API method + * @param method - the Web API method to call {@link https://api.slack.com/methods} + * @param options - options + */ + apiCall(method_1) { + return __awaiter(this, arguments, void 0, function* (method, options = {}) { + this.logger.debug(`apiCall('${method}') start`); + warnDeprecations(method, this.logger); + warnIfFallbackIsMissing(method, this.logger, options); + warnIfThreadTsIsNotString(method, this.logger, options); + if (typeof options === "string" || typeof options === "number" || typeof options === "boolean") { + throw new TypeError(`Expected an options argument but instead received a ${typeof options}`); + } + (0, file_upload_1.warnIfNotUsingFilesUploadV2)(method, this.logger); + if (method === "files.uploadV2") + return this.filesUploadV2(options); + const headers = {}; + if (options.token) + headers.Authorization = `Bearer ${options.token}`; + const url2 = this.deriveRequestUrl(method); + const response = yield this.makeRequest(url2, Object.assign({ team_id: this.teamId }, options), headers); + const result = yield this.buildResult(response); + this.logger.debug(`http request result: ${JSON.stringify(result)}`); + if (result.response_metadata !== void 0 && result.response_metadata.warnings !== void 0) { + result.response_metadata.warnings.forEach(this.logger.warn.bind(this.logger)); + } + if (result.response_metadata !== void 0 && result.response_metadata.messages !== void 0) { + for (const msg of result.response_metadata.messages) { + const errReg = /\[ERROR\](.*)/; + const warnReg = /\[WARN\](.*)/; + if (errReg.test(msg)) { + const errMatch = msg.match(errReg); + if (errMatch != null) { + this.logger.error(errMatch[1].trim()); + } + } else if (warnReg.test(msg)) { + const warnMatch = msg.match(warnReg); + if (warnMatch != null) { + this.logger.warn(warnMatch[1].trim()); + } + } + } + } + if (!result.ok && response.headers["content-type"] !== "application/gzip") { + throw (0, errors_1.platformErrorFromResult)(result); + } + if ("ok" in result && result.ok === false) { + throw (0, errors_1.platformErrorFromResult)(result); + } + this.logger.debug(`apiCall('${method}') end`); + return result; + }); + } + paginate(method, options, shouldStop, reduce) { + const pageSize = (() => { + if (options !== void 0 && typeof options.limit === "number") { + const { limit } = options; + options.limit = void 0; + return limit; + } + return defaultPageSize; + })(); + function generatePages() { + return __asyncGenerator(this, arguments, function* generatePages_1() { + let result; + let paginationOptions = { + limit: pageSize + }; + if (options !== void 0 && options.cursor !== void 0) { + paginationOptions.cursor = options.cursor; + } + while (result === void 0 || paginationOptions !== void 0) { + result = yield __await(this.apiCall(method, Object.assign(options !== void 0 ? options : {}, paginationOptions))); + yield yield __await(result); + paginationOptions = paginationOptionsForNextPage(result, pageSize); + } + }); + } + if (shouldStop === void 0) { + return generatePages.call(this); + } + const pageReducer = reduce !== void 0 ? reduce : noopPageReducer; + let index2 = 0; + return (() => __awaiter(this, void 0, void 0, function* () { + var _a2, e_1, _b, _c2; + const pageIterator = generatePages.call(this); + const firstIteratorResult = yield pageIterator.next(void 0); + const firstPage = firstIteratorResult.value; + let accumulator = pageReducer(void 0, firstPage, index2); + index2 += 1; + if (shouldStop(firstPage)) { + return accumulator; + } + try { + for (var _d2 = true, pageIterator_1 = __asyncValues(pageIterator), pageIterator_1_1; pageIterator_1_1 = yield pageIterator_1.next(), _a2 = pageIterator_1_1.done, !_a2; _d2 = true) { + _c2 = pageIterator_1_1.value; + _d2 = false; + const page = _c2; + accumulator = pageReducer(accumulator, page, index2); + if (shouldStop(page)) { + return accumulator; + } + index2 += 1; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d2 && !_a2 && (_b = pageIterator_1.return)) yield _b.call(pageIterator_1); + } finally { + if (e_1) throw e_1.error; + } + } + return accumulator; + }))(); + } + /** + * This wrapper method provides an easy way to upload files using the following endpoints: + * + * **#1**: For each file submitted with this method, submit filenames + * and file metadata to {@link https://api.slack.com/methods/files.getUploadURLExternal files.getUploadURLExternal} to request a URL to + * which to send the file data to and an id for the file + * + * **#2**: for each returned file `upload_url`, upload corresponding file to + * URLs returned from step 1 (e.g. https://files.slack.com/upload/v1/...\") + * + * **#3**: Complete uploads {@link https://api.slack.com/methods/files.completeUploadExternal files.completeUploadExternal} + * @param options + */ + filesUploadV2(options) { + return __awaiter(this, void 0, void 0, function* () { + this.logger.debug("files.uploadV2() start"); + const fileUploads = yield this.getAllFileUploads(options); + const fileUploadsURLRes = yield this.fetchAllUploadURLExternal(fileUploads); + fileUploadsURLRes.forEach((res, idx) => { + fileUploads[idx].upload_url = res.upload_url; + fileUploads[idx].file_id = res.file_id; + }); + yield this.postFileUploadsToExternalURL(fileUploads, options); + const completion = yield this.completeFileUploads(fileUploads); + return { ok: true, files: completion }; + }); + } + /** + * For each file submitted with this method, submits filenames + * and file metadata to files.getUploadURLExternal to request a URL to + * which to send the file data to and an id for the file + * @param fileUploads + */ + fetchAllUploadURLExternal(fileUploads) { + return __awaiter(this, void 0, void 0, function* () { + return Promise.all(fileUploads.map((upload) => { + const options = { + filename: upload.filename, + length: upload.length, + alt_text: upload.alt_text, + snippet_type: upload.snippet_type + }; + if ("token" in upload) { + options.token = upload.token; + } + return this.files.getUploadURLExternal(options); + })); + }); + } + /** + * Complete uploads. + * @param fileUploads + * @returns + */ + completeFileUploads(fileUploads) { + return __awaiter(this, void 0, void 0, function* () { + const toComplete = Object.values((0, file_upload_1.getAllFileUploadsToComplete)(fileUploads)); + return Promise.all(toComplete.map((job) => this.files.completeUploadExternal(job))); + }); + } + /** + * for each returned file upload URL, upload corresponding file + * @param fileUploads + * @returns + */ + postFileUploadsToExternalURL(fileUploads, options) { + return __awaiter(this, void 0, void 0, function* () { + return Promise.all(fileUploads.map((upload) => __awaiter(this, void 0, void 0, function* () { + const { upload_url, file_id, filename, data } = upload; + const body = data; + if (upload_url) { + const headers = {}; + if (options.token) + headers.Authorization = `Bearer ${options.token}`; + const uploadRes = yield this.makeRequest(upload_url, { + body + }, headers); + if (uploadRes.status !== 200) { + return Promise.reject(Error(`Failed to upload file (id:${file_id}, filename: ${filename})`)); + } + const returnData = { ok: true, body: uploadRes.data }; + return Promise.resolve(returnData); + } + return Promise.reject(Error(`No upload url found for file (id: ${file_id}, filename: ${filename}`)); + }))); + }); + } + /** + * @param options All file uploads arguments + * @returns An array of file upload entries + */ + getAllFileUploads(options) { + return __awaiter(this, void 0, void 0, function* () { + let fileUploads = []; + if ("file" in options || "content" in options) { + fileUploads.push(yield (0, file_upload_1.getFileUploadJob)(options, this.logger)); + } + if ("file_uploads" in options) { + fileUploads = fileUploads.concat(yield (0, file_upload_1.getMultipleFileUploadJobs)(options, this.logger)); + } + return fileUploads; + }); + } + /** + * Low-level function to make a single API request. handles queuing, retries, and http-level errors + */ + makeRequest(url_1, body_1) { + return __awaiter(this, arguments, void 0, function* (url2, body, headers = {}) { + const task = () => this.requestQueue.add(() => __awaiter(this, void 0, void 0, function* () { + try { + const config3 = Object.assign({ headers }, this.tlsConfig); + if (url2.endsWith("admin.analytics.getFile")) { + config3.responseType = "arraybuffer"; + } + if (url2.endsWith("apps.event.authorizations.list")) { + body.token = void 0; + } + this.logger.debug(`http request url: ${url2}`); + this.logger.debug(`http request body: ${JSON.stringify(redact(body))}`); + let allHeaders = Object.keys(this.axios.defaults.headers).reduce((acc, cur) => { + if (!axiosHeaderPropsToIgnore.includes(cur)) { + acc[cur] = this.axios.defaults.headers[cur]; + } + return acc; + }, {}); + allHeaders = Object.assign(Object.assign(Object.assign({}, this.axios.defaults.headers.common), allHeaders), headers); + this.logger.debug(`http request headers: ${JSON.stringify(redact(allHeaders))}`); + const response = yield this.axios.post(url2, body, config3); + this.logger.debug("http response received"); + if (response.status === 429) { + const retrySec = parseRetryHeaders(response); + if (retrySec !== void 0) { + this.emit(WebClientEvent.RATE_LIMITED, retrySec, { url: url2, body }); + if (this.rejectRateLimitedCalls) { + throw new p_retry_1.AbortError((0, errors_1.rateLimitedErrorWithDelay)(retrySec)); + } + this.logger.info(`API Call failed due to rate limiting. Will retry in ${retrySec} seconds.`); + this.requestQueue.pause(); + yield (0, helpers_1.default)(retrySec * 1e3); + this.requestQueue.start(); + throw new Error(`A rate limit was exceeded (url: ${url2}, retry-after: ${retrySec})`); + } + throw new p_retry_1.AbortError(new Error(`Retry header did not contain a valid timeout (url: ${url2}, retry-after header: ${response.headers["retry-after"]})`)); + } + if (response.status !== 200) { + throw (0, errors_1.httpErrorFromResponse)(response); + } + return response; + } catch (error) { + const e = error; + this.logger.warn("http request failed", e.message); + if (e.request) { + throw (0, errors_1.requestErrorWithOriginal)(e, this.attachOriginalToWebAPIRequestError); + } + throw error; + } + })); + return (0, p_retry_1.default)(task, this.retryConfig); + }); + } + /** + * Get the complete request URL for the provided URL. + * @param url - The resource to POST to. Either a Slack API method or absolute URL. + */ + deriveRequestUrl(url2) { + const isAbsoluteURL2 = url2.startsWith("https://") || url2.startsWith("http://"); + if (isAbsoluteURL2 && this.allowAbsoluteUrls) { + return url2; + } + return `${this.axios.getUri() + url2}`; + } + /** + * Transforms options (a simple key-value object) into an acceptable value for a body. This can be either + * a string, used when posting with a content-type of url-encoded. Or, it can be a readable stream, used + * when the options contain a binary (a stream or a buffer) and the upload should be done with content-type + * multipart/form-data. + * @param config - The Axios request configuration object + */ + serializeApiCallData(config3) { + const { data, headers } = config3; + let containsBinaryData = false; + const flattened = Object.entries(data).map(([key, value]) => { + if (value === void 0 || value === null) { + return []; + } + let serializedValue = value; + if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { + containsBinaryData = true; + } else if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") { + serializedValue = JSON.stringify(value); + } + return [key, serializedValue]; + }); + if (containsBinaryData) { + this.logger.debug("Request arguments contain binary data"); + const form = flattened.reduce((frm, [key, value]) => { + if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { + const opts = {}; + opts.filename = (() => { + const streamOrBuffer = value; + if (typeof streamOrBuffer.name === "string") { + return (0, node_path_1.basename)(streamOrBuffer.name); + } + if (typeof streamOrBuffer.path === "string") { + return (0, node_path_1.basename)(streamOrBuffer.path); + } + return defaultFilename; + })(); + frm.append(key, value, opts); + } else if (key !== void 0 && value !== void 0) { + frm.append(key, value); + } + return frm; + }, new form_data_1.default()); + if (headers) { + for (const [header, value] of Object.entries(form.getHeaders())) { + headers[header] = value; + } + } + config3.data = form; + config3.headers = headers; + return config3; + } + if (headers) + headers["Content-Type"] = "application/x-www-form-urlencoded"; + const initialValue = {}; + config3.data = (0, node_querystring_1.stringify)(flattened.reduce((accumulator, [key, value]) => { + if (key !== void 0 && value !== void 0) { + accumulator[key] = value; + } + return accumulator; + }, initialValue)); + config3.headers = headers; + return config3; + } + /** + * Processes an HTTP response into a WebAPICallResult by performing JSON parsing on the body and merging relevant + * HTTP headers into the object. + * @param response - an http response + */ + buildResult(response) { + return __awaiter(this, void 0, void 0, function* () { + let { data } = response; + const isGzipResponse = response.headers["content-type"] === "application/gzip"; + if (isGzipResponse) { + try { + const unzippedData = yield new Promise((resolve, reject) => { + node_zlib_1.default.unzip(data, (err, buf) => { + if (err) { + return reject(err); + } + return resolve(buf.toString().split("\n")); + }); + }).then((res) => res).catch((err) => { + throw err; + }); + const fileData = []; + if (Array.isArray(unzippedData)) { + for (const dataset of unzippedData) { + if (dataset && dataset.length > 0) { + fileData.push(JSON.parse(dataset)); + } + } + } + data = { file_data: fileData }; + } catch (err) { + data = { ok: false, error: err }; + } + } else if (!isGzipResponse && response.request.path === "/api/admin.analytics.getFile") { + data = JSON.parse(new node_util_1.TextDecoder().decode(data)); + } + if (typeof data === "string") { + try { + data = JSON.parse(data); + } catch (_) { + data = { ok: false, error: data }; + } + } + if (data.response_metadata === void 0) { + data.response_metadata = {}; + } + if (response.headers["x-oauth-scopes"] !== void 0) { + data.response_metadata.scopes = response.headers["x-oauth-scopes"].trim().split(/\s*,\s*/); + } + if (response.headers["x-accepted-oauth-scopes"] !== void 0) { + data.response_metadata.acceptedScopes = response.headers["x-accepted-oauth-scopes"].trim().split(/\s*,\s*/); + } + const retrySec = parseRetryHeaders(response); + if (retrySec !== void 0) { + data.response_metadata.retryAfter = retrySec; + } + return data; + }); + } + }; + exports2.WebClient = WebClient2; + WebClient2.loggerName = "WebClient"; + exports2.default = WebClient2; + function paginationOptionsForNextPage(previousResult, pageSize) { + if (previousResult !== void 0 && previousResult.response_metadata !== void 0 && previousResult.response_metadata.next_cursor !== void 0 && previousResult.response_metadata.next_cursor !== "") { + return { + limit: pageSize, + cursor: previousResult.response_metadata.next_cursor + }; + } + return void 0; + } + function parseRetryHeaders(response) { + if (response.headers["retry-after"] !== void 0) { + const retryAfter = Number.parseInt(response.headers["retry-after"], 10); + if (!Number.isNaN(retryAfter)) { + return retryAfter; + } + } + return void 0; + } + function warnDeprecations(method, logger) { + const deprecatedMethods = ["workflows."]; + const isDeprecated = deprecatedMethods.some((depMethod) => { + const re2 = new RegExp(`^${depMethod}`); + return re2.test(method); + }); + if (isDeprecated) { + logger.warn(`${method} is deprecated. Please check on https://api.slack.com/methods for an alternative.`); + } + } + function warnIfFallbackIsMissing(method, logger, options) { + const targetMethods = ["chat.postEphemeral", "chat.postMessage", "chat.scheduleMessage"]; + const isTargetMethod = targetMethods.includes(method); + const hasAttachments = (args) => Array.isArray(args.attachments) && args.attachments.length; + const missingAttachmentFallbackDetected = (args) => Array.isArray(args.attachments) && args.attachments.some((attachment) => !attachment.fallback || attachment.fallback.trim() === ""); + const isEmptyText = (args) => args.text === void 0 || args.text === null || args.text === ""; + const buildMissingTextWarning = () => `The top-level \`text\` argument is missing in the request payload for a ${method} call - It's a best practice to always provide a \`text\` argument when posting a message. The \`text\` is used in places where the content cannot be rendered such as: system push notifications, assistive technology such as screen readers, etc.`; + const buildMissingFallbackWarning = () => `Additionally, the attachment-level \`fallback\` argument is missing in the request payload for a ${method} call - To avoid this warning, it is recommended to always provide a top-level \`text\` argument when posting a message. Alternatively, you can provide an attachment-level \`fallback\` argument, though this is now considered a legacy field (see https://api.slack.com/reference/messaging/attachments#legacy_fields for more details).`; + if (isTargetMethod && typeof options === "object") { + if (hasAttachments(options)) { + if (missingAttachmentFallbackDetected(options) && isEmptyText(options)) { + logger.warn(buildMissingTextWarning()); + logger.warn(buildMissingFallbackWarning()); + } + } else if (isEmptyText(options)) { + logger.warn(buildMissingTextWarning()); + } + } + } + function warnIfThreadTsIsNotString(method, logger, options) { + const targetMethods = ["chat.postEphemeral", "chat.postMessage", "chat.scheduleMessage", "files.upload"]; + const isTargetMethod = targetMethods.includes(method); + if (isTargetMethod && (options === null || options === void 0 ? void 0 : options.thread_ts) !== void 0 && typeof (options === null || options === void 0 ? void 0 : options.thread_ts) !== "string") { + logger.warn(buildThreadTsWarningMessage(method)); + } + } + function buildThreadTsWarningMessage(method) { + return `The given thread_ts value in the request payload for a ${method} call is a float value. We highly recommend using a string value instead.`; + } + function redact(body) { + const flattened = Object.entries(body).map(([key, value]) => { + if (value === void 0 || value === null) { + return []; + } + let serializedValue = value; + if (key.match(/.*token.*/) !== null || key.match(/[Aa]uthorization/)) { + serializedValue = "[[REDACTED]]"; + } + if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { + serializedValue = "[[BINARY VALUE OMITTED]]"; + } else if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") { + serializedValue = JSON.stringify(value); + } + return [key, serializedValue]; + }); + const initialValue = {}; + return flattened.reduce((accumulator, [key, value]) => { + if (key !== void 0 && value !== void 0) { + accumulator[key] = value; + } + return accumulator; + }, initialValue); + } + } +}); + +// node_modules/@slack/web-api/dist/types/request/index.js +var require_request = __commonJS({ + "node_modules/@slack/web-api/dist/types/request/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/web-api/dist/types/response/index.js +var require_response = __commonJS({ + "node_modules/@slack/web-api/dist/types/response/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/web-api/dist/index.js +var require_dist4 = __commonJS({ + "node_modules/@slack/web-api/dist/index.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; + } + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { + for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); + }; + var __importDefault = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.addAppMetadata = exports2.retryPolicies = exports2.ErrorCode = exports2.LogLevel = exports2.WebClientEvent = exports2.WebClient = void 0; + var WebClient_1 = require_WebClient(); + Object.defineProperty(exports2, "WebClient", { enumerable: true, get: function() { + return WebClient_1.WebClient; + } }); + Object.defineProperty(exports2, "WebClientEvent", { enumerable: true, get: function() { + return WebClient_1.WebClientEvent; + } }); + var logger_1 = require_logger2(); + Object.defineProperty(exports2, "LogLevel", { enumerable: true, get: function() { + return logger_1.LogLevel; + } }); + var errors_1 = require_errors3(); + Object.defineProperty(exports2, "ErrorCode", { enumerable: true, get: function() { + return errors_1.ErrorCode; + } }); + var retry_policies_1 = require_retry_policies(); + Object.defineProperty(exports2, "retryPolicies", { enumerable: true, get: function() { + return __importDefault(retry_policies_1).default; + } }); + var instrument_1 = require_instrument(); + Object.defineProperty(exports2, "addAppMetadata", { enumerable: true, get: function() { + return instrument_1.addAppMetadata; + } }); + __exportStar(require_methods(), exports2); + __exportStar(require_request(), exports2); + __exportStar(require_response(), exports2); + } +}); + +// node_modules/@prisma/client/runtime/library.js +var require_library = __commonJS({ + "node_modules/@prisma/client/runtime/library.js"(exports, module) { + "use strict"; + var eu = Object.create; + var Nr = Object.defineProperty; + var tu = Object.getOwnPropertyDescriptor; + var ru = Object.getOwnPropertyNames; + var nu = Object.getPrototypeOf; + var iu = Object.prototype.hasOwnProperty; + var Z = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports); + var Ut = (e, t) => { + for (var r in t) Nr(e, r, { get: t[r], enumerable: true }); + }; + var ho = (e, t, r, n) => { + if (t && typeof t == "object" || typeof t == "function") for (let i of ru(t)) !iu.call(e, i) && i !== r && Nr(e, i, { get: () => t[i], enumerable: !(n = tu(t, i)) || n.enumerable }); + return e; + }; + var k = (e, t, r) => (r = e != null ? eu(nu(e)) : {}, ho(t || !e || !e.__esModule ? Nr(r, "default", { value: e, enumerable: true }) : r, e)); + var ou = (e) => ho(Nr({}, "__esModule", { value: true }), e); + var jo = Z((pf, Zn) => { + "use strict"; + var v = Zn.exports; + Zn.exports.default = v; + var D = "\x1B[", Ht = "\x1B]", ft = "\x07", Jr = ";", qo = process.env.TERM_PROGRAM === "Apple_Terminal"; + v.cursorTo = (e, t) => { + if (typeof e != "number") throw new TypeError("The `x` argument is required"); + return typeof t != "number" ? D + (e + 1) + "G" : D + (t + 1) + ";" + (e + 1) + "H"; + }; + v.cursorMove = (e, t) => { + if (typeof e != "number") throw new TypeError("The `x` argument is required"); + let r = ""; + return e < 0 ? r += D + -e + "D" : e > 0 && (r += D + e + "C"), t < 0 ? r += D + -t + "A" : t > 0 && (r += D + t + "B"), r; + }; + v.cursorUp = (e = 1) => D + e + "A"; + v.cursorDown = (e = 1) => D + e + "B"; + v.cursorForward = (e = 1) => D + e + "C"; + v.cursorBackward = (e = 1) => D + e + "D"; + v.cursorLeft = D + "G"; + v.cursorSavePosition = qo ? "\x1B7" : D + "s"; + v.cursorRestorePosition = qo ? "\x1B8" : D + "u"; + v.cursorGetPosition = D + "6n"; + v.cursorNextLine = D + "E"; + v.cursorPrevLine = D + "F"; + v.cursorHide = D + "?25l"; + v.cursorShow = D + "?25h"; + v.eraseLines = (e) => { + let t = ""; + for (let r = 0; r < e; r++) t += v.eraseLine + (r < e - 1 ? v.cursorUp() : ""); + return e && (t += v.cursorLeft), t; + }; + v.eraseEndLine = D + "K"; + v.eraseStartLine = D + "1K"; + v.eraseLine = D + "2K"; + v.eraseDown = D + "J"; + v.eraseUp = D + "1J"; + v.eraseScreen = D + "2J"; + v.scrollUp = D + "S"; + v.scrollDown = D + "T"; + v.clearScreen = "\x1Bc"; + v.clearTerminal = process.platform === "win32" ? `${v.eraseScreen}${D}0f` : `${v.eraseScreen}${D}3J${D}H`; + v.beep = ft; + v.link = (e, t) => [Ht, "8", Jr, Jr, t, ft, e, Ht, "8", Jr, Jr, ft].join(""); + v.image = (e, t = {}) => { + let r = `${Ht}1337;File=inline=1`; + return t.width && (r += `;width=${t.width}`), t.height && (r += `;height=${t.height}`), t.preserveAspectRatio === false && (r += ";preserveAspectRatio=0"), r + ":" + e.toString("base64") + ft; + }; + v.iTerm = { setCwd: (e = process.cwd()) => `${Ht}50;CurrentDir=${e}${ft}`, annotation: (e, t = {}) => { + let r = `${Ht}1337;`, n = typeof t.x < "u", i = typeof t.y < "u"; + if ((n || i) && !(n && i && typeof t.length < "u")) throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined"); + return e = e.replace(/\|/g, ""), r += t.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=", t.length > 0 ? r += (n ? [e, t.length, t.x, t.y] : [t.length, e]).join("|") : r += e, r + ft; + } }; + }); + var Xn = Z((df, Vo) => { + "use strict"; + Vo.exports = (e, t = process.argv) => { + let r = e.startsWith("-") ? "" : e.length === 1 ? "-" : "--", n = t.indexOf(r + e), i = t.indexOf("--"); + return n !== -1 && (i === -1 || n < i); + }; + }); + var Go = Z((mf, Uo) => { + "use strict"; + var Gu = __require("os"), Bo = __require("tty"), de = Xn(), { env: Q } = process, Qe; + de("no-color") || de("no-colors") || de("color=false") || de("color=never") ? Qe = 0 : (de("color") || de("colors") || de("color=true") || de("color=always")) && (Qe = 1); + "FORCE_COLOR" in Q && (Q.FORCE_COLOR === "true" ? Qe = 1 : Q.FORCE_COLOR === "false" ? Qe = 0 : Qe = Q.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(Q.FORCE_COLOR, 10), 3)); + function ei(e) { + return e === 0 ? false : { level: e, hasBasic: true, has256: e >= 2, has16m: e >= 3 }; + } + function ti(e, t) { + if (Qe === 0) return 0; + if (de("color=16m") || de("color=full") || de("color=truecolor")) return 3; + if (de("color=256")) return 2; + if (e && !t && Qe === void 0) return 0; + let r = Qe || 0; + if (Q.TERM === "dumb") return r; + if (process.platform === "win32") { + let n = Gu.release().split("."); + return Number(n[0]) >= 10 && Number(n[2]) >= 10586 ? Number(n[2]) >= 14931 ? 3 : 2 : 1; + } + if ("CI" in Q) return ["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((n) => n in Q) || Q.CI_NAME === "codeship" ? 1 : r; + if ("TEAMCITY_VERSION" in Q) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Q.TEAMCITY_VERSION) ? 1 : 0; + if (Q.COLORTERM === "truecolor") return 3; + if ("TERM_PROGRAM" in Q) { + let n = parseInt((Q.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (Q.TERM_PROGRAM) { + case "iTerm.app": + return n >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; + } + } + return /-256(color)?$/i.test(Q.TERM) ? 2 : /^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Q.TERM) || "COLORTERM" in Q ? 1 : r; + } + function Qu(e) { + let t = ti(e, e && e.isTTY); + return ei(t); + } + Uo.exports = { supportsColor: Qu, stdout: ei(ti(true, Bo.isatty(1))), stderr: ei(ti(true, Bo.isatty(2))) }; + }); + var Wo = Z((ff, Jo) => { + "use strict"; + var Ju = Go(), gt = Xn(); + function Qo(e) { + if (/^\d{3,4}$/.test(e)) { + let r = /(\d{1,2})(\d{2})/.exec(e); + return { major: 0, minor: parseInt(r[1], 10), patch: parseInt(r[2], 10) }; + } + let t = (e || "").split(".").map((r) => parseInt(r, 10)); + return { major: t[0], minor: t[1], patch: t[2] }; + } + function ri(e) { + let { env: t } = process; + if ("FORCE_HYPERLINK" in t) return !(t.FORCE_HYPERLINK.length > 0 && parseInt(t.FORCE_HYPERLINK, 10) === 0); + if (gt("no-hyperlink") || gt("no-hyperlinks") || gt("hyperlink=false") || gt("hyperlink=never")) return false; + if (gt("hyperlink=true") || gt("hyperlink=always") || "NETLIFY" in t) return true; + if (!Ju.supportsColor(e) || e && !e.isTTY || process.platform === "win32" || "CI" in t || "TEAMCITY_VERSION" in t) return false; + if ("TERM_PROGRAM" in t) { + let r = Qo(t.TERM_PROGRAM_VERSION); + switch (t.TERM_PROGRAM) { + case "iTerm.app": + return r.major === 3 ? r.minor >= 1 : r.major > 3; + case "WezTerm": + return r.major >= 20200620; + case "vscode": + return r.major > 1 || r.major === 1 && r.minor >= 72; + } + } + if ("VTE_VERSION" in t) { + if (t.VTE_VERSION === "0.50.0") return false; + let r = Qo(t.VTE_VERSION); + return r.major > 0 || r.minor >= 50; + } + return false; + } + Jo.exports = { supportsHyperlink: ri, stdout: ri(process.stdout), stderr: ri(process.stderr) }; + }); + var Ko = Z((gf, Kt) => { + "use strict"; + var Wu = jo(), ni = Wo(), Ho = (e, t, { target: r = "stdout", ...n } = {}) => ni[r] ? Wu.link(e, t) : n.fallback === false ? e : typeof n.fallback == "function" ? n.fallback(e, t) : `${e} (\u200B${t}\u200B)`; + Kt.exports = (e, t, r = {}) => Ho(e, t, r); + Kt.exports.stderr = (e, t, r = {}) => Ho(e, t, { target: "stderr", ...r }); + Kt.exports.isSupported = ni.stdout; + Kt.exports.stderr.isSupported = ni.stderr; + }); + var oi = Z((Rf, Hu) => { + Hu.exports = { name: "@prisma/engines-version", version: "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2", main: "index.js", types: "index.d.ts", license: "Apache-2.0", author: "Tim Suchanek ", prisma: { enginesVersion: "605197351a3c8bdd595af2d2a9bc3025bca48ea2" }, repository: { type: "git", url: "https://github.com/prisma/engines-wrapper.git", directory: "packages/engines-version" }, devDependencies: { "@types/node": "18.19.34", typescript: "4.9.5" }, files: ["index.js", "index.d.ts"], scripts: { build: "tsc -d" } }; + }); + var si = Z((Wr) => { + "use strict"; + Object.defineProperty(Wr, "__esModule", { value: true }); + Wr.enginesVersion = void 0; + Wr.enginesVersion = oi().prisma.enginesVersion; + }); + var Xo = Z((Gf, Yu) => { + Yu.exports = { name: "dotenv", version: "16.0.3", description: "Loads environment variables from .env file", main: "lib/main.js", types: "lib/main.d.ts", exports: { ".": { require: "./lib/main.js", types: "./lib/main.d.ts", default: "./lib/main.js" }, "./config": "./config.js", "./config.js": "./config.js", "./lib/env-options": "./lib/env-options.js", "./lib/env-options.js": "./lib/env-options.js", "./lib/cli-options": "./lib/cli-options.js", "./lib/cli-options.js": "./lib/cli-options.js", "./package.json": "./package.json" }, scripts: { "dts-check": "tsc --project tests/types/tsconfig.json", lint: "standard", "lint-readme": "standard-markdown", pretest: "npm run lint && npm run dts-check", test: "tap tests/*.js --100 -Rspec", prerelease: "npm test", release: "standard-version" }, repository: { type: "git", url: "git://github.com/motdotla/dotenv.git" }, keywords: ["dotenv", "env", ".env", "environment", "variables", "config", "settings"], readmeFilename: "README.md", license: "BSD-2-Clause", devDependencies: { "@types/node": "^17.0.9", decache: "^4.6.1", dtslint: "^3.7.0", sinon: "^12.0.1", standard: "^16.0.4", "standard-markdown": "^7.1.0", "standard-version": "^9.3.2", tap: "^15.1.6", tar: "^6.1.11", typescript: "^4.5.4" }, engines: { node: ">=12" } }; + }); + var ts = Z((Qf, Kr) => { + "use strict"; + var Zu = __require("fs"), es = __require("path"), Xu = __require("os"), ec = Xo(), tc = ec.version, rc = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; + function nc2(e) { + let t = {}, r = e.toString(); + r = r.replace(/\r\n?/mg, ` +`); + let n; + for (; (n = rc.exec(r)) != null; ) { + let i = n[1], o = n[2] || ""; + o = o.trim(); + let s = o[0]; + o = o.replace(/^(['"`])([\s\S]*)\1$/mg, "$2"), s === '"' && (o = o.replace(/\\n/g, ` +`), o = o.replace(/\\r/g, "\r")), t[i] = o; + } + return t; + } + function ci(e) { + console.log(`[dotenv@${tc}][DEBUG] ${e}`); + } + function ic(e) { + return e[0] === "~" ? es.join(Xu.homedir(), e.slice(1)) : e; + } + function oc(e) { + let t = es.resolve(process.cwd(), ".env"), r = "utf8", n = !!(e && e.debug), i = !!(e && e.override); + e && (e.path != null && (t = ic(e.path)), e.encoding != null && (r = e.encoding)); + try { + let o = Hr.parse(Zu.readFileSync(t, { encoding: r })); + return Object.keys(o).forEach(function(s) { + Object.prototype.hasOwnProperty.call(process.env, s) ? (i === true && (process.env[s] = o[s]), n && ci(i === true ? `"${s}" is already defined in \`process.env\` and WAS overwritten` : `"${s}" is already defined in \`process.env\` and was NOT overwritten`)) : process.env[s] = o[s]; + }), { parsed: o }; + } catch (o) { + return n && ci(`Failed to load ${t} ${o.message}`), { error: o }; + } + } + var Hr = { config: oc, parse: nc2 }; + Kr.exports.config = Hr.config; + Kr.exports.parse = Hr.parse; + Kr.exports = Hr; + }); + var as = Z((Zf, ss) => { + "use strict"; + ss.exports = (e) => { + let t = e.match(/^[ \t]*(?=\S)/gm); + return t ? t.reduce((r, n) => Math.min(r, n.length), 1 / 0) : 0; + }; + }); + var us = Z((Xf, ls) => { + "use strict"; + var uc = as(); + ls.exports = (e) => { + let t = uc(e); + if (t === 0) return e; + let r = new RegExp(`^[ \\t]{${t}}`, "gm"); + return e.replace(r, ""); + }; + }); + var fi = Z((og, cs) => { + "use strict"; + cs.exports = (e, t = 1, r) => { + if (r = { indent: " ", includeEmptyLines: false, ...r }, typeof e != "string") throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof e}\``); + if (typeof t != "number") throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof t}\``); + if (typeof r.indent != "string") throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof r.indent}\``); + if (t === 0) return e; + let n = r.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; + return e.replace(n, r.indent.repeat(t)); + }; + }); + var fs = Z((lg, ms) => { + "use strict"; + ms.exports = ({ onlyFirst: e = false } = {}) => { + let t = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"); + return new RegExp(t, e ? void 0 : "g"); + }; + }); + var bi = Z((ug, gs) => { + "use strict"; + var yc = fs(); + gs.exports = (e) => typeof e == "string" ? e.replace(yc(), "") : e; + }); + var hs = Z((dg, Zr) => { + "use strict"; + Zr.exports = (e = {}) => { + let t; + if (e.repoUrl) t = e.repoUrl; + else if (e.user && e.repo) t = `https://github.com/${e.user}/${e.repo}`; + else throw new Error("You need to specify either the `repoUrl` option or both the `user` and `repo` options"); + let r = new URL(`${t}/issues/new`), n = ["body", "title", "labels", "template", "milestone", "assignee", "projects"]; + for (let i of n) { + let o = e[i]; + if (o !== void 0) { + if (i === "labels" || i === "projects") { + if (!Array.isArray(o)) throw new TypeError(`The \`${i}\` option should be an array`); + o = o.join(","); + } + r.searchParams.set(i, o); + } + } + return r.toString(); + }; + Zr.exports.default = Zr.exports; + }); + var Ai = Z((Th, $s) => { + "use strict"; + $s.exports = /* @__PURE__ */ function() { + function e(t, r, n, i, o) { + return t < r || n < r ? t > n ? n + 1 : t + 1 : i === o ? r : r + 1; + } + return function(t, r) { + if (t === r) return 0; + if (t.length > r.length) { + var n = t; + t = r, r = n; + } + for (var i = t.length, o = r.length; i > 0 && t.charCodeAt(i - 1) === r.charCodeAt(o - 1); ) i--, o--; + for (var s = 0; s < i && t.charCodeAt(s) === r.charCodeAt(s); ) s++; + if (i -= s, o -= s, i === 0 || o < 3) return o; + var a = 0, l, u, c, p, d, f, g, h, O, T, S, C, E = []; + for (l = 0; l < i; l++) E.push(l + 1), E.push(t.charCodeAt(s + l)); + for (var me = E.length - 1; a < o - 3; ) for (O = r.charCodeAt(s + (u = a)), T = r.charCodeAt(s + (c = a + 1)), S = r.charCodeAt(s + (p = a + 2)), C = r.charCodeAt(s + (d = a + 3)), f = a += 4, l = 0; l < me; l += 2) g = E[l], h = E[l + 1], u = e(g, u, c, O, h), c = e(u, c, p, T, h), p = e(c, p, d, S, h), f = e(p, d, f, C, h), E[l] = f, d = p, p = c, c = u, u = g; + for (; a < o; ) for (O = r.charCodeAt(s + (u = a)), f = ++a, l = 0; l < me; l += 2) g = E[l], E[l] = f = e(g, u, f, O, E[l + 1]), u = g; + return f; + }; + }(); + }); + var Nm = {}; + Ut(Nm, { Debug: () => Gn, Decimal: () => xe, Extensions: () => jn, MetricsClient: () => Dt, NotFoundError: () => Le, PrismaClientInitializationError: () => R, PrismaClientKnownRequestError: () => V, PrismaClientRustPanicError: () => le, PrismaClientUnknownRequestError: () => B, PrismaClientValidationError: () => J, Public: () => Vn, Sql: () => oe, defineDmmfProperty: () => ua, deserializeJsonResponse: () => wt, dmmfToRuntimeDataModel: () => la, empty: () => ma, getPrismaClient: () => Yl, getRuntime: () => In, join: () => da, makeStrictEnum: () => Zl, makeTypedQueryFactory: () => ca, objectEnumValues: () => yn, raw: () => ji, serializeJsonQuery: () => vn, skip: () => Pn, sqltag: () => Vi, warnEnvConflicts: () => Xl, warnOnce: () => tr }); + module.exports = ou(Nm); + var jn = {}; + Ut(jn, { defineExtension: () => yo, getExtensionContext: () => bo }); + function yo(e) { + return typeof e == "function" ? e : (t) => t.$extends(e); + } + function bo(e) { + return e; + } + var Vn = {}; + Ut(Vn, { validator: () => Eo }); + function Eo(...e) { + return (t) => t; + } + var Mr = {}; + Ut(Mr, { $: () => To, bgBlack: () => gu, bgBlue: () => Eu, bgCyan: () => xu, bgGreen: () => yu, bgMagenta: () => wu, bgRed: () => hu, bgWhite: () => Pu, bgYellow: () => bu, black: () => pu, blue: () => rt, bold: () => H, cyan: () => De, dim: () => Oe, gray: () => Gt, green: () => qe, grey: () => fu, hidden: () => uu, inverse: () => lu, italic: () => au, magenta: () => du, red: () => ce, reset: () => su, strikethrough: () => cu, underline: () => X, white: () => mu, yellow: () => ke }); + var Bn; + var wo; + var xo; + var Po; + var vo = true; + typeof process < "u" && ({ FORCE_COLOR: Bn, NODE_DISABLE_COLORS: wo, NO_COLOR: xo, TERM: Po } = process.env || {}, vo = process.stdout && process.stdout.isTTY); + var To = { enabled: !wo && xo == null && Po !== "dumb" && (Bn != null && Bn !== "0" || vo) }; + function M(e, t) { + let r = new RegExp(`\\x1b\\[${t}m`, "g"), n = `\x1B[${e}m`, i = `\x1B[${t}m`; + return function(o) { + return !To.enabled || o == null ? o : n + (~("" + o).indexOf(i) ? o.replace(r, i + n) : o) + i; + }; + } + var su = M(0, 0); + var H = M(1, 22); + var Oe = M(2, 22); + var au = M(3, 23); + var X = M(4, 24); + var lu = M(7, 27); + var uu = M(8, 28); + var cu = M(9, 29); + var pu = M(30, 39); + var ce = M(31, 39); + var qe = M(32, 39); + var ke = M(33, 39); + var rt = M(34, 39); + var du = M(35, 39); + var De = M(36, 39); + var mu = M(37, 39); + var Gt = M(90, 39); + var fu = M(90, 39); + var gu = M(40, 49); + var hu = M(41, 49); + var yu = M(42, 49); + var bu = M(43, 49); + var Eu = M(44, 49); + var wu = M(45, 49); + var xu = M(46, 49); + var Pu = M(47, 49); + var vu = 100; + var Ro = ["green", "yellow", "blue", "magenta", "cyan", "red"]; + var Qt = []; + var Co = Date.now(); + var Tu = 0; + var Un = typeof process < "u" ? process.env : {}; + globalThis.DEBUG ??= Un.DEBUG ?? ""; + globalThis.DEBUG_COLORS ??= Un.DEBUG_COLORS ? Un.DEBUG_COLORS === "true" : true; + var Jt = { enable(e) { + typeof e == "string" && (globalThis.DEBUG = e); + }, disable() { + let e = globalThis.DEBUG; + return globalThis.DEBUG = "", e; + }, enabled(e) { + let t = globalThis.DEBUG.split(",").map((i) => i.replace(/[.+?^${}()|[\]\\]/g, "\\$&")), r = t.some((i) => i === "" || i[0] === "-" ? false : e.match(RegExp(i.split("*").join(".*") + "$"))), n = t.some((i) => i === "" || i[0] !== "-" ? false : e.match(RegExp(i.slice(1).split("*").join(".*") + "$"))); + return r && !n; + }, log: (...e) => { + let [t, r, ...n] = e; + (console.warn ?? console.log)(`${t} ${r}`, ...n); + }, formatters: {} }; + function Ru(e) { + let t = { color: Ro[Tu++ % Ro.length], enabled: Jt.enabled(e), namespace: e, log: Jt.log, extend: () => { + } }, r = (...n) => { + let { enabled: i, namespace: o, color: s, log: a } = t; + if (n.length !== 0 && Qt.push([o, ...n]), Qt.length > vu && Qt.shift(), Jt.enabled(o) || i) { + let l = n.map((c) => typeof c == "string" ? c : Cu(c)), u = `+${Date.now() - Co}ms`; + Co = Date.now(), globalThis.DEBUG_COLORS ? a(Mr[s](H(o)), ...l, Mr[s](u)) : a(o, ...l, u); + } + }; + return new Proxy(r, { get: (n, i) => t[i], set: (n, i, o) => t[i] = o }); + } + var Gn = new Proxy(Ru, { get: (e, t) => Jt[t], set: (e, t, r) => Jt[t] = r }); + function Cu(e, t = 2) { + let r = /* @__PURE__ */ new Set(); + return JSON.stringify(e, (n, i) => { + if (typeof i == "object" && i !== null) { + if (r.has(i)) return "[Circular *]"; + r.add(i); + } else if (typeof i == "bigint") return i.toString(); + return i; + }, t); + } + function So(e = 7500) { + let t = Qt.map(([r, ...n]) => `${r} ${n.map((i) => typeof i == "string" ? i : JSON.stringify(i)).join(" ")}`).join(` +`); + return t.length < e ? t : t.slice(-e); + } + function Ao() { + Qt.length = 0; + } + var L = Gn; + var Io = k(__require("fs")); + function Qn() { + let e = process.env.PRISMA_QUERY_ENGINE_LIBRARY; + if (!(e && Io.default.existsSync(e)) && process.arch === "ia32") throw new Error('The default query engine type (Node-API, "library") is currently not supported for 32bit Node. Please set `engineType = "binary"` in the "generator" block of your "schema.prisma" file (or use the environment variables "PRISMA_CLIENT_ENGINE_TYPE=binary" and/or "PRISMA_CLI_QUERY_ENGINE_TYPE=binary".)'); + } + var Jn = ["darwin", "darwin-arm64", "debian-openssl-1.0.x", "debian-openssl-1.1.x", "debian-openssl-3.0.x", "rhel-openssl-1.0.x", "rhel-openssl-1.1.x", "rhel-openssl-3.0.x", "linux-arm64-openssl-1.1.x", "linux-arm64-openssl-1.0.x", "linux-arm64-openssl-3.0.x", "linux-arm-openssl-1.1.x", "linux-arm-openssl-1.0.x", "linux-arm-openssl-3.0.x", "linux-musl", "linux-musl-openssl-3.0.x", "linux-musl-arm64-openssl-1.1.x", "linux-musl-arm64-openssl-3.0.x", "linux-nixos", "linux-static-x64", "linux-static-arm64", "windows", "freebsd11", "freebsd12", "freebsd13", "freebsd14", "freebsd15", "openbsd", "netbsd", "arm"]; + var $r = "libquery_engine"; + function qr(e, t) { + let r = t === "url"; + return e.includes("windows") ? r ? "query_engine.dll.node" : `query_engine-${e}.dll.node` : e.includes("darwin") ? r ? `${$r}.dylib.node` : `${$r}-${e}.dylib.node` : r ? `${$r}.so.node` : `${$r}-${e}.so.node`; + } + var _o = k(__require("child_process")); + var zn = k(__require("fs/promises")); + var Gr = k(__require("os")); + var _e = Symbol.for("@ts-pattern/matcher"); + var Su = Symbol.for("@ts-pattern/isVariadic"); + var Vr = "@ts-pattern/anonymous-select-key"; + var Wn = (e) => !!(e && typeof e == "object"); + var jr = (e) => e && !!e[_e]; + var Ee = (e, t, r) => { + if (jr(e)) { + let n = e[_e](), { matched: i, selections: o } = n.match(t); + return i && o && Object.keys(o).forEach((s) => r(s, o[s])), i; + } + if (Wn(e)) { + if (!Wn(t)) return false; + if (Array.isArray(e)) { + if (!Array.isArray(t)) return false; + let n = [], i = [], o = []; + for (let s of e.keys()) { + let a = e[s]; + jr(a) && a[Su] ? o.push(a) : o.length ? i.push(a) : n.push(a); + } + if (o.length) { + if (o.length > 1) throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed."); + if (t.length < n.length + i.length) return false; + let s = t.slice(0, n.length), a = i.length === 0 ? [] : t.slice(-i.length), l = t.slice(n.length, i.length === 0 ? 1 / 0 : -i.length); + return n.every((u, c) => Ee(u, s[c], r)) && i.every((u, c) => Ee(u, a[c], r)) && (o.length === 0 || Ee(o[0], l, r)); + } + return e.length === t.length && e.every((s, a) => Ee(s, t[a], r)); + } + return Object.keys(e).every((n) => { + let i = e[n]; + return (n in t || jr(o = i) && o[_e]().matcherType === "optional") && Ee(i, t[n], r); + var o; + }); + } + return Object.is(t, e); + }; + var Ge = (e) => { + var t, r, n; + return Wn(e) ? jr(e) ? (t = (r = (n = e[_e]()).getSelectionKeys) == null ? void 0 : r.call(n)) != null ? t : [] : Array.isArray(e) ? Wt(e, Ge) : Wt(Object.values(e), Ge) : []; + }; + var Wt = (e, t) => e.reduce((r, n) => r.concat(t(n)), []); + function pe(e) { + return Object.assign(e, { optional: () => Au(e), and: (t) => j(e, t), or: (t) => Iu(e, t), select: (t) => t === void 0 ? Oo(e) : Oo(t, e) }); + } + function Au(e) { + return pe({ [_e]: () => ({ match: (t) => { + let r = {}, n = (i, o) => { + r[i] = o; + }; + return t === void 0 ? (Ge(e).forEach((i) => n(i, void 0)), { matched: true, selections: r }) : { matched: Ee(e, t, n), selections: r }; + }, getSelectionKeys: () => Ge(e), matcherType: "optional" }) }); + } + function j(...e) { + return pe({ [_e]: () => ({ match: (t) => { + let r = {}, n = (i, o) => { + r[i] = o; + }; + return { matched: e.every((i) => Ee(i, t, n)), selections: r }; + }, getSelectionKeys: () => Wt(e, Ge), matcherType: "and" }) }); + } + function Iu(...e) { + return pe({ [_e]: () => ({ match: (t) => { + let r = {}, n = (i, o) => { + r[i] = o; + }; + return Wt(e, Ge).forEach((i) => n(i, void 0)), { matched: e.some((i) => Ee(i, t, n)), selections: r }; + }, getSelectionKeys: () => Wt(e, Ge), matcherType: "or" }) }); + } + function I(e) { + return { [_e]: () => ({ match: (t) => ({ matched: !!e(t) }) }) }; + } + function Oo(...e) { + let t = typeof e[0] == "string" ? e[0] : void 0, r = e.length === 2 ? e[1] : typeof e[0] == "string" ? void 0 : e[0]; + return pe({ [_e]: () => ({ match: (n) => { + let i = { [t ?? Vr]: n }; + return { matched: r === void 0 || Ee(r, n, (o, s) => { + i[o] = s; + }), selections: i }; + }, getSelectionKeys: () => [t ?? Vr].concat(r === void 0 ? [] : Ge(r)) }) }); + } + function ye(e) { + return typeof e == "number"; + } + function je(e) { + return typeof e == "string"; + } + function Ve(e) { + return typeof e == "bigint"; + } + var Km = pe(I(function(e) { + return true; + })); + var Be = (e) => Object.assign(pe(e), { startsWith: (t) => { + return Be(j(e, (r = t, I((n) => je(n) && n.startsWith(r))))); + var r; + }, endsWith: (t) => { + return Be(j(e, (r = t, I((n) => je(n) && n.endsWith(r))))); + var r; + }, minLength: (t) => Be(j(e, ((r) => I((n) => je(n) && n.length >= r))(t))), length: (t) => Be(j(e, ((r) => I((n) => je(n) && n.length === r))(t))), maxLength: (t) => Be(j(e, ((r) => I((n) => je(n) && n.length <= r))(t))), includes: (t) => { + return Be(j(e, (r = t, I((n) => je(n) && n.includes(r))))); + var r; + }, regex: (t) => { + return Be(j(e, (r = t, I((n) => je(n) && !!n.match(r))))); + var r; + } }); + var zm = Be(I(je)); + var be = (e) => Object.assign(pe(e), { between: (t, r) => be(j(e, ((n, i) => I((o) => ye(o) && n <= o && i >= o))(t, r))), lt: (t) => be(j(e, ((r) => I((n) => ye(n) && n < r))(t))), gt: (t) => be(j(e, ((r) => I((n) => ye(n) && n > r))(t))), lte: (t) => be(j(e, ((r) => I((n) => ye(n) && n <= r))(t))), gte: (t) => be(j(e, ((r) => I((n) => ye(n) && n >= r))(t))), int: () => be(j(e, I((t) => ye(t) && Number.isInteger(t)))), finite: () => be(j(e, I((t) => ye(t) && Number.isFinite(t)))), positive: () => be(j(e, I((t) => ye(t) && t > 0))), negative: () => be(j(e, I((t) => ye(t) && t < 0))) }); + var Ym = be(I(ye)); + var Ue = (e) => Object.assign(pe(e), { between: (t, r) => Ue(j(e, ((n, i) => I((o) => Ve(o) && n <= o && i >= o))(t, r))), lt: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n < r))(t))), gt: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n > r))(t))), lte: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n <= r))(t))), gte: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n >= r))(t))), positive: () => Ue(j(e, I((t) => Ve(t) && t > 0))), negative: () => Ue(j(e, I((t) => Ve(t) && t < 0))) }); + var Zm = Ue(I(Ve)); + var Xm = pe(I(function(e) { + return typeof e == "boolean"; + })); + var ef = pe(I(function(e) { + return typeof e == "symbol"; + })); + var tf = pe(I(function(e) { + return e == null; + })); + var rf = pe(I(function(e) { + return e != null; + })); + var Hn = { matched: false, value: void 0 }; + function mt(e) { + return new Kn(e, Hn); + } + var Kn = class e { + constructor(t, r) { + this.input = void 0, this.state = void 0, this.input = t, this.state = r; + } + with(...t) { + if (this.state.matched) return this; + let r = t[t.length - 1], n = [t[0]], i; + t.length === 3 && typeof t[1] == "function" ? i = t[1] : t.length > 2 && n.push(...t.slice(1, t.length - 1)); + let o = false, s = {}, a = (u, c) => { + o = true, s[u] = c; + }, l = !n.some((u) => Ee(u, this.input, a)) || i && !i(this.input) ? Hn : { matched: true, value: r(o ? Vr in s ? s[Vr] : s : this.input, this.input) }; + return new e(this.input, l); + } + when(t, r) { + if (this.state.matched) return this; + let n = !!t(this.input); + return new e(this.input, n ? { matched: true, value: r(this.input, this.input) } : Hn); + } + otherwise(t) { + return this.state.matched ? this.state.value : t(this.input); + } + exhaustive() { + if (this.state.matched) return this.state.value; + let t; + try { + t = JSON.stringify(this.input); + } catch { + t = this.input; + } + throw new Error(`Pattern matching error: no pattern matches value ${t}`); + } + run() { + return this.exhaustive(); + } + returnType() { + return this; + } + }; + var Fo = __require("util"); + var Ou = { warn: ke("prisma:warn") }; + var ku = { warn: () => !process.env.PRISMA_DISABLE_WARNINGS }; + function Br(e, ...t) { + ku.warn() && console.warn(`${Ou.warn} ${e}`, ...t); + } + var Du = (0, Fo.promisify)(_o.default.exec); + var te = L("prisma:get-platform"); + var _u = ["1.0.x", "1.1.x", "3.0.x"]; + async function Lo() { + let e = Gr.default.platform(), t = process.arch; + if (e === "freebsd") { + let s = await Qr("freebsd-version"); + if (s && s.trim().length > 0) { + let l = /^(\d+)\.?/.exec(s); + if (l) return { platform: "freebsd", targetDistro: `freebsd${l[1]}`, arch: t }; + } + } + if (e !== "linux") return { platform: e, arch: t }; + let r = await Lu(), n = await Uu(), i = Mu({ arch: t, archFromUname: n, familyDistro: r.familyDistro }), { libssl: o } = await $u(i); + return { platform: "linux", libssl: o, arch: t, archFromUname: n, ...r }; + } + function Fu(e) { + let t = /^ID="?([^"\n]*)"?$/im, r = /^ID_LIKE="?([^"\n]*)"?$/im, n = t.exec(e), i = n && n[1] && n[1].toLowerCase() || "", o = r.exec(e), s = o && o[1] && o[1].toLowerCase() || "", a = mt({ id: i, idLike: s }).with({ id: "alpine" }, ({ id: l }) => ({ targetDistro: "musl", familyDistro: l, originalDistro: l })).with({ id: "raspbian" }, ({ id: l }) => ({ targetDistro: "arm", familyDistro: "debian", originalDistro: l })).with({ id: "nixos" }, ({ id: l }) => ({ targetDistro: "nixos", originalDistro: l, familyDistro: "nixos" })).with({ id: "debian" }, { id: "ubuntu" }, ({ id: l }) => ({ targetDistro: "debian", familyDistro: "debian", originalDistro: l })).with({ id: "rhel" }, { id: "centos" }, { id: "fedora" }, ({ id: l }) => ({ targetDistro: "rhel", familyDistro: "rhel", originalDistro: l })).when(({ idLike: l }) => l.includes("debian") || l.includes("ubuntu"), ({ id: l }) => ({ targetDistro: "debian", familyDistro: "debian", originalDistro: l })).when(({ idLike: l }) => i === "arch" || l.includes("arch"), ({ id: l }) => ({ targetDistro: "debian", familyDistro: "arch", originalDistro: l })).when(({ idLike: l }) => l.includes("centos") || l.includes("fedora") || l.includes("rhel") || l.includes("suse"), ({ id: l }) => ({ targetDistro: "rhel", familyDistro: "rhel", originalDistro: l })).otherwise(({ id: l }) => ({ targetDistro: void 0, familyDistro: void 0, originalDistro: l })); + return te(`Found distro info: +${JSON.stringify(a, null, 2)}`), a; + } + async function Lu() { + let e = "/etc/os-release"; + try { + let t = await zn.default.readFile(e, { encoding: "utf-8" }); + return Fu(t); + } catch { + return { targetDistro: void 0, familyDistro: void 0, originalDistro: void 0 }; + } + } + function Nu(e) { + let t = /^OpenSSL\s(\d+\.\d+)\.\d+/.exec(e); + if (t) { + let r = `${t[1]}.x`; + return No(r); + } + } + function ko(e) { + let t = /libssl\.so\.(\d)(\.\d)?/.exec(e); + if (t) { + let r = `${t[1]}${t[2] ?? ".0"}.x`; + return No(r); + } + } + function No(e) { + let t = (() => { + if ($o(e)) return e; + let r = e.split("."); + return r[1] = "0", r.join("."); + })(); + if (_u.includes(t)) return t; + } + function Mu(e) { + return mt(e).with({ familyDistro: "musl" }, () => (te('Trying platform-specific paths for "alpine"'), ["/lib"])).with({ familyDistro: "debian" }, ({ archFromUname: t }) => (te('Trying platform-specific paths for "debian" (and "ubuntu")'), [`/usr/lib/${t}-linux-gnu`, `/lib/${t}-linux-gnu`])).with({ familyDistro: "rhel" }, () => (te('Trying platform-specific paths for "rhel"'), ["/lib64", "/usr/lib64"])).otherwise(({ familyDistro: t, arch: r, archFromUname: n }) => (te(`Don't know any platform-specific paths for "${t}" on ${r} (${n})`), [])); + } + async function $u(e) { + let t = 'grep -v "libssl.so.0"', r = await Do(e); + if (r) { + te(`Found libssl.so file using platform-specific paths: ${r}`); + let o = ko(r); + if (te(`The parsed libssl version is: ${o}`), o) return { libssl: o, strategy: "libssl-specific-path" }; + } + te('Falling back to "ldconfig" and other generic paths'); + let n = await Qr(`ldconfig -p | sed "s/.*=>s*//" | sed "s|.*/||" | grep libssl | sort | ${t}`); + if (n || (n = await Do(["/lib64", "/usr/lib64", "/lib"])), n) { + te(`Found libssl.so file using "ldconfig" or other generic paths: ${n}`); + let o = ko(n); + if (te(`The parsed libssl version is: ${o}`), o) return { libssl: o, strategy: "ldconfig" }; + } + let i = await Qr("openssl version -v"); + if (i) { + te(`Found openssl binary with version: ${i}`); + let o = Nu(i); + if (te(`The parsed openssl version is: ${o}`), o) return { libssl: o, strategy: "openssl-binary" }; + } + return te("Couldn't find any version of libssl or OpenSSL in the system"), {}; + } + async function Do(e) { + for (let t of e) { + let r = await qu(t); + if (r) return r; + } + } + async function qu(e) { + try { + return (await zn.default.readdir(e)).find((r) => r.startsWith("libssl.so.") && !r.startsWith("libssl.so.0")); + } catch (t) { + if (t.code === "ENOENT") return; + throw t; + } + } + async function nt() { + let { binaryTarget: e } = await Mo(); + return e; + } + function ju(e) { + return e.binaryTarget !== void 0; + } + async function Yn() { + let { memoized: e, ...t } = await Mo(); + return t; + } + var Ur = {}; + async function Mo() { + if (ju(Ur)) return Promise.resolve({ ...Ur, memoized: true }); + let e = await Lo(), t = Vu(e); + return Ur = { ...e, binaryTarget: t }, { ...Ur, memoized: false }; + } + function Vu(e) { + let { platform: t, arch: r, archFromUname: n, libssl: i, targetDistro: o, familyDistro: s, originalDistro: a } = e; + t === "linux" && !["x64", "arm64"].includes(r) && Br(`Prisma only officially supports Linux on amd64 (x86_64) and arm64 (aarch64) system architectures (detected "${r}" instead). If you are using your own custom Prisma engines, you can ignore this warning, as long as you've compiled the engines for your system architecture "${n}".`); + let l = "1.1.x"; + if (t === "linux" && i === void 0) { + let c = mt({ familyDistro: s }).with({ familyDistro: "debian" }, () => "Please manually install OpenSSL via `apt-get update -y && apt-get install -y openssl` and try installing Prisma again. If you're running Prisma on Docker, add this command to your Dockerfile, or switch to an image that already has OpenSSL installed.").otherwise(() => "Please manually install OpenSSL and try installing Prisma again."); + Br(`Prisma failed to detect the libssl/openssl version to use, and may not work as expected. Defaulting to "openssl-${l}". +${c}`); + } + let u = "debian"; + if (t === "linux" && o === void 0 && te(`Distro is "${a}". Falling back to Prisma engines built for "${u}".`), t === "darwin" && r === "arm64") return "darwin-arm64"; + if (t === "darwin") return "darwin"; + if (t === "win32") return "windows"; + if (t === "freebsd") return o; + if (t === "openbsd") return "openbsd"; + if (t === "netbsd") return "netbsd"; + if (t === "linux" && o === "nixos") return "linux-nixos"; + if (t === "linux" && r === "arm64") return `${o === "musl" ? "linux-musl-arm64" : "linux-arm64"}-openssl-${i || l}`; + if (t === "linux" && r === "arm") return `linux-arm-openssl-${i || l}`; + if (t === "linux" && o === "musl") { + let c = "linux-musl"; + return !i || $o(i) ? c : `${c}-openssl-${i}`; + } + return t === "linux" && o && i ? `${o}-openssl-${i}` : (t !== "linux" && Br(`Prisma detected unknown OS "${t}" and may not work as expected. Defaulting to "linux".`), i ? `${u}-openssl-${i}` : o ? `${o}-openssl-${l}` : `${u}-openssl-${l}`); + } + async function Bu(e) { + try { + return await e(); + } catch { + return; + } + } + function Qr(e) { + return Bu(async () => { + let t = await Du(e); + return te(`Command "${e}" successfully returned "${t.stdout}"`), t.stdout; + }); + } + async function Uu() { + return typeof Gr.default.machine == "function" ? Gr.default.machine() : (await Qr("uname -m"))?.trim(); + } + function $o(e) { + return e.startsWith("1."); + } + var zo = k(Ko()); + function ii(e) { + return (0, zo.default)(e, e, { fallback: X }); + } + var Ku = k(si()); + var $ = k(__require("path")); + var zu = k(si()); + var Lf = L("prisma:engines"); + function Yo() { + return $.default.join(__dirname, "../"); + } + var Nf = "libquery-engine"; + $.default.join(__dirname, "../query-engine-darwin"); + $.default.join(__dirname, "../query-engine-darwin-arm64"); + $.default.join(__dirname, "../query-engine-debian-openssl-1.0.x"); + $.default.join(__dirname, "../query-engine-debian-openssl-1.1.x"); + $.default.join(__dirname, "../query-engine-debian-openssl-3.0.x"); + $.default.join(__dirname, "../query-engine-linux-static-x64"); + $.default.join(__dirname, "../query-engine-linux-static-arm64"); + $.default.join(__dirname, "../query-engine-rhel-openssl-1.0.x"); + $.default.join(__dirname, "../query-engine-rhel-openssl-1.1.x"); + $.default.join(__dirname, "../query-engine-rhel-openssl-3.0.x"); + $.default.join(__dirname, "../libquery_engine-darwin.dylib.node"); + $.default.join(__dirname, "../libquery_engine-darwin-arm64.dylib.node"); + $.default.join(__dirname, "../libquery_engine-debian-openssl-1.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-debian-openssl-1.1.x.so.node"); + $.default.join(__dirname, "../libquery_engine-debian-openssl-3.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-linux-arm64-openssl-1.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-linux-arm64-openssl-1.1.x.so.node"); + $.default.join(__dirname, "../libquery_engine-linux-arm64-openssl-3.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-linux-musl.so.node"); + $.default.join(__dirname, "../libquery_engine-linux-musl-openssl-3.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-rhel-openssl-1.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-rhel-openssl-1.1.x.so.node"); + $.default.join(__dirname, "../libquery_engine-rhel-openssl-3.0.x.so.node"); + $.default.join(__dirname, "../query_engine-windows.dll.node"); + var ai = k(__require("fs")); + var Zo = L("chmodPlusX"); + function li(e) { + if (process.platform === "win32") return; + let t = ai.default.statSync(e), r = t.mode | 64 | 8 | 1; + if (t.mode === r) { + Zo(`Execution permissions of ${e} are fine`); + return; + } + let n = r.toString(8).slice(-3); + Zo(`Have to call chmodPlusX on ${e}`), ai.default.chmodSync(e, n); + } + function ui(e) { + let t = e.e, r = (a) => `Prisma cannot find the required \`${a}\` system library in your system`, n = t.message.includes("cannot open shared object file"), i = `Please refer to the documentation about Prisma's system requirements: ${ii("https://pris.ly/d/system-requirements")}`, o = `Unable to require(\`${Oe(e.id)}\`).`, s = mt({ message: t.message, code: t.code }).with({ code: "ENOENT" }, () => "File does not exist.").when(({ message: a }) => n && a.includes("libz"), () => `${r("libz")}. Please install it and try again.`).when(({ message: a }) => n && a.includes("libgcc_s"), () => `${r("libgcc_s")}. Please install it and try again.`).when(({ message: a }) => n && a.includes("libssl"), () => { + let a = e.platformInfo.libssl ? `openssl-${e.platformInfo.libssl}` : "openssl"; + return `${r("libssl")}. Please install ${a} and try again.`; + }).when(({ message: a }) => a.includes("GLIBC"), () => `Prisma has detected an incompatible version of the \`glibc\` C standard library installed in your system. This probably means your system may be too old to run Prisma. ${i}`).when(({ message: a }) => e.platformInfo.platform === "linux" && a.includes("symbol not found"), () => `The Prisma engines are not compatible with your system ${e.platformInfo.originalDistro} on (${e.platformInfo.archFromUname}) which uses the \`${e.platformInfo.binaryTarget}\` binaryTarget by default. ${i}`).otherwise(() => `The Prisma engines do not seem to be compatible with your system. ${i}`); + return `${o} +${s} + +Details: ${t.message}`; + } + var di = k(ts()); + var zr = k(__require("fs")); + var ht = k(__require("path")); + function rs(e) { + let t = e.ignoreProcessEnv ? {} : process.env, r = (n) => n.match(/(.?\${(?:[a-zA-Z0-9_]+)?})/g)?.reduce(function(o, s) { + let a = /(.?)\${([a-zA-Z0-9_]+)?}/g.exec(s); + if (!a) return o; + let l = a[1], u, c; + if (l === "\\") c = a[0], u = c.replace("\\$", "$"); + else { + let p = a[2]; + c = a[0].substring(l.length), u = Object.hasOwnProperty.call(t, p) ? t[p] : e.parsed[p] || "", u = r(u); + } + return o.replace(c, u); + }, n) ?? n; + for (let n in e.parsed) { + let i = Object.hasOwnProperty.call(t, n) ? t[n] : e.parsed[n]; + e.parsed[n] = r(i); + } + for (let n in e.parsed) t[n] = e.parsed[n]; + return e; + } + var pi = L("prisma:tryLoadEnv"); + function zt({ rootEnvPath: e, schemaEnvPath: t }, r = { conflictCheck: "none" }) { + let n = ns(e); + r.conflictCheck !== "none" && sc(n, t, r.conflictCheck); + let i = null; + return is(n?.path, t) || (i = ns(t)), !n && !i && pi("No Environment variables loaded"), i?.dotenvResult.error ? console.error(ce(H("Schema Env Error: ")) + i.dotenvResult.error) : { message: [n?.message, i?.message].filter(Boolean).join(` +`), parsed: { ...n?.dotenvResult?.parsed, ...i?.dotenvResult?.parsed } }; + } + function sc(e, t, r) { + let n = e?.dotenvResult.parsed, i = !is(e?.path, t); + if (n && t && i && zr.default.existsSync(t)) { + let o = di.default.parse(zr.default.readFileSync(t)), s = []; + for (let a in o) n[a] === o[a] && s.push(a); + if (s.length > 0) { + let a = ht.default.relative(process.cwd(), e.path), l = ht.default.relative(process.cwd(), t); + if (r === "error") { + let u = `There is a conflict between env var${s.length > 1 ? "s" : ""} in ${X(a)} and ${X(l)} +Conflicting env vars: +${s.map((c) => ` ${H(c)}`).join(` +`)} + +We suggest to move the contents of ${X(l)} to ${X(a)} to consolidate your env vars. +`; + throw new Error(u); + } else if (r === "warn") { + let u = `Conflict for env var${s.length > 1 ? "s" : ""} ${s.map((c) => H(c)).join(", ")} in ${X(a)} and ${X(l)} +Env vars from ${X(l)} overwrite the ones from ${X(a)} + `; + console.warn(`${ke("warn(prisma)")} ${u}`); + } + } + } + } + function ns(e) { + if (ac(e)) { + pi(`Environment variables loaded from ${e}`); + let t = di.default.config({ path: e, debug: process.env.DOTENV_CONFIG_DEBUG ? true : void 0 }); + return { dotenvResult: rs(t), message: Oe(`Environment variables loaded from ${ht.default.relative(process.cwd(), e)}`), path: e }; + } else pi(`Environment variables not found at ${e}`); + return null; + } + function is(e, t) { + return e && t && ht.default.resolve(e) === ht.default.resolve(t); + } + function ac(e) { + return !!(e && zr.default.existsSync(e)); + } + var os = "library"; + function Yt(e) { + let t = lc(); + return t || (e?.config.engineType === "library" ? "library" : e?.config.engineType === "binary" ? "binary" : os); + } + function lc() { + let e = process.env.PRISMA_CLIENT_ENGINE_TYPE; + return e === "library" ? "library" : e === "binary" ? "binary" : void 0; + } + var Je; + ((t) => { + let e; + ((E) => (E.findUnique = "findUnique", E.findUniqueOrThrow = "findUniqueOrThrow", E.findFirst = "findFirst", E.findFirstOrThrow = "findFirstOrThrow", E.findMany = "findMany", E.create = "create", E.createMany = "createMany", E.createManyAndReturn = "createManyAndReturn", E.update = "update", E.updateMany = "updateMany", E.upsert = "upsert", E.delete = "delete", E.deleteMany = "deleteMany", E.groupBy = "groupBy", E.count = "count", E.aggregate = "aggregate", E.findRaw = "findRaw", E.aggregateRaw = "aggregateRaw"))(e = t.ModelAction ||= {}); + })(Je ||= {}); + var Zt = k(__require("path")); + function mi(e) { + return Zt.default.sep === Zt.default.posix.sep ? e : e.split(Zt.default.sep).join(Zt.default.posix.sep); + } + var ps = k(fi()); + function hi(e) { + return String(new gi(e)); + } + var gi = class { + constructor(t) { + this.config = t; + } + toString() { + let { config: t } = this, r = t.provider.fromEnvVar ? `env("${t.provider.fromEnvVar}")` : t.provider.value, n = JSON.parse(JSON.stringify({ provider: r, binaryTargets: cc(t.binaryTargets) })); + return `generator ${t.name} { +${(0, ps.default)(pc(n), 2)} +}`; + } + }; + function cc(e) { + let t; + if (e.length > 0) { + let r = e.find((n) => n.fromEnvVar !== null); + r ? t = `env("${r.fromEnvVar}")` : t = e.map((n) => n.native ? "native" : n.value); + } else t = void 0; + return t; + } + function pc(e) { + let t = Object.keys(e).reduce((r, n) => Math.max(r, n.length), 0); + return Object.entries(e).map(([r, n]) => `${r.padEnd(t)} = ${dc(n)}`).join(` +`); + } + function dc(e) { + return JSON.parse(JSON.stringify(e, (t, r) => Array.isArray(r) ? `[${r.map((n) => JSON.stringify(n)).join(", ")}]` : JSON.stringify(r))); + } + var er = {}; + Ut(er, { error: () => gc, info: () => fc, log: () => mc, query: () => hc, should: () => ds, tags: () => Xt, warn: () => yi }); + var Xt = { error: ce("prisma:error"), warn: ke("prisma:warn"), info: De("prisma:info"), query: rt("prisma:query") }; + var ds = { warn: () => !process.env.PRISMA_DISABLE_WARNINGS }; + function mc(...e) { + console.log(...e); + } + function yi(e, ...t) { + ds.warn() && console.warn(`${Xt.warn} ${e}`, ...t); + } + function fc(e, ...t) { + console.info(`${Xt.info} ${e}`, ...t); + } + function gc(e, ...t) { + console.error(`${Xt.error} ${e}`, ...t); + } + function hc(e, ...t) { + console.log(`${Xt.query} ${e}`, ...t); + } + function Yr(e, t) { + if (!e) throw new Error(`${t}. This should never happen. If you see this error, please, open an issue at https://pris.ly/prisma-prisma-bug-report`); + } + function Fe(e, t) { + throw new Error(t); + } + function Ei(e, t) { + return Object.prototype.hasOwnProperty.call(e, t); + } + var wi = (e, t) => e.reduce((r, n) => (r[t(n)] = n, r), {}); + function yt(e, t) { + let r = {}; + for (let n of Object.keys(e)) r[n] = t(e[n], n); + return r; + } + function xi(e, t) { + if (e.length === 0) return; + let r = e[0]; + for (let n = 1; n < e.length; n++) t(r, e[n]) < 0 && (r = e[n]); + return r; + } + function w(e, t) { + Object.defineProperty(e, "name", { value: t, configurable: true }); + } + var ys = /* @__PURE__ */ new Set(); + var tr = (e, t, ...r) => { + ys.has(e) || (ys.add(e), yi(t, ...r)); + }; + var V = class extends Error { + constructor(t, { code: r, clientVersion: n, meta: i, batchRequestIdx: o }) { + super(t), this.name = "PrismaClientKnownRequestError", this.code = r, this.clientVersion = n, this.meta = i, Object.defineProperty(this, "batchRequestIdx", { value: o, enumerable: false, writable: true }); + } + get [Symbol.toStringTag]() { + return "PrismaClientKnownRequestError"; + } + }; + w(V, "PrismaClientKnownRequestError"); + var Le = class extends V { + constructor(t, r) { + super(t, { code: "P2025", clientVersion: r }), this.name = "NotFoundError"; + } + }; + w(Le, "NotFoundError"); + var R = class e extends Error { + constructor(t, r, n) { + super(t), this.name = "PrismaClientInitializationError", this.clientVersion = r, this.errorCode = n, Error.captureStackTrace(e); + } + get [Symbol.toStringTag]() { + return "PrismaClientInitializationError"; + } + }; + w(R, "PrismaClientInitializationError"); + var le = class extends Error { + constructor(t, r) { + super(t), this.name = "PrismaClientRustPanicError", this.clientVersion = r; + } + get [Symbol.toStringTag]() { + return "PrismaClientRustPanicError"; + } + }; + w(le, "PrismaClientRustPanicError"); + var B = class extends Error { + constructor(t, { clientVersion: r, batchRequestIdx: n }) { + super(t), this.name = "PrismaClientUnknownRequestError", this.clientVersion = r, Object.defineProperty(this, "batchRequestIdx", { value: n, writable: true, enumerable: false }); + } + get [Symbol.toStringTag]() { + return "PrismaClientUnknownRequestError"; + } + }; + w(B, "PrismaClientUnknownRequestError"); + var J = class extends Error { + constructor(r, { clientVersion: n }) { + super(r); + this.name = "PrismaClientValidationError"; + this.clientVersion = n; + } + get [Symbol.toStringTag]() { + return "PrismaClientValidationError"; + } + }; + w(J, "PrismaClientValidationError"); + var bt = 9e15; + var ze = 1e9; + var Pi = "0123456789abcdef"; + var tn = "2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058"; + var rn = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789"; + var vi = { precision: 20, rounding: 4, modulo: 1, toExpNeg: -7, toExpPos: 21, minE: -bt, maxE: bt, crypto: false }; + var xs; + var Ne; + var x = true; + var on = "[DecimalError] "; + var Ke = on + "Invalid argument: "; + var Ps = on + "Precision limit exceeded"; + var vs = on + "crypto unavailable"; + var Ts = "[object Decimal]"; + var ee = Math.floor; + var G = Math.pow; + var bc = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i; + var Ec = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i; + var wc = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i; + var Rs = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i; + var ge = 1e7; + var b = 7; + var xc = 9007199254740991; + var Pc = tn.length - 1; + var Ti = rn.length - 1; + var m = { toStringTag: Ts }; + m.absoluteValue = m.abs = function() { + var e = new this.constructor(this); + return e.s < 0 && (e.s = 1), y(e); + }; + m.ceil = function() { + return y(new this.constructor(this), this.e + 1, 2); + }; + m.clampedTo = m.clamp = function(e, t) { + var r, n = this, i = n.constructor; + if (e = new i(e), t = new i(t), !e.s || !t.s) return new i(NaN); + if (e.gt(t)) throw Error(Ke + t); + return r = n.cmp(e), r < 0 ? e : n.cmp(t) > 0 ? t : new i(n); + }; + m.comparedTo = m.cmp = function(e) { + var t, r, n, i, o = this, s = o.d, a = (e = new o.constructor(e)).d, l = o.s, u = e.s; + if (!s || !a) return !l || !u ? NaN : l !== u ? l : s === a ? 0 : !s ^ l < 0 ? 1 : -1; + if (!s[0] || !a[0]) return s[0] ? l : a[0] ? -u : 0; + if (l !== u) return l; + if (o.e !== e.e) return o.e > e.e ^ l < 0 ? 1 : -1; + for (n = s.length, i = a.length, t = 0, r = n < i ? n : i; t < r; ++t) if (s[t] !== a[t]) return s[t] > a[t] ^ l < 0 ? 1 : -1; + return n === i ? 0 : n > i ^ l < 0 ? 1 : -1; + }; + m.cosine = m.cos = function() { + var e, t, r = this, n = r.constructor; + return r.d ? r.d[0] ? (e = n.precision, t = n.rounding, n.precision = e + Math.max(r.e, r.sd()) + b, n.rounding = 1, r = vc(n, Os(n, r)), n.precision = e, n.rounding = t, y(Ne == 2 || Ne == 3 ? r.neg() : r, e, t, true)) : new n(1) : new n(NaN); + }; + m.cubeRoot = m.cbrt = function() { + var e, t, r, n, i, o, s, a, l, u, c = this, p = c.constructor; + if (!c.isFinite() || c.isZero()) return new p(c); + for (x = false, o = c.s * G(c.s * c, 1 / 3), !o || Math.abs(o) == 1 / 0 ? (r = K(c.d), e = c.e, (o = (e - r.length + 1) % 3) && (r += o == 1 || o == -2 ? "0" : "00"), o = G(r, 1 / 3), e = ee((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)), o == 1 / 0 ? r = "5e" + e : (r = o.toExponential(), r = r.slice(0, r.indexOf("e") + 1) + e), n = new p(r), n.s = c.s) : n = new p(o.toString()), s = (e = p.precision) + 3; ; ) if (a = n, l = a.times(a).times(a), u = l.plus(c), n = N(u.plus(c).times(a), u.plus(l), s + 2, 1), K(a.d).slice(0, s) === (r = K(n.d)).slice(0, s)) if (r = r.slice(s - 3, s + 1), r == "9999" || !i && r == "4999") { + if (!i && (y(a, e + 1, 0), a.times(a).times(a).eq(c))) { + n = a; + break; + } + s += 4, i = 1; + } else { + (!+r || !+r.slice(1) && r.charAt(0) == "5") && (y(n, e + 1, 1), t = !n.times(n).times(n).eq(c)); + break; + } + return x = true, y(n, e, p.rounding, t); + }; + m.decimalPlaces = m.dp = function() { + var e, t = this.d, r = NaN; + if (t) { + if (e = t.length - 1, r = (e - ee(this.e / b)) * b, e = t[e], e) for (; e % 10 == 0; e /= 10) r--; + r < 0 && (r = 0); + } + return r; + }; + m.dividedBy = m.div = function(e) { + return N(this, new this.constructor(e)); + }; + m.dividedToIntegerBy = m.divToInt = function(e) { + var t = this, r = t.constructor; + return y(N(t, new r(e), 0, 1, 1), r.precision, r.rounding); + }; + m.equals = m.eq = function(e) { + return this.cmp(e) === 0; + }; + m.floor = function() { + return y(new this.constructor(this), this.e + 1, 3); + }; + m.greaterThan = m.gt = function(e) { + return this.cmp(e) > 0; + }; + m.greaterThanOrEqualTo = m.gte = function(e) { + var t = this.cmp(e); + return t == 1 || t === 0; + }; + m.hyperbolicCosine = m.cosh = function() { + var e, t, r, n, i, o = this, s = o.constructor, a = new s(1); + if (!o.isFinite()) return new s(o.s ? 1 / 0 : NaN); + if (o.isZero()) return a; + r = s.precision, n = s.rounding, s.precision = r + Math.max(o.e, o.sd()) + 4, s.rounding = 1, i = o.d.length, i < 32 ? (e = Math.ceil(i / 3), t = (1 / an(4, e)).toString()) : (e = 16, t = "2.3283064365386962890625e-10"), o = Et(s, 1, o.times(t), new s(1), true); + for (var l, u = e, c = new s(8); u--; ) l = o.times(o), o = a.minus(l.times(c.minus(l.times(c)))); + return y(o, s.precision = r, s.rounding = n, true); + }; + m.hyperbolicSine = m.sinh = function() { + var e, t, r, n, i = this, o = i.constructor; + if (!i.isFinite() || i.isZero()) return new o(i); + if (t = o.precision, r = o.rounding, o.precision = t + Math.max(i.e, i.sd()) + 4, o.rounding = 1, n = i.d.length, n < 3) i = Et(o, 2, i, i, true); + else { + e = 1.4 * Math.sqrt(n), e = e > 16 ? 16 : e | 0, i = i.times(1 / an(5, e)), i = Et(o, 2, i, i, true); + for (var s, a = new o(5), l = new o(16), u = new o(20); e--; ) s = i.times(i), i = i.times(a.plus(s.times(l.times(s).plus(u)))); + } + return o.precision = t, o.rounding = r, y(i, t, r, true); + }; + m.hyperbolicTangent = m.tanh = function() { + var e, t, r = this, n = r.constructor; + return r.isFinite() ? r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + 7, n.rounding = 1, N(r.sinh(), r.cosh(), n.precision = e, n.rounding = t)) : new n(r.s); + }; + m.inverseCosine = m.acos = function() { + var e, t = this, r = t.constructor, n = t.abs().cmp(1), i = r.precision, o = r.rounding; + return n !== -1 ? n === 0 ? t.isNeg() ? fe(r, i, o) : new r(0) : new r(NaN) : t.isZero() ? fe(r, i + 4, o).times(0.5) : (r.precision = i + 6, r.rounding = 1, t = t.asin(), e = fe(r, i + 4, o).times(0.5), r.precision = i, r.rounding = o, e.minus(t)); + }; + m.inverseHyperbolicCosine = m.acosh = function() { + var e, t, r = this, n = r.constructor; + return r.lte(1) ? new n(r.eq(1) ? 0 : NaN) : r.isFinite() ? (e = n.precision, t = n.rounding, n.precision = e + Math.max(Math.abs(r.e), r.sd()) + 4, n.rounding = 1, x = false, r = r.times(r).minus(1).sqrt().plus(r), x = true, n.precision = e, n.rounding = t, r.ln()) : new n(r); + }; + m.inverseHyperbolicSine = m.asinh = function() { + var e, t, r = this, n = r.constructor; + return !r.isFinite() || r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + 2 * Math.max(Math.abs(r.e), r.sd()) + 6, n.rounding = 1, x = false, r = r.times(r).plus(1).sqrt().plus(r), x = true, n.precision = e, n.rounding = t, r.ln()); + }; + m.inverseHyperbolicTangent = m.atanh = function() { + var e, t, r, n, i = this, o = i.constructor; + return i.isFinite() ? i.e >= 0 ? new o(i.abs().eq(1) ? i.s / 0 : i.isZero() ? i : NaN) : (e = o.precision, t = o.rounding, n = i.sd(), Math.max(n, e) < 2 * -i.e - 1 ? y(new o(i), e, t, true) : (o.precision = r = n - i.e, i = N(i.plus(1), new o(1).minus(i), r + e, 1), o.precision = e + 4, o.rounding = 1, i = i.ln(), o.precision = e, o.rounding = t, i.times(0.5))) : new o(NaN); + }; + m.inverseSine = m.asin = function() { + var e, t, r, n, i = this, o = i.constructor; + return i.isZero() ? new o(i) : (t = i.abs().cmp(1), r = o.precision, n = o.rounding, t !== -1 ? t === 0 ? (e = fe(o, r + 4, n).times(0.5), e.s = i.s, e) : new o(NaN) : (o.precision = r + 6, o.rounding = 1, i = i.div(new o(1).minus(i.times(i)).sqrt().plus(1)).atan(), o.precision = r, o.rounding = n, i.times(2))); + }; + m.inverseTangent = m.atan = function() { + var e, t, r, n, i, o, s, a, l, u = this, c = u.constructor, p = c.precision, d = c.rounding; + if (u.isFinite()) { + if (u.isZero()) return new c(u); + if (u.abs().eq(1) && p + 4 <= Ti) return s = fe(c, p + 4, d).times(0.25), s.s = u.s, s; + } else { + if (!u.s) return new c(NaN); + if (p + 4 <= Ti) return s = fe(c, p + 4, d).times(0.5), s.s = u.s, s; + } + for (c.precision = a = p + 10, c.rounding = 1, r = Math.min(28, a / b + 2 | 0), e = r; e; --e) u = u.div(u.times(u).plus(1).sqrt().plus(1)); + for (x = false, t = Math.ceil(a / b), n = 1, l = u.times(u), s = new c(u), i = u; e !== -1; ) if (i = i.times(l), o = s.minus(i.div(n += 2)), i = i.times(l), s = o.plus(i.div(n += 2)), s.d[t] !== void 0) for (e = t; s.d[e] === o.d[e] && e--; ) ; + return r && (s = s.times(2 << r - 1)), x = true, y(s, c.precision = p, c.rounding = d, true); + }; + m.isFinite = function() { + return !!this.d; + }; + m.isInteger = m.isInt = function() { + return !!this.d && ee(this.e / b) > this.d.length - 2; + }; + m.isNaN = function() { + return !this.s; + }; + m.isNegative = m.isNeg = function() { + return this.s < 0; + }; + m.isPositive = m.isPos = function() { + return this.s > 0; + }; + m.isZero = function() { + return !!this.d && this.d[0] === 0; + }; + m.lessThan = m.lt = function(e) { + return this.cmp(e) < 0; + }; + m.lessThanOrEqualTo = m.lte = function(e) { + return this.cmp(e) < 1; + }; + m.logarithm = m.log = function(e) { + var t, r, n, i, o, s, a, l, u = this, c = u.constructor, p = c.precision, d = c.rounding, f = 5; + if (e == null) e = new c(10), t = true; + else { + if (e = new c(e), r = e.d, e.s < 0 || !r || !r[0] || e.eq(1)) return new c(NaN); + t = e.eq(10); + } + if (r = u.d, u.s < 0 || !r || !r[0] || u.eq(1)) return new c(r && !r[0] ? -1 / 0 : u.s != 1 ? NaN : r ? 0 : 1 / 0); + if (t) if (r.length > 1) o = true; + else { + for (i = r[0]; i % 10 === 0; ) i /= 10; + o = i !== 1; + } + if (x = false, a = p + f, s = He(u, a), n = t ? nn(c, a + 10) : He(e, a), l = N(s, n, a, 1), rr(l.d, i = p, d)) do + if (a += 10, s = He(u, a), n = t ? nn(c, a + 10) : He(e, a), l = N(s, n, a, 1), !o) { + +K(l.d).slice(i + 1, i + 15) + 1 == 1e14 && (l = y(l, p + 1, 0)); + break; + } + while (rr(l.d, i += 10, d)); + return x = true, y(l, p, d); + }; + m.minus = m.sub = function(e) { + var t, r, n, i, o, s, a, l, u, c, p, d, f = this, g = f.constructor; + if (e = new g(e), !f.d || !e.d) return !f.s || !e.s ? e = new g(NaN) : f.d ? e.s = -e.s : e = new g(e.d || f.s !== e.s ? f : NaN), e; + if (f.s != e.s) return e.s = -e.s, f.plus(e); + if (u = f.d, d = e.d, a = g.precision, l = g.rounding, !u[0] || !d[0]) { + if (d[0]) e.s = -e.s; + else if (u[0]) e = new g(f); + else return new g(l === 3 ? -0 : 0); + return x ? y(e, a, l) : e; + } + if (r = ee(e.e / b), c = ee(f.e / b), u = u.slice(), o = c - r, o) { + for (p = o < 0, p ? (t = u, o = -o, s = d.length) : (t = d, r = c, s = u.length), n = Math.max(Math.ceil(a / b), s) + 2, o > n && (o = n, t.length = 1), t.reverse(), n = o; n--; ) t.push(0); + t.reverse(); + } else { + for (n = u.length, s = d.length, p = n < s, p && (s = n), n = 0; n < s; n++) if (u[n] != d[n]) { + p = u[n] < d[n]; + break; + } + o = 0; + } + for (p && (t = u, u = d, d = t, e.s = -e.s), s = u.length, n = d.length - s; n > 0; --n) u[s++] = 0; + for (n = d.length; n > o; ) { + if (u[--n] < d[n]) { + for (i = n; i && u[--i] === 0; ) u[i] = ge - 1; + --u[i], u[n] += ge; + } + u[n] -= d[n]; + } + for (; u[--s] === 0; ) u.pop(); + for (; u[0] === 0; u.shift()) --r; + return u[0] ? (e.d = u, e.e = sn(u, r), x ? y(e, a, l) : e) : new g(l === 3 ? -0 : 0); + }; + m.modulo = m.mod = function(e) { + var t, r = this, n = r.constructor; + return e = new n(e), !r.d || !e.s || e.d && !e.d[0] ? new n(NaN) : !e.d || r.d && !r.d[0] ? y(new n(r), n.precision, n.rounding) : (x = false, n.modulo == 9 ? (t = N(r, e.abs(), 0, 3, 1), t.s *= e.s) : t = N(r, e, 0, n.modulo, 1), t = t.times(e), x = true, r.minus(t)); + }; + m.naturalExponential = m.exp = function() { + return Ri(this); + }; + m.naturalLogarithm = m.ln = function() { + return He(this); + }; + m.negated = m.neg = function() { + var e = new this.constructor(this); + return e.s = -e.s, y(e); + }; + m.plus = m.add = function(e) { + var t, r, n, i, o, s, a, l, u, c, p = this, d = p.constructor; + if (e = new d(e), !p.d || !e.d) return !p.s || !e.s ? e = new d(NaN) : p.d || (e = new d(e.d || p.s === e.s ? p : NaN)), e; + if (p.s != e.s) return e.s = -e.s, p.minus(e); + if (u = p.d, c = e.d, a = d.precision, l = d.rounding, !u[0] || !c[0]) return c[0] || (e = new d(p)), x ? y(e, a, l) : e; + if (o = ee(p.e / b), n = ee(e.e / b), u = u.slice(), i = o - n, i) { + for (i < 0 ? (r = u, i = -i, s = c.length) : (r = c, n = o, s = u.length), o = Math.ceil(a / b), s = o > s ? o + 1 : s + 1, i > s && (i = s, r.length = 1), r.reverse(); i--; ) r.push(0); + r.reverse(); + } + for (s = u.length, i = c.length, s - i < 0 && (i = s, r = c, c = u, u = r), t = 0; i; ) t = (u[--i] = u[i] + c[i] + t) / ge | 0, u[i] %= ge; + for (t && (u.unshift(t), ++n), s = u.length; u[--s] == 0; ) u.pop(); + return e.d = u, e.e = sn(u, n), x ? y(e, a, l) : e; + }; + m.precision = m.sd = function(e) { + var t, r = this; + if (e !== void 0 && e !== !!e && e !== 1 && e !== 0) throw Error(Ke + e); + return r.d ? (t = Cs(r.d), e && r.e + 1 > t && (t = r.e + 1)) : t = NaN, t; + }; + m.round = function() { + var e = this, t = e.constructor; + return y(new t(e), e.e + 1, t.rounding); + }; + m.sine = m.sin = function() { + var e, t, r = this, n = r.constructor; + return r.isFinite() ? r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + Math.max(r.e, r.sd()) + b, n.rounding = 1, r = Rc(n, Os(n, r)), n.precision = e, n.rounding = t, y(Ne > 2 ? r.neg() : r, e, t, true)) : new n(NaN); + }; + m.squareRoot = m.sqrt = function() { + var e, t, r, n, i, o, s = this, a = s.d, l = s.e, u = s.s, c = s.constructor; + if (u !== 1 || !a || !a[0]) return new c(!u || u < 0 && (!a || a[0]) ? NaN : a ? s : 1 / 0); + for (x = false, u = Math.sqrt(+s), u == 0 || u == 1 / 0 ? (t = K(a), (t.length + l) % 2 == 0 && (t += "0"), u = Math.sqrt(t), l = ee((l + 1) / 2) - (l < 0 || l % 2), u == 1 / 0 ? t = "5e" + l : (t = u.toExponential(), t = t.slice(0, t.indexOf("e") + 1) + l), n = new c(t)) : n = new c(u.toString()), r = (l = c.precision) + 3; ; ) if (o = n, n = o.plus(N(s, o, r + 2, 1)).times(0.5), K(o.d).slice(0, r) === (t = K(n.d)).slice(0, r)) if (t = t.slice(r - 3, r + 1), t == "9999" || !i && t == "4999") { + if (!i && (y(o, l + 1, 0), o.times(o).eq(s))) { + n = o; + break; + } + r += 4, i = 1; + } else { + (!+t || !+t.slice(1) && t.charAt(0) == "5") && (y(n, l + 1, 1), e = !n.times(n).eq(s)); + break; + } + return x = true, y(n, l, c.rounding, e); + }; + m.tangent = m.tan = function() { + var e, t, r = this, n = r.constructor; + return r.isFinite() ? r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + 10, n.rounding = 1, r = r.sin(), r.s = 1, r = N(r, new n(1).minus(r.times(r)).sqrt(), e + 10, 0), n.precision = e, n.rounding = t, y(Ne == 2 || Ne == 4 ? r.neg() : r, e, t, true)) : new n(NaN); + }; + m.times = m.mul = function(e) { + var t, r, n, i, o, s, a, l, u, c = this, p = c.constructor, d = c.d, f = (e = new p(e)).d; + if (e.s *= c.s, !d || !d[0] || !f || !f[0]) return new p(!e.s || d && !d[0] && !f || f && !f[0] && !d ? NaN : !d || !f ? e.s / 0 : e.s * 0); + for (r = ee(c.e / b) + ee(e.e / b), l = d.length, u = f.length, l < u && (o = d, d = f, f = o, s = l, l = u, u = s), o = [], s = l + u, n = s; n--; ) o.push(0); + for (n = u; --n >= 0; ) { + for (t = 0, i = l + n; i > n; ) a = o[i] + f[n] * d[i - n - 1] + t, o[i--] = a % ge | 0, t = a / ge | 0; + o[i] = (o[i] + t) % ge | 0; + } + for (; !o[--s]; ) o.pop(); + return t ? ++r : o.shift(), e.d = o, e.e = sn(o, r), x ? y(e, p.precision, p.rounding) : e; + }; + m.toBinary = function(e, t) { + return Si(this, 2, e, t); + }; + m.toDecimalPlaces = m.toDP = function(e, t) { + var r = this, n = r.constructor; + return r = new n(r), e === void 0 ? r : (ie(e, 0, ze), t === void 0 ? t = n.rounding : ie(t, 0, 8), y(r, e + r.e + 1, t)); + }; + m.toExponential = function(e, t) { + var r, n = this, i = n.constructor; + return e === void 0 ? r = we(n, true) : (ie(e, 0, ze), t === void 0 ? t = i.rounding : ie(t, 0, 8), n = y(new i(n), e + 1, t), r = we(n, true, e + 1)), n.isNeg() && !n.isZero() ? "-" + r : r; + }; + m.toFixed = function(e, t) { + var r, n, i = this, o = i.constructor; + return e === void 0 ? r = we(i) : (ie(e, 0, ze), t === void 0 ? t = o.rounding : ie(t, 0, 8), n = y(new o(i), e + i.e + 1, t), r = we(n, false, e + n.e + 1)), i.isNeg() && !i.isZero() ? "-" + r : r; + }; + m.toFraction = function(e) { + var t, r, n, i, o, s, a, l, u, c, p, d, f = this, g = f.d, h = f.constructor; + if (!g) return new h(f); + if (u = r = new h(1), n = l = new h(0), t = new h(n), o = t.e = Cs(g) - f.e - 1, s = o % b, t.d[0] = G(10, s < 0 ? b + s : s), e == null) e = o > 0 ? t : u; + else { + if (a = new h(e), !a.isInt() || a.lt(u)) throw Error(Ke + a); + e = a.gt(t) ? o > 0 ? t : u : a; + } + for (x = false, a = new h(K(g)), c = h.precision, h.precision = o = g.length * b * 2; p = N(a, t, 0, 1, 1), i = r.plus(p.times(n)), i.cmp(e) != 1; ) r = n, n = i, i = u, u = l.plus(p.times(i)), l = i, i = t, t = a.minus(p.times(i)), a = i; + return i = N(e.minus(r), n, 0, 1, 1), l = l.plus(i.times(u)), r = r.plus(i.times(n)), l.s = u.s = f.s, d = N(u, n, o, 1).minus(f).abs().cmp(N(l, r, o, 1).minus(f).abs()) < 1 ? [u, n] : [l, r], h.precision = c, x = true, d; + }; + m.toHexadecimal = m.toHex = function(e, t) { + return Si(this, 16, e, t); + }; + m.toNearest = function(e, t) { + var r = this, n = r.constructor; + if (r = new n(r), e == null) { + if (!r.d) return r; + e = new n(1), t = n.rounding; + } else { + if (e = new n(e), t === void 0 ? t = n.rounding : ie(t, 0, 8), !r.d) return e.s ? r : e; + if (!e.d) return e.s && (e.s = r.s), e; + } + return e.d[0] ? (x = false, r = N(r, e, 0, t, 1).times(e), x = true, y(r)) : (e.s = r.s, r = e), r; + }; + m.toNumber = function() { + return +this; + }; + m.toOctal = function(e, t) { + return Si(this, 8, e, t); + }; + m.toPower = m.pow = function(e) { + var t, r, n, i, o, s, a = this, l = a.constructor, u = +(e = new l(e)); + if (!a.d || !e.d || !a.d[0] || !e.d[0]) return new l(G(+a, u)); + if (a = new l(a), a.eq(1)) return a; + if (n = l.precision, o = l.rounding, e.eq(1)) return y(a, n, o); + if (t = ee(e.e / b), t >= e.d.length - 1 && (r = u < 0 ? -u : u) <= xc) return i = Ss(l, a, r, n), e.s < 0 ? new l(1).div(i) : y(i, n, o); + if (s = a.s, s < 0) { + if (t < e.d.length - 1) return new l(NaN); + if (e.d[t] & 1 || (s = 1), a.e == 0 && a.d[0] == 1 && a.d.length == 1) return a.s = s, a; + } + return r = G(+a, u), t = r == 0 || !isFinite(r) ? ee(u * (Math.log("0." + K(a.d)) / Math.LN10 + a.e + 1)) : new l(r + "").e, t > l.maxE + 1 || t < l.minE - 1 ? new l(t > 0 ? s / 0 : 0) : (x = false, l.rounding = a.s = 1, r = Math.min(12, (t + "").length), i = Ri(e.times(He(a, n + r)), n), i.d && (i = y(i, n + 5, 1), rr(i.d, n, o) && (t = n + 10, i = y(Ri(e.times(He(a, t + r)), t), t + 5, 1), +K(i.d).slice(n + 1, n + 15) + 1 == 1e14 && (i = y(i, n + 1, 0)))), i.s = s, x = true, l.rounding = o, y(i, n, o)); + }; + m.toPrecision = function(e, t) { + var r, n = this, i = n.constructor; + return e === void 0 ? r = we(n, n.e <= i.toExpNeg || n.e >= i.toExpPos) : (ie(e, 1, ze), t === void 0 ? t = i.rounding : ie(t, 0, 8), n = y(new i(n), e, t), r = we(n, e <= n.e || n.e <= i.toExpNeg, e)), n.isNeg() && !n.isZero() ? "-" + r : r; + }; + m.toSignificantDigits = m.toSD = function(e, t) { + var r = this, n = r.constructor; + return e === void 0 ? (e = n.precision, t = n.rounding) : (ie(e, 1, ze), t === void 0 ? t = n.rounding : ie(t, 0, 8)), y(new n(r), e, t); + }; + m.toString = function() { + var e = this, t = e.constructor, r = we(e, e.e <= t.toExpNeg || e.e >= t.toExpPos); + return e.isNeg() && !e.isZero() ? "-" + r : r; + }; + m.truncated = m.trunc = function() { + return y(new this.constructor(this), this.e + 1, 1); + }; + m.valueOf = m.toJSON = function() { + var e = this, t = e.constructor, r = we(e, e.e <= t.toExpNeg || e.e >= t.toExpPos); + return e.isNeg() ? "-" + r : r; + }; + function K(e) { + var t, r, n, i = e.length - 1, o = "", s = e[0]; + if (i > 0) { + for (o += s, t = 1; t < i; t++) n = e[t] + "", r = b - n.length, r && (o += We(r)), o += n; + s = e[t], n = s + "", r = b - n.length, r && (o += We(r)); + } else if (s === 0) return "0"; + for (; s % 10 === 0; ) s /= 10; + return o + s; + } + function ie(e, t, r) { + if (e !== ~~e || e < t || e > r) throw Error(Ke + e); + } + function rr(e, t, r, n) { + var i, o, s, a; + for (o = e[0]; o >= 10; o /= 10) --t; + return --t < 0 ? (t += b, i = 0) : (i = Math.ceil((t + 1) / b), t %= b), o = G(10, b - t), a = e[i] % o | 0, n == null ? t < 3 ? (t == 0 ? a = a / 100 | 0 : t == 1 && (a = a / 10 | 0), s = r < 4 && a == 99999 || r > 3 && a == 49999 || a == 5e4 || a == 0) : s = (r < 4 && a + 1 == o || r > 3 && a + 1 == o / 2) && (e[i + 1] / o / 100 | 0) == G(10, t - 2) - 1 || (a == o / 2 || a == 0) && (e[i + 1] / o / 100 | 0) == 0 : t < 4 ? (t == 0 ? a = a / 1e3 | 0 : t == 1 ? a = a / 100 | 0 : t == 2 && (a = a / 10 | 0), s = (n || r < 4) && a == 9999 || !n && r > 3 && a == 4999) : s = ((n || r < 4) && a + 1 == o || !n && r > 3 && a + 1 == o / 2) && (e[i + 1] / o / 1e3 | 0) == G(10, t - 3) - 1, s; + } + function en(e, t, r) { + for (var n, i = [0], o, s = 0, a = e.length; s < a; ) { + for (o = i.length; o--; ) i[o] *= t; + for (i[0] += Pi.indexOf(e.charAt(s++)), n = 0; n < i.length; n++) i[n] > r - 1 && (i[n + 1] === void 0 && (i[n + 1] = 0), i[n + 1] += i[n] / r | 0, i[n] %= r); + } + return i.reverse(); + } + function vc(e, t) { + var r, n, i; + if (t.isZero()) return t; + n = t.d.length, n < 32 ? (r = Math.ceil(n / 3), i = (1 / an(4, r)).toString()) : (r = 16, i = "2.3283064365386962890625e-10"), e.precision += r, t = Et(e, 1, t.times(i), new e(1)); + for (var o = r; o--; ) { + var s = t.times(t); + t = s.times(s).minus(s).times(8).plus(1); + } + return e.precision -= r, t; + } + var N = /* @__PURE__ */ function() { + function e(n, i, o) { + var s, a = 0, l = n.length; + for (n = n.slice(); l--; ) s = n[l] * i + a, n[l] = s % o | 0, a = s / o | 0; + return a && n.unshift(a), n; + } + function t(n, i, o, s) { + var a, l; + if (o != s) l = o > s ? 1 : -1; + else for (a = l = 0; a < o; a++) if (n[a] != i[a]) { + l = n[a] > i[a] ? 1 : -1; + break; + } + return l; + } + function r(n, i, o, s) { + for (var a = 0; o--; ) n[o] -= a, a = n[o] < i[o] ? 1 : 0, n[o] = a * s + n[o] - i[o]; + for (; !n[0] && n.length > 1; ) n.shift(); + } + return function(n, i, o, s, a, l) { + var u, c, p, d, f, g, h, O, T, S, C, E, me, ae, Bt, U, ne, Ie, z, dt, Lr = n.constructor, qn = n.s == i.s ? 1 : -1, Y = n.d, _ = i.d; + if (!Y || !Y[0] || !_ || !_[0]) return new Lr(!n.s || !i.s || (Y ? _ && Y[0] == _[0] : !_) ? NaN : Y && Y[0] == 0 || !_ ? qn * 0 : qn / 0); + for (l ? (f = 1, c = n.e - i.e) : (l = ge, f = b, c = ee(n.e / f) - ee(i.e / f)), z = _.length, ne = Y.length, T = new Lr(qn), S = T.d = [], p = 0; _[p] == (Y[p] || 0); p++) ; + if (_[p] > (Y[p] || 0) && c--, o == null ? (ae = o = Lr.precision, s = Lr.rounding) : a ? ae = o + (n.e - i.e) + 1 : ae = o, ae < 0) S.push(1), g = true; + else { + if (ae = ae / f + 2 | 0, p = 0, z == 1) { + for (d = 0, _ = _[0], ae++; (p < ne || d) && ae--; p++) Bt = d * l + (Y[p] || 0), S[p] = Bt / _ | 0, d = Bt % _ | 0; + g = d || p < ne; + } else { + for (d = l / (_[0] + 1) | 0, d > 1 && (_ = e(_, d, l), Y = e(Y, d, l), z = _.length, ne = Y.length), U = z, C = Y.slice(0, z), E = C.length; E < z; ) C[E++] = 0; + dt = _.slice(), dt.unshift(0), Ie = _[0], _[1] >= l / 2 && ++Ie; + do + d = 0, u = t(_, C, z, E), u < 0 ? (me = C[0], z != E && (me = me * l + (C[1] || 0)), d = me / Ie | 0, d > 1 ? (d >= l && (d = l - 1), h = e(_, d, l), O = h.length, E = C.length, u = t(h, C, O, E), u == 1 && (d--, r(h, z < O ? dt : _, O, l))) : (d == 0 && (u = d = 1), h = _.slice()), O = h.length, O < E && h.unshift(0), r(C, h, E, l), u == -1 && (E = C.length, u = t(_, C, z, E), u < 1 && (d++, r(C, z < E ? dt : _, E, l))), E = C.length) : u === 0 && (d++, C = [0]), S[p++] = d, u && C[0] ? C[E++] = Y[U] || 0 : (C = [Y[U]], E = 1); + while ((U++ < ne || C[0] !== void 0) && ae--); + g = C[0] !== void 0; + } + S[0] || S.shift(); + } + if (f == 1) T.e = c, xs = g; + else { + for (p = 1, d = S[0]; d >= 10; d /= 10) p++; + T.e = p + c * f - 1, y(T, a ? o + T.e + 1 : o, s, g); + } + return T; + }; + }(); + function y(e, t, r, n) { + var i, o, s, a, l, u, c, p, d, f = e.constructor; + e: if (t != null) { + if (p = e.d, !p) return e; + for (i = 1, a = p[0]; a >= 10; a /= 10) i++; + if (o = t - i, o < 0) o += b, s = t, c = p[d = 0], l = c / G(10, i - s - 1) % 10 | 0; + else if (d = Math.ceil((o + 1) / b), a = p.length, d >= a) if (n) { + for (; a++ <= d; ) p.push(0); + c = l = 0, i = 1, o %= b, s = o - b + 1; + } else break e; + else { + for (c = a = p[d], i = 1; a >= 10; a /= 10) i++; + o %= b, s = o - b + i, l = s < 0 ? 0 : c / G(10, i - s - 1) % 10 | 0; + } + if (n = n || t < 0 || p[d + 1] !== void 0 || (s < 0 ? c : c % G(10, i - s - 1)), u = r < 4 ? (l || n) && (r == 0 || r == (e.s < 0 ? 3 : 2)) : l > 5 || l == 5 && (r == 4 || n || r == 6 && (o > 0 ? s > 0 ? c / G(10, i - s) : 0 : p[d - 1]) % 10 & 1 || r == (e.s < 0 ? 8 : 7)), t < 1 || !p[0]) return p.length = 0, u ? (t -= e.e + 1, p[0] = G(10, (b - t % b) % b), e.e = -t || 0) : p[0] = e.e = 0, e; + if (o == 0 ? (p.length = d, a = 1, d--) : (p.length = d + 1, a = G(10, b - o), p[d] = s > 0 ? (c / G(10, i - s) % G(10, s) | 0) * a : 0), u) for (; ; ) if (d == 0) { + for (o = 1, s = p[0]; s >= 10; s /= 10) o++; + for (s = p[0] += a, a = 1; s >= 10; s /= 10) a++; + o != a && (e.e++, p[0] == ge && (p[0] = 1)); + break; + } else { + if (p[d] += a, p[d] != ge) break; + p[d--] = 0, a = 1; + } + for (o = p.length; p[--o] === 0; ) p.pop(); + } + return x && (e.e > f.maxE ? (e.d = null, e.e = NaN) : e.e < f.minE && (e.e = 0, e.d = [0])), e; + } + function we(e, t, r) { + if (!e.isFinite()) return Is(e); + var n, i = e.e, o = K(e.d), s = o.length; + return t ? (r && (n = r - s) > 0 ? o = o.charAt(0) + "." + o.slice(1) + We(n) : s > 1 && (o = o.charAt(0) + "." + o.slice(1)), o = o + (e.e < 0 ? "e" : "e+") + e.e) : i < 0 ? (o = "0." + We(-i - 1) + o, r && (n = r - s) > 0 && (o += We(n))) : i >= s ? (o += We(i + 1 - s), r && (n = r - i - 1) > 0 && (o = o + "." + We(n))) : ((n = i + 1) < s && (o = o.slice(0, n) + "." + o.slice(n)), r && (n = r - s) > 0 && (i + 1 === s && (o += "."), o += We(n))), o; + } + function sn(e, t) { + var r = e[0]; + for (t *= b; r >= 10; r /= 10) t++; + return t; + } + function nn(e, t, r) { + if (t > Pc) throw x = true, r && (e.precision = r), Error(Ps); + return y(new e(tn), t, 1, true); + } + function fe(e, t, r) { + if (t > Ti) throw Error(Ps); + return y(new e(rn), t, r, true); + } + function Cs(e) { + var t = e.length - 1, r = t * b + 1; + if (t = e[t], t) { + for (; t % 10 == 0; t /= 10) r--; + for (t = e[0]; t >= 10; t /= 10) r++; + } + return r; + } + function We(e) { + for (var t = ""; e--; ) t += "0"; + return t; + } + function Ss(e, t, r, n) { + var i, o = new e(1), s = Math.ceil(n / b + 4); + for (x = false; ; ) { + if (r % 2 && (o = o.times(t), Es(o.d, s) && (i = true)), r = ee(r / 2), r === 0) { + r = o.d.length - 1, i && o.d[r] === 0 && ++o.d[r]; + break; + } + t = t.times(t), Es(t.d, s); + } + return x = true, o; + } + function bs(e) { + return e.d[e.d.length - 1] & 1; + } + function As(e, t, r) { + for (var n, i = new e(t[0]), o = 0; ++o < t.length; ) if (n = new e(t[o]), n.s) i[r](n) && (i = n); + else { + i = n; + break; + } + return i; + } + function Ri(e, t) { + var r, n, i, o, s, a, l, u = 0, c = 0, p = 0, d = e.constructor, f = d.rounding, g = d.precision; + if (!e.d || !e.d[0] || e.e > 17) return new d(e.d ? e.d[0] ? e.s < 0 ? 0 : 1 / 0 : 1 : e.s ? e.s < 0 ? 0 : e : NaN); + for (t == null ? (x = false, l = g) : l = t, a = new d(0.03125); e.e > -2; ) e = e.times(a), p += 5; + for (n = Math.log(G(2, p)) / Math.LN10 * 2 + 5 | 0, l += n, r = o = s = new d(1), d.precision = l; ; ) { + if (o = y(o.times(e), l, 1), r = r.times(++c), a = s.plus(N(o, r, l, 1)), K(a.d).slice(0, l) === K(s.d).slice(0, l)) { + for (i = p; i--; ) s = y(s.times(s), l, 1); + if (t == null) if (u < 3 && rr(s.d, l - n, f, u)) d.precision = l += 10, r = o = a = new d(1), c = 0, u++; + else return y(s, d.precision = g, f, x = true); + else return d.precision = g, s; + } + s = a; + } + } + function He(e, t) { + var r, n, i, o, s, a, l, u, c, p, d, f = 1, g = 10, h = e, O = h.d, T = h.constructor, S = T.rounding, C = T.precision; + if (h.s < 0 || !O || !O[0] || !h.e && O[0] == 1 && O.length == 1) return new T(O && !O[0] ? -1 / 0 : h.s != 1 ? NaN : O ? 0 : h); + if (t == null ? (x = false, c = C) : c = t, T.precision = c += g, r = K(O), n = r.charAt(0), Math.abs(o = h.e) < 15e14) { + for (; n < 7 && n != 1 || n == 1 && r.charAt(1) > 3; ) h = h.times(e), r = K(h.d), n = r.charAt(0), f++; + o = h.e, n > 1 ? (h = new T("0." + r), o++) : h = new T(n + "." + r.slice(1)); + } else return u = nn(T, c + 2, C).times(o + ""), h = He(new T(n + "." + r.slice(1)), c - g).plus(u), T.precision = C, t == null ? y(h, C, S, x = true) : h; + for (p = h, l = s = h = N(h.minus(1), h.plus(1), c, 1), d = y(h.times(h), c, 1), i = 3; ; ) { + if (s = y(s.times(d), c, 1), u = l.plus(N(s, new T(i), c, 1)), K(u.d).slice(0, c) === K(l.d).slice(0, c)) if (l = l.times(2), o !== 0 && (l = l.plus(nn(T, c + 2, C).times(o + ""))), l = N(l, new T(f), c, 1), t == null) if (rr(l.d, c - g, S, a)) T.precision = c += g, u = s = h = N(p.minus(1), p.plus(1), c, 1), d = y(h.times(h), c, 1), i = a = 1; + else return y(l, T.precision = C, S, x = true); + else return T.precision = C, l; + l = u, i += 2; + } + } + function Is(e) { + return String(e.s * e.s / 0); + } + function Ci(e, t) { + var r, n, i; + for ((r = t.indexOf(".")) > -1 && (t = t.replace(".", "")), (n = t.search(/e/i)) > 0 ? (r < 0 && (r = n), r += +t.slice(n + 1), t = t.substring(0, n)) : r < 0 && (r = t.length), n = 0; t.charCodeAt(n) === 48; n++) ; + for (i = t.length; t.charCodeAt(i - 1) === 48; --i) ; + if (t = t.slice(n, i), t) { + if (i -= n, e.e = r = r - n - 1, e.d = [], n = (r + 1) % b, r < 0 && (n += b), n < i) { + for (n && e.d.push(+t.slice(0, n)), i -= b; n < i; ) e.d.push(+t.slice(n, n += b)); + t = t.slice(n), n = b - t.length; + } else n -= i; + for (; n--; ) t += "0"; + e.d.push(+t), x && (e.e > e.constructor.maxE ? (e.d = null, e.e = NaN) : e.e < e.constructor.minE && (e.e = 0, e.d = [0])); + } else e.e = 0, e.d = [0]; + return e; + } + function Tc(e, t) { + var r, n, i, o, s, a, l, u, c; + if (t.indexOf("_") > -1) { + if (t = t.replace(/(\d)_(?=\d)/g, "$1"), Rs.test(t)) return Ci(e, t); + } else if (t === "Infinity" || t === "NaN") return +t || (e.s = NaN), e.e = NaN, e.d = null, e; + if (Ec.test(t)) r = 16, t = t.toLowerCase(); + else if (bc.test(t)) r = 2; + else if (wc.test(t)) r = 8; + else throw Error(Ke + t); + for (o = t.search(/p/i), o > 0 ? (l = +t.slice(o + 1), t = t.substring(2, o)) : t = t.slice(2), o = t.indexOf("."), s = o >= 0, n = e.constructor, s && (t = t.replace(".", ""), a = t.length, o = a - o, i = Ss(n, new n(r), o, o * 2)), u = en(t, r, ge), c = u.length - 1, o = c; u[o] === 0; --o) u.pop(); + return o < 0 ? new n(e.s * 0) : (e.e = sn(u, c), e.d = u, x = false, s && (e = N(e, i, a * 4)), l && (e = e.times(Math.abs(l) < 54 ? G(2, l) : it.pow(2, l))), x = true, e); + } + function Rc(e, t) { + var r, n = t.d.length; + if (n < 3) return t.isZero() ? t : Et(e, 2, t, t); + r = 1.4 * Math.sqrt(n), r = r > 16 ? 16 : r | 0, t = t.times(1 / an(5, r)), t = Et(e, 2, t, t); + for (var i, o = new e(5), s = new e(16), a = new e(20); r--; ) i = t.times(t), t = t.times(o.plus(i.times(s.times(i).minus(a)))); + return t; + } + function Et(e, t, r, n, i) { + var o, s, a, l, u = 1, c = e.precision, p = Math.ceil(c / b); + for (x = false, l = r.times(r), a = new e(n); ; ) { + if (s = N(a.times(l), new e(t++ * t++), c, 1), a = i ? n.plus(s) : n.minus(s), n = N(s.times(l), new e(t++ * t++), c, 1), s = a.plus(n), s.d[p] !== void 0) { + for (o = p; s.d[o] === a.d[o] && o--; ) ; + if (o == -1) break; + } + o = a, a = n, n = s, s = o, u++; + } + return x = true, s.d.length = p + 1, s; + } + function an(e, t) { + for (var r = e; --t; ) r *= e; + return r; + } + function Os(e, t) { + var r, n = t.s < 0, i = fe(e, e.precision, 1), o = i.times(0.5); + if (t = t.abs(), t.lte(o)) return Ne = n ? 4 : 1, t; + if (r = t.divToInt(i), r.isZero()) Ne = n ? 3 : 2; + else { + if (t = t.minus(r.times(i)), t.lte(o)) return Ne = bs(r) ? n ? 2 : 3 : n ? 4 : 1, t; + Ne = bs(r) ? n ? 1 : 4 : n ? 3 : 2; + } + return t.minus(i).abs(); + } + function Si(e, t, r, n) { + var i, o, s, a, l, u, c, p, d, f = e.constructor, g = r !== void 0; + if (g ? (ie(r, 1, ze), n === void 0 ? n = f.rounding : ie(n, 0, 8)) : (r = f.precision, n = f.rounding), !e.isFinite()) c = Is(e); + else { + for (c = we(e), s = c.indexOf("."), g ? (i = 2, t == 16 ? r = r * 4 - 3 : t == 8 && (r = r * 3 - 2)) : i = t, s >= 0 && (c = c.replace(".", ""), d = new f(1), d.e = c.length - s, d.d = en(we(d), 10, i), d.e = d.d.length), p = en(c, 10, i), o = l = p.length; p[--l] == 0; ) p.pop(); + if (!p[0]) c = g ? "0p+0" : "0"; + else { + if (s < 0 ? o-- : (e = new f(e), e.d = p, e.e = o, e = N(e, d, r, n, 0, i), p = e.d, o = e.e, u = xs), s = p[r], a = i / 2, u = u || p[r + 1] !== void 0, u = n < 4 ? (s !== void 0 || u) && (n === 0 || n === (e.s < 0 ? 3 : 2)) : s > a || s === a && (n === 4 || u || n === 6 && p[r - 1] & 1 || n === (e.s < 0 ? 8 : 7)), p.length = r, u) for (; ++p[--r] > i - 1; ) p[r] = 0, r || (++o, p.unshift(1)); + for (l = p.length; !p[l - 1]; --l) ; + for (s = 0, c = ""; s < l; s++) c += Pi.charAt(p[s]); + if (g) { + if (l > 1) if (t == 16 || t == 8) { + for (s = t == 16 ? 4 : 3, --l; l % s; l++) c += "0"; + for (p = en(c, i, t), l = p.length; !p[l - 1]; --l) ; + for (s = 1, c = "1."; s < l; s++) c += Pi.charAt(p[s]); + } else c = c.charAt(0) + "." + c.slice(1); + c = c + (o < 0 ? "p" : "p+") + o; + } else if (o < 0) { + for (; ++o; ) c = "0" + c; + c = "0." + c; + } else if (++o > l) for (o -= l; o--; ) c += "0"; + else o < l && (c = c.slice(0, o) + "." + c.slice(o)); + } + c = (t == 16 ? "0x" : t == 2 ? "0b" : t == 8 ? "0o" : "") + c; + } + return e.s < 0 ? "-" + c : c; + } + function Es(e, t) { + if (e.length > t) return e.length = t, true; + } + function Cc(e) { + return new this(e).abs(); + } + function Sc(e) { + return new this(e).acos(); + } + function Ac(e) { + return new this(e).acosh(); + } + function Ic(e, t) { + return new this(e).plus(t); + } + function Oc(e) { + return new this(e).asin(); + } + function kc(e) { + return new this(e).asinh(); + } + function Dc(e) { + return new this(e).atan(); + } + function _c(e) { + return new this(e).atanh(); + } + function Fc(e, t) { + e = new this(e), t = new this(t); + var r, n = this.precision, i = this.rounding, o = n + 4; + return !e.s || !t.s ? r = new this(NaN) : !e.d && !t.d ? (r = fe(this, o, 1).times(t.s > 0 ? 0.25 : 0.75), r.s = e.s) : !t.d || e.isZero() ? (r = t.s < 0 ? fe(this, n, i) : new this(0), r.s = e.s) : !e.d || t.isZero() ? (r = fe(this, o, 1).times(0.5), r.s = e.s) : t.s < 0 ? (this.precision = o, this.rounding = 1, r = this.atan(N(e, t, o, 1)), t = fe(this, o, 1), this.precision = n, this.rounding = i, r = e.s < 0 ? r.minus(t) : r.plus(t)) : r = this.atan(N(e, t, o, 1)), r; + } + function Lc(e) { + return new this(e).cbrt(); + } + function Nc(e) { + return y(e = new this(e), e.e + 1, 2); + } + function Mc(e, t, r) { + return new this(e).clamp(t, r); + } + function $c(e) { + if (!e || typeof e != "object") throw Error(on + "Object expected"); + var t, r, n, i = e.defaults === true, o = ["precision", 1, ze, "rounding", 0, 8, "toExpNeg", -bt, 0, "toExpPos", 0, bt, "maxE", 0, bt, "minE", -bt, 0, "modulo", 0, 9]; + for (t = 0; t < o.length; t += 3) if (r = o[t], i && (this[r] = vi[r]), (n = e[r]) !== void 0) if (ee(n) === n && n >= o[t + 1] && n <= o[t + 2]) this[r] = n; + else throw Error(Ke + r + ": " + n); + if (r = "crypto", i && (this[r] = vi[r]), (n = e[r]) !== void 0) if (n === true || n === false || n === 0 || n === 1) if (n) if (typeof crypto < "u" && crypto && (crypto.getRandomValues || crypto.randomBytes)) this[r] = true; + else throw Error(vs); + else this[r] = false; + else throw Error(Ke + r + ": " + n); + return this; + } + function qc(e) { + return new this(e).cos(); + } + function jc(e) { + return new this(e).cosh(); + } + function ks(e) { + var t, r, n; + function i(o) { + var s, a, l, u = this; + if (!(u instanceof i)) return new i(o); + if (u.constructor = i, ws(o)) { + u.s = o.s, x ? !o.d || o.e > i.maxE ? (u.e = NaN, u.d = null) : o.e < i.minE ? (u.e = 0, u.d = [0]) : (u.e = o.e, u.d = o.d.slice()) : (u.e = o.e, u.d = o.d ? o.d.slice() : o.d); + return; + } + if (l = typeof o, l === "number") { + if (o === 0) { + u.s = 1 / o < 0 ? -1 : 1, u.e = 0, u.d = [0]; + return; + } + if (o < 0 ? (o = -o, u.s = -1) : u.s = 1, o === ~~o && o < 1e7) { + for (s = 0, a = o; a >= 10; a /= 10) s++; + x ? s > i.maxE ? (u.e = NaN, u.d = null) : s < i.minE ? (u.e = 0, u.d = [0]) : (u.e = s, u.d = [o]) : (u.e = s, u.d = [o]); + return; + } else if (o * 0 !== 0) { + o || (u.s = NaN), u.e = NaN, u.d = null; + return; + } + return Ci(u, o.toString()); + } else if (l !== "string") throw Error(Ke + o); + return (a = o.charCodeAt(0)) === 45 ? (o = o.slice(1), u.s = -1) : (a === 43 && (o = o.slice(1)), u.s = 1), Rs.test(o) ? Ci(u, o) : Tc(u, o); + } + if (i.prototype = m, i.ROUND_UP = 0, i.ROUND_DOWN = 1, i.ROUND_CEIL = 2, i.ROUND_FLOOR = 3, i.ROUND_HALF_UP = 4, i.ROUND_HALF_DOWN = 5, i.ROUND_HALF_EVEN = 6, i.ROUND_HALF_CEIL = 7, i.ROUND_HALF_FLOOR = 8, i.EUCLID = 9, i.config = i.set = $c, i.clone = ks, i.isDecimal = ws, i.abs = Cc, i.acos = Sc, i.acosh = Ac, i.add = Ic, i.asin = Oc, i.asinh = kc, i.atan = Dc, i.atanh = _c, i.atan2 = Fc, i.cbrt = Lc, i.ceil = Nc, i.clamp = Mc, i.cos = qc, i.cosh = jc, i.div = Vc, i.exp = Bc, i.floor = Uc, i.hypot = Gc, i.ln = Qc, i.log = Jc, i.log10 = Hc, i.log2 = Wc, i.max = Kc, i.min = zc, i.mod = Yc, i.mul = Zc, i.pow = Xc, i.random = ep, i.round = tp, i.sign = rp, i.sin = np, i.sinh = ip, i.sqrt = op, i.sub = sp, i.sum = ap, i.tan = lp, i.tanh = up, i.trunc = cp, e === void 0 && (e = {}), e && e.defaults !== true) for (n = ["precision", "rounding", "toExpNeg", "toExpPos", "maxE", "minE", "modulo", "crypto"], t = 0; t < n.length; ) e.hasOwnProperty(r = n[t++]) || (e[r] = this[r]); + return i.config(e), i; + } + function Vc(e, t) { + return new this(e).div(t); + } + function Bc(e) { + return new this(e).exp(); + } + function Uc(e) { + return y(e = new this(e), e.e + 1, 3); + } + function Gc() { + var e, t, r = new this(0); + for (x = false, e = 0; e < arguments.length; ) if (t = new this(arguments[e++]), t.d) r.d && (r = r.plus(t.times(t))); + else { + if (t.s) return x = true, new this(1 / 0); + r = t; + } + return x = true, r.sqrt(); + } + function ws(e) { + return e instanceof it || e && e.toStringTag === Ts || false; + } + function Qc(e) { + return new this(e).ln(); + } + function Jc(e, t) { + return new this(e).log(t); + } + function Wc(e) { + return new this(e).log(2); + } + function Hc(e) { + return new this(e).log(10); + } + function Kc() { + return As(this, arguments, "lt"); + } + function zc() { + return As(this, arguments, "gt"); + } + function Yc(e, t) { + return new this(e).mod(t); + } + function Zc(e, t) { + return new this(e).mul(t); + } + function Xc(e, t) { + return new this(e).pow(t); + } + function ep(e) { + var t, r, n, i, o = 0, s = new this(1), a = []; + if (e === void 0 ? e = this.precision : ie(e, 1, ze), n = Math.ceil(e / b), this.crypto) if (crypto.getRandomValues) for (t = crypto.getRandomValues(new Uint32Array(n)); o < n; ) i = t[o], i >= 429e7 ? t[o] = crypto.getRandomValues(new Uint32Array(1))[0] : a[o++] = i % 1e7; + else if (crypto.randomBytes) { + for (t = crypto.randomBytes(n *= 4); o < n; ) i = t[o] + (t[o + 1] << 8) + (t[o + 2] << 16) + ((t[o + 3] & 127) << 24), i >= 214e7 ? crypto.randomBytes(4).copy(t, o) : (a.push(i % 1e7), o += 4); + o = n / 4; + } else throw Error(vs); + else for (; o < n; ) a[o++] = Math.random() * 1e7 | 0; + for (n = a[--o], e %= b, n && e && (i = G(10, b - e), a[o] = (n / i | 0) * i); a[o] === 0; o--) a.pop(); + if (o < 0) r = 0, a = [0]; + else { + for (r = -1; a[0] === 0; r -= b) a.shift(); + for (n = 1, i = a[0]; i >= 10; i /= 10) n++; + n < b && (r -= b - n); + } + return s.e = r, s.d = a, s; + } + function tp(e) { + return y(e = new this(e), e.e + 1, this.rounding); + } + function rp(e) { + return e = new this(e), e.d ? e.d[0] ? e.s : 0 * e.s : e.s || NaN; + } + function np(e) { + return new this(e).sin(); + } + function ip(e) { + return new this(e).sinh(); + } + function op(e) { + return new this(e).sqrt(); + } + function sp(e, t) { + return new this(e).sub(t); + } + function ap() { + var e = 0, t = arguments, r = new this(t[e]); + for (x = false; r.s && ++e < t.length; ) r = r.plus(t[e]); + return x = true, y(r, this.precision, this.rounding); + } + function lp(e) { + return new this(e).tan(); + } + function up(e) { + return new this(e).tanh(); + } + function cp(e) { + return y(e = new this(e), e.e + 1, 1); + } + m[Symbol.for("nodejs.util.inspect.custom")] = m.toString; + m[Symbol.toStringTag] = "Decimal"; + var it = m.constructor = ks(vi); + tn = new it(tn); + rn = new it(rn); + var xe = it; + function wt(e) { + return e === null ? e : Array.isArray(e) ? e.map(wt) : typeof e == "object" ? pp(e) ? dp(e) : yt(e, wt) : e; + } + function pp(e) { + return e !== null && typeof e == "object" && typeof e.$type == "string"; + } + function dp({ $type: e, value: t }) { + switch (e) { + case "BigInt": + return BigInt(t); + case "Bytes": + return Buffer.from(t, "base64"); + case "DateTime": + return new Date(t); + case "Decimal": + return new xe(t); + case "Json": + return JSON.parse(t); + default: + Fe(t, "Unknown tagged value"); + } + } + function xt(e) { + return e.substring(0, 1).toLowerCase() + e.substring(1); + } + function Pt(e) { + return e instanceof Date || Object.prototype.toString.call(e) === "[object Date]"; + } + function ln(e) { + return e.toString() !== "Invalid Date"; + } + function vt(e) { + return it.isDecimal(e) ? true : e !== null && typeof e == "object" && typeof e.s == "number" && typeof e.e == "number" && typeof e.toFixed == "function" && Array.isArray(e.d); + } + var Ms = k(fi()); + var Ns = k(__require("fs")); + var Ds = { keyword: De, entity: De, value: (e) => H(rt(e)), punctuation: rt, directive: De, function: De, variable: (e) => H(rt(e)), string: (e) => H(qe(e)), boolean: ke, number: De, comment: Gt }; + var mp = (e) => e; + var un = {}; + var fp = 0; + var P = { manual: un.Prism && un.Prism.manual, disableWorkerMessageHandler: un.Prism && un.Prism.disableWorkerMessageHandler, util: { encode: function(e) { + if (e instanceof he) { + let t = e; + return new he(t.type, P.util.encode(t.content), t.alias); + } else return Array.isArray(e) ? e.map(P.util.encode) : e.replace(/&/g, "&").replace(/ e.length) return; + if (Ie instanceof he) continue; + if (me && U != t.length - 1) { + S.lastIndex = ne; + var p = S.exec(e); + if (!p) break; + var c = p.index + (E ? p[1].length : 0), d = p.index + p[0].length, a = U, l = ne; + for (let _ = t.length; a < _ && (l < d || !t[a].type && !t[a - 1].greedy); ++a) l += t[a].length, c >= l && (++U, ne = l); + if (t[U] instanceof he) continue; + u = a - U, Ie = e.slice(ne, l), p.index -= ne; + } else { + S.lastIndex = 0; + var p = S.exec(Ie), u = 1; + } + if (!p) { + if (o) break; + continue; + } + E && (ae = p[1] ? p[1].length : 0); + var c = p.index + ae, p = p[0].slice(ae), d = c + p.length, f = Ie.slice(0, c), g = Ie.slice(d); + let z = [U, u]; + f && (++U, ne += f.length, z.push(f)); + let dt = new he(h, C ? P.tokenize(p, C) : p, Bt, p, me); + if (z.push(dt), g && z.push(g), Array.prototype.splice.apply(t, z), u != 1 && P.matchGrammar(e, t, r, U, ne, true, h), o) break; + } + } + } + }, tokenize: function(e, t) { + let r = [e], n = t.rest; + if (n) { + for (let i in n) t[i] = n[i]; + delete t.rest; + } + return P.matchGrammar(e, r, t, 0, 0, false), r; + }, hooks: { all: {}, add: function(e, t) { + let r = P.hooks.all; + r[e] = r[e] || [], r[e].push(t); + }, run: function(e, t) { + let r = P.hooks.all[e]; + if (!(!r || !r.length)) for (var n = 0, i; i = r[n++]; ) i(t); + } }, Token: he }; + P.languages.clike = { comment: [{ pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/, lookbehind: true }, { pattern: /(^|[^\\:])\/\/.*/, lookbehind: true, greedy: true }], string: { pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, greedy: true }, "class-name": { pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i, lookbehind: true, inside: { punctuation: /[.\\]/ } }, keyword: /\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/, boolean: /\b(?:true|false)\b/, function: /\w+(?=\()/, number: /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i, operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/, punctuation: /[{}[\];(),.:]/ }; + P.languages.javascript = P.languages.extend("clike", { "class-name": [P.languages.clike["class-name"], { pattern: /(^|[^$\w\xA0-\uFFFF])[_$A-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\.(?:prototype|constructor))/, lookbehind: true }], keyword: [{ pattern: /((?:^|})\s*)(?:catch|finally)\b/, lookbehind: true }, { pattern: /(^|[^.])\b(?:as|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/, lookbehind: true }], number: /\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/, function: /[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/, operator: /-[-=]?|\+[+=]?|!=?=?|<>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3}/ }); + P.languages.javascript["class-name"][0].pattern = /(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/; + P.languages.insertBefore("javascript", "keyword", { regex: { pattern: /((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^/\\\[\r\n])+\/[gimyus]{0,6}(?=\s*($|[\r\n,.;})\]]))/, lookbehind: true, greedy: true }, "function-variable": { pattern: /[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/, alias: "function" }, parameter: [{ pattern: /(function(?:\s+[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)?\s*\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\))/, lookbehind: true, inside: P.languages.javascript }, { pattern: /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=>)/i, inside: P.languages.javascript }, { pattern: /(\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*=>)/, lookbehind: true, inside: P.languages.javascript }, { pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*\s*)\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*\{)/, lookbehind: true, inside: P.languages.javascript }], constant: /\b[A-Z](?:[A-Z_]|\dx?)*\b/ }); + P.languages.markup && P.languages.markup.tag.addInlined("script", "javascript"); + P.languages.js = P.languages.javascript; + P.languages.typescript = P.languages.extend("javascript", { keyword: /\b(?:abstract|as|async|await|break|case|catch|class|const|constructor|continue|debugger|declare|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|module|namespace|new|null|of|package|private|protected|public|readonly|return|require|set|static|super|switch|this|throw|try|type|typeof|var|void|while|with|yield)\b/, builtin: /\b(?:string|Function|any|number|boolean|Array|symbol|console|Promise|unknown|never)\b/ }); + P.languages.ts = P.languages.typescript; + function he(e, t, r, n, i) { + this.type = e, this.content = t, this.alias = r, this.length = (n || "").length | 0, this.greedy = !!i; + } + he.stringify = function(e, t) { + return typeof e == "string" ? e : Array.isArray(e) ? e.map(function(r) { + return he.stringify(r, t); + }).join("") : gp(e.type)(e.content); + }; + function gp(e) { + return Ds[e] || mp; + } + function _s(e) { + return hp(e, P.languages.javascript); + } + function hp(e, t) { + return P.tokenize(e, t).map((n) => he.stringify(n)).join(""); + } + var Fs = k(us()); + function Ls(e) { + return (0, Fs.default)(e); + } + var cn = class e { + static read(t) { + let r; + try { + r = Ns.default.readFileSync(t, "utf-8"); + } catch { + return null; + } + return e.fromContent(r); + } + static fromContent(t) { + let r = t.split(/\r?\n/); + return new e(1, r); + } + constructor(t, r) { + this.firstLineNumber = t, this.lines = r; + } + get lastLineNumber() { + return this.firstLineNumber + this.lines.length - 1; + } + mapLineAt(t, r) { + if (t < this.firstLineNumber || t > this.lines.length + this.firstLineNumber) return this; + let n = t - this.firstLineNumber, i = [...this.lines]; + return i[n] = r(i[n]), new e(this.firstLineNumber, i); + } + mapLines(t) { + return new e(this.firstLineNumber, this.lines.map((r, n) => t(r, this.firstLineNumber + n))); + } + lineAt(t) { + return this.lines[t - this.firstLineNumber]; + } + prependSymbolAt(t, r) { + return this.mapLines((n, i) => i === t ? `${r} ${n}` : ` ${n}`); + } + slice(t, r) { + let n = this.lines.slice(t - 1, r).join(` +`); + return new e(t, Ls(n).split(` +`)); + } + highlight() { + let t = _s(this.toString()); + return new e(this.firstLineNumber, t.split(` +`)); + } + toString() { + return this.lines.join(` +`); + } + }; + var yp = { red: ce, gray: Gt, dim: Oe, bold: H, underline: X, highlightSource: (e) => e.highlight() }; + var bp = { red: (e) => e, gray: (e) => e, dim: (e) => e, bold: (e) => e, underline: (e) => e, highlightSource: (e) => e }; + function Ep({ message: e, originalMethod: t, isPanic: r, callArguments: n }) { + return { functionName: `prisma.${t}()`, message: e, isPanic: r ?? false, callArguments: n }; + } + function wp({ callsite: e, message: t, originalMethod: r, isPanic: n, callArguments: i }, o) { + let s = Ep({ message: t, originalMethod: r, isPanic: n, callArguments: i }); + if (!e || typeof window < "u" || process.env.NODE_ENV === "production") return s; + let a = e.getLocation(); + if (!a || !a.lineNumber || !a.columnNumber) return s; + let l = Math.max(1, a.lineNumber - 3), u = cn.read(a.fileName)?.slice(l, a.lineNumber), c = u?.lineAt(a.lineNumber); + if (u && c) { + let p = Pp(c), d = xp(c); + if (!d) return s; + s.functionName = `${d.code})`, s.location = a, n || (u = u.mapLineAt(a.lineNumber, (g) => g.slice(0, d.openingBraceIndex))), u = o.highlightSource(u); + let f = String(u.lastLineNumber).length; + if (s.contextLines = u.mapLines((g, h) => o.gray(String(h).padStart(f)) + " " + g).mapLines((g) => o.dim(g)).prependSymbolAt(a.lineNumber, o.bold(o.red("\u2192"))), i) { + let g = p + f + 1; + g += 2, s.callArguments = (0, Ms.default)(i, g).slice(g); + } + } + return s; + } + function xp(e) { + let t = Object.keys(Je.ModelAction).join("|"), n = new RegExp(String.raw`\.(${t})\(`).exec(e); + if (n) { + let i = n.index + n[0].length, o = e.lastIndexOf(" ", n.index) + 1; + return { code: e.slice(o, i), openingBraceIndex: i }; + } + return null; + } + function Pp(e) { + let t = 0; + for (let r = 0; r < e.length; r++) { + if (e.charAt(r) !== " ") return t; + t++; + } + return t; + } + function vp({ functionName: e, location: t, message: r, isPanic: n, contextLines: i, callArguments: o }, s) { + let a = [""], l = t ? " in" : ":"; + if (n ? (a.push(s.red(`Oops, an unknown error occurred! This is ${s.bold("on us")}, you did nothing wrong.`)), a.push(s.red(`It occurred in the ${s.bold(`\`${e}\``)} invocation${l}`))) : a.push(s.red(`Invalid ${s.bold(`\`${e}\``)} invocation${l}`)), t && a.push(s.underline(Tp(t))), i) { + a.push(""); + let u = [i.toString()]; + o && (u.push(o), u.push(s.dim(")"))), a.push(u.join("")), o && a.push(""); + } else a.push(""), o && a.push(o), a.push(""); + return a.push(r), a.join(` +`); + } + function Tp(e) { + let t = [e.fileName]; + return e.lineNumber && t.push(String(e.lineNumber)), e.columnNumber && t.push(String(e.columnNumber)), t.join(":"); + } + function Tt(e) { + let t = e.showColors ? yp : bp, r; + return r = wp(e, t), vp(r, t); + } + var Gs = k(Ai()); + function Vs(e, t, r) { + let n = Bs(e), i = Rp(n), o = Sp(i); + o ? pn(o, t, r) : t.addErrorMessage(() => "Unknown error"); + } + function Bs(e) { + return e.errors.flatMap((t) => t.kind === "Union" ? Bs(t) : [t]); + } + function Rp(e) { + let t = /* @__PURE__ */ new Map(), r = []; + for (let n of e) { + if (n.kind !== "InvalidArgumentType") { + r.push(n); + continue; + } + let i = `${n.selectionPath.join(".")}:${n.argumentPath.join(".")}`, o = t.get(i); + o ? t.set(i, { ...n, argument: { ...n.argument, typeNames: Cp(o.argument.typeNames, n.argument.typeNames) } }) : t.set(i, n); + } + return r.push(...t.values()), r; + } + function Cp(e, t) { + return [...new Set(e.concat(t))]; + } + function Sp(e) { + return xi(e, (t, r) => { + let n = qs(t), i = qs(r); + return n !== i ? n - i : js(t) - js(r); + }); + } + function qs(e) { + let t = 0; + return Array.isArray(e.selectionPath) && (t += e.selectionPath.length), Array.isArray(e.argumentPath) && (t += e.argumentPath.length), t; + } + function js(e) { + switch (e.kind) { + case "InvalidArgumentValue": + case "ValueTooLarge": + return 20; + case "InvalidArgumentType": + return 10; + case "RequiredArgumentMissing": + return -10; + default: + return 0; + } + } + var ue = class { + constructor(t, r) { + this.name = t; + this.value = r; + this.isRequired = false; + } + makeRequired() { + return this.isRequired = true, this; + } + write(t) { + let { colors: { green: r } } = t.context; + t.addMarginSymbol(r(this.isRequired ? "+" : "?")), t.write(r(this.name)), this.isRequired || t.write(r("?")), t.write(r(": ")), typeof this.value == "string" ? t.write(r(this.value)) : t.write(this.value); + } + }; + var Rt = class { + constructor(t = 0, r) { + this.context = r; + this.lines = []; + this.currentLine = ""; + this.currentIndent = 0; + this.currentIndent = t; + } + write(t) { + return typeof t == "string" ? this.currentLine += t : t.write(this), this; + } + writeJoined(t, r, n = (i, o) => o.write(i)) { + let i = r.length - 1; + for (let o = 0; o < r.length; o++) n(r[o], this), o !== i && this.write(t); + return this; + } + writeLine(t) { + return this.write(t).newLine(); + } + newLine() { + this.lines.push(this.indentedCurrentLine()), this.currentLine = "", this.marginSymbol = void 0; + let t = this.afterNextNewLineCallback; + return this.afterNextNewLineCallback = void 0, t?.(), this; + } + withIndent(t) { + return this.indent(), t(this), this.unindent(), this; + } + afterNextNewline(t) { + return this.afterNextNewLineCallback = t, this; + } + indent() { + return this.currentIndent++, this; + } + unindent() { + return this.currentIndent > 0 && this.currentIndent--, this; + } + addMarginSymbol(t) { + return this.marginSymbol = t, this; + } + toString() { + return this.lines.concat(this.indentedCurrentLine()).join(` +`); + } + getCurrentLineLength() { + return this.currentLine.length; + } + indentedCurrentLine() { + let t = this.currentLine.padStart(this.currentLine.length + 2 * this.currentIndent); + return this.marginSymbol ? this.marginSymbol + t.slice(1) : t; + } + }; + var dn = class { + constructor(t) { + this.value = t; + } + write(t) { + t.write(this.value); + } + markAsError() { + this.value.markAsError(); + } + }; + var mn = (e) => e; + var fn = { bold: mn, red: mn, green: mn, dim: mn, enabled: false }; + var Us = { bold: H, red: ce, green: qe, dim: Oe, enabled: true }; + var Ct = { write(e) { + e.writeLine(","); + } }; + var Pe = class { + constructor(t) { + this.contents = t; + this.isUnderlined = false; + this.color = (t2) => t2; + } + underline() { + return this.isUnderlined = true, this; + } + setColor(t) { + return this.color = t, this; + } + write(t) { + let r = t.getCurrentLineLength(); + t.write(this.color(this.contents)), this.isUnderlined && t.afterNextNewline(() => { + t.write(" ".repeat(r)).writeLine(this.color("~".repeat(this.contents.length))); + }); + } + }; + var Ye = class { + constructor() { + this.hasError = false; + } + markAsError() { + return this.hasError = true, this; + } + }; + var St = class extends Ye { + constructor() { + super(...arguments); + this.items = []; + } + addItem(r) { + return this.items.push(new dn(r)), this; + } + getField(r) { + return this.items[r]; + } + getPrintWidth() { + return this.items.length === 0 ? 2 : Math.max(...this.items.map((n) => n.value.getPrintWidth())) + 2; + } + write(r) { + if (this.items.length === 0) { + this.writeEmpty(r); + return; + } + this.writeWithItems(r); + } + writeEmpty(r) { + let n = new Pe("[]"); + this.hasError && n.setColor(r.context.colors.red).underline(), r.write(n); + } + writeWithItems(r) { + let { colors: n } = r.context; + r.writeLine("[").withIndent(() => r.writeJoined(Ct, this.items).newLine()).write("]"), this.hasError && r.afterNextNewline(() => { + r.writeLine(n.red("~".repeat(this.getPrintWidth()))); + }); + } + asObject() { + } + }; + var At = class e extends Ye { + constructor() { + super(...arguments); + this.fields = {}; + this.suggestions = []; + } + addField(r) { + this.fields[r.name] = r; + } + addSuggestion(r) { + this.suggestions.push(r); + } + getField(r) { + return this.fields[r]; + } + getDeepField(r) { + let [n, ...i] = r, o = this.getField(n); + if (!o) return; + let s = o; + for (let a of i) { + let l; + if (s.value instanceof e ? l = s.value.getField(a) : s.value instanceof St && (l = s.value.getField(Number(a))), !l) return; + s = l; + } + return s; + } + getDeepFieldValue(r) { + return r.length === 0 ? this : this.getDeepField(r)?.value; + } + hasField(r) { + return !!this.getField(r); + } + removeAllFields() { + this.fields = {}; + } + removeField(r) { + delete this.fields[r]; + } + getFields() { + return this.fields; + } + isEmpty() { + return Object.keys(this.fields).length === 0; + } + getFieldValue(r) { + return this.getField(r)?.value; + } + getDeepSubSelectionValue(r) { + let n = this; + for (let i of r) { + if (!(n instanceof e)) return; + let o = n.getSubSelectionValue(i); + if (!o) return; + n = o; + } + return n; + } + getDeepSelectionParent(r) { + let n = this.getSelectionParent(); + if (!n) return; + let i = n; + for (let o of r) { + let s = i.value.getFieldValue(o); + if (!s || !(s instanceof e)) return; + let a = s.getSelectionParent(); + if (!a) return; + i = a; + } + return i; + } + getSelectionParent() { + let r = this.getField("select")?.value.asObject(); + if (r) return { kind: "select", value: r }; + let n = this.getField("include")?.value.asObject(); + if (n) return { kind: "include", value: n }; + } + getSubSelectionValue(r) { + return this.getSelectionParent()?.value.fields[r].value; + } + getPrintWidth() { + let r = Object.values(this.fields); + return r.length == 0 ? 2 : Math.max(...r.map((i) => i.getPrintWidth())) + 2; + } + write(r) { + let n = Object.values(this.fields); + if (n.length === 0 && this.suggestions.length === 0) { + this.writeEmpty(r); + return; + } + this.writeWithContents(r, n); + } + asObject() { + return this; + } + writeEmpty(r) { + let n = new Pe("{}"); + this.hasError && n.setColor(r.context.colors.red).underline(), r.write(n); + } + writeWithContents(r, n) { + r.writeLine("{").withIndent(() => { + r.writeJoined(Ct, [...n, ...this.suggestions]).newLine(); + }), r.write("}"), this.hasError && r.afterNextNewline(() => { + r.writeLine(r.context.colors.red("~".repeat(this.getPrintWidth()))); + }); + } + }; + var W = class extends Ye { + constructor(r) { + super(); + this.text = r; + } + getPrintWidth() { + return this.text.length; + } + write(r) { + let n = new Pe(this.text); + this.hasError && n.underline().setColor(r.context.colors.red), r.write(n); + } + asObject() { + } + }; + var nr = class { + constructor() { + this.fields = []; + } + addField(t, r) { + return this.fields.push({ write(n) { + let { green: i, dim: o } = n.context.colors; + n.write(i(o(`${t}: ${r}`))).addMarginSymbol(i(o("+"))); + } }), this; + } + write(t) { + let { colors: { green: r } } = t.context; + t.writeLine(r("{")).withIndent(() => { + t.writeJoined(Ct, this.fields).newLine(); + }).write(r("}")).addMarginSymbol(r("+")); + } + }; + function pn(e, t, r) { + switch (e.kind) { + case "MutuallyExclusiveFields": + Ip(e, t); + break; + case "IncludeOnScalar": + Op(e, t); + break; + case "EmptySelection": + kp(e, t, r); + break; + case "UnknownSelectionField": + Lp(e, t); + break; + case "InvalidSelectionValue": + Np(e, t); + break; + case "UnknownArgument": + Mp(e, t); + break; + case "UnknownInputField": + $p(e, t); + break; + case "RequiredArgumentMissing": + qp(e, t); + break; + case "InvalidArgumentType": + jp(e, t); + break; + case "InvalidArgumentValue": + Vp(e, t); + break; + case "ValueTooLarge": + Bp(e, t); + break; + case "SomeFieldsMissing": + Up(e, t); + break; + case "TooManyFieldsGiven": + Gp(e, t); + break; + case "Union": + Vs(e, t, r); + break; + default: + throw new Error("not implemented: " + e.kind); + } + } + function Ip(e, t) { + let r = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + r && (r.getField(e.firstField)?.markAsError(), r.getField(e.secondField)?.markAsError()), t.addErrorMessage((n) => `Please ${n.bold("either")} use ${n.green(`\`${e.firstField}\``)} or ${n.green(`\`${e.secondField}\``)}, but ${n.red("not both")} at the same time.`); + } + function Op(e, t) { + let [r, n] = ir(e.selectionPath), i = e.outputType, o = t.arguments.getDeepSelectionParent(r)?.value; + if (o && (o.getField(n)?.markAsError(), i)) for (let s of i.fields) s.isRelation && o.addSuggestion(new ue(s.name, "true")); + t.addErrorMessage((s) => { + let a = `Invalid scalar field ${s.red(`\`${n}\``)} for ${s.bold("include")} statement`; + return i ? a += ` on model ${s.bold(i.name)}. ${or(s)}` : a += ".", a += ` +Note that ${s.bold("include")} statements only accept relation fields.`, a; + }); + } + function kp(e, t, r) { + let n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + if (n) { + let i = n.getField("omit")?.value.asObject(); + if (i) { + Dp(e, t, i); + return; + } + if (n.hasField("select")) { + _p(e, t); + return; + } + } + if (r?.[xt(e.outputType.name)]) { + Fp(e, t); + return; + } + t.addErrorMessage(() => `Unknown field at "${e.selectionPath.join(".")} selection"`); + } + function Dp(e, t, r) { + r.removeAllFields(); + for (let n of e.outputType.fields) r.addSuggestion(new ue(n.name, "false")); + t.addErrorMessage((n) => `The ${n.red("omit")} statement includes every field of the model ${n.bold(e.outputType.name)}. At least one field must be included in the result`); + } + function _p(e, t) { + let r = e.outputType, n = t.arguments.getDeepSelectionParent(e.selectionPath)?.value, i = n?.isEmpty() ?? false; + n && (n.removeAllFields(), Ws(n, r)), t.addErrorMessage((o) => i ? `The ${o.red("`select`")} statement for type ${o.bold(r.name)} must not be empty. ${or(o)}` : `The ${o.red("`select`")} statement for type ${o.bold(r.name)} needs ${o.bold("at least one truthy value")}.`); + } + function Fp(e, t) { + let r = new nr(); + for (let i of e.outputType.fields) i.isRelation || r.addField(i.name, "false"); + let n = new ue("omit", r).makeRequired(); + if (e.selectionPath.length === 0) t.arguments.addSuggestion(n); + else { + let [i, o] = ir(e.selectionPath), a = t.arguments.getDeepSelectionParent(i)?.value.asObject()?.getField(o); + if (a) { + let l = a?.value.asObject() ?? new At(); + l.addSuggestion(n), a.value = l; + } + } + t.addErrorMessage((i) => `The global ${i.red("omit")} configuration excludes every field of the model ${i.bold(e.outputType.name)}. At least one field must be included in the result`); + } + function Lp(e, t) { + let r = Hs(e.selectionPath, t); + if (r.parentKind !== "unknown") { + r.field.markAsError(); + let n = r.parent; + switch (r.parentKind) { + case "select": + Ws(n, e.outputType); + break; + case "include": + Qp(n, e.outputType); + break; + case "omit": + Jp(n, e.outputType); + break; + } + } + t.addErrorMessage((n) => { + let i = [`Unknown field ${n.red(`\`${r.fieldName}\``)}`]; + return r.parentKind !== "unknown" && i.push(`for ${n.bold(r.parentKind)} statement`), i.push(`on model ${n.bold(`\`${e.outputType.name}\``)}.`), i.push(or(n)), i.join(" "); + }); + } + function Np(e, t) { + let r = Hs(e.selectionPath, t); + r.parentKind !== "unknown" && r.field.value.markAsError(), t.addErrorMessage((n) => `Invalid value for selection field \`${n.red(r.fieldName)}\`: ${e.underlyingError}`); + } + function Mp(e, t) { + let r = e.argumentPath[0], n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + n && (n.getField(r)?.markAsError(), Wp(n, e.arguments)), t.addErrorMessage((i) => Qs(i, r, e.arguments.map((o) => o.name))); + } + function $p(e, t) { + let [r, n] = ir(e.argumentPath), i = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + if (i) { + i.getDeepField(e.argumentPath)?.markAsError(); + let o = i.getDeepFieldValue(r)?.asObject(); + o && Ks(o, e.inputType); + } + t.addErrorMessage((o) => Qs(o, n, e.inputType.fields.map((s) => s.name))); + } + function Qs(e, t, r) { + let n = [`Unknown argument \`${e.red(t)}\`.`], i = Kp(t, r); + return i && n.push(`Did you mean \`${e.green(i)}\`?`), r.length > 0 && n.push(or(e)), n.join(" "); + } + function qp(e, t) { + let r; + t.addErrorMessage((l) => r?.value instanceof W && r.value.text === "null" ? `Argument \`${l.green(o)}\` must not be ${l.red("null")}.` : `Argument \`${l.green(o)}\` is missing.`); + let n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + if (!n) return; + let [i, o] = ir(e.argumentPath), s = new nr(), a = n.getDeepFieldValue(i)?.asObject(); + if (a) if (r = a.getField(o), r && a.removeField(o), e.inputTypes.length === 1 && e.inputTypes[0].kind === "object") { + for (let l of e.inputTypes[0].fields) s.addField(l.name, l.typeNames.join(" | ")); + a.addSuggestion(new ue(o, s).makeRequired()); + } else { + let l = e.inputTypes.map(Js).join(" | "); + a.addSuggestion(new ue(o, l).makeRequired()); + } + } + function Js(e) { + return e.kind === "list" ? `${Js(e.elementType)}[]` : e.name; + } + function jp(e, t) { + let r = e.argument.name, n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + n && n.getDeepFieldValue(e.argumentPath)?.markAsError(), t.addErrorMessage((i) => { + let o = gn("or", e.argument.typeNames.map((s) => i.green(s))); + return `Argument \`${i.bold(r)}\`: Invalid value provided. Expected ${o}, provided ${i.red(e.inferredType)}.`; + }); + } + function Vp(e, t) { + let r = e.argument.name, n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + n && n.getDeepFieldValue(e.argumentPath)?.markAsError(), t.addErrorMessage((i) => { + let o = [`Invalid value for argument \`${i.bold(r)}\``]; + if (e.underlyingError && o.push(`: ${e.underlyingError}`), o.push("."), e.argument.typeNames.length > 0) { + let s = gn("or", e.argument.typeNames.map((a) => i.green(a))); + o.push(` Expected ${s}.`); + } + return o.join(""); + }); + } + function Bp(e, t) { + let r = e.argument.name, n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(), i; + if (n) { + let s = n.getDeepField(e.argumentPath)?.value; + s?.markAsError(), s instanceof W && (i = s.text); + } + t.addErrorMessage((o) => { + let s = ["Unable to fit value"]; + return i && s.push(o.red(i)), s.push(`into a 64-bit signed integer for field \`${o.bold(r)}\``), s.join(" "); + }); + } + function Up(e, t) { + let r = e.argumentPath[e.argumentPath.length - 1], n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + if (n) { + let i = n.getDeepFieldValue(e.argumentPath)?.asObject(); + i && Ks(i, e.inputType); + } + t.addErrorMessage((i) => { + let o = [`Argument \`${i.bold(r)}\` of type ${i.bold(e.inputType.name)} needs`]; + return e.constraints.minFieldCount === 1 ? e.constraints.requiredFields ? o.push(`${i.green("at least one of")} ${gn("or", e.constraints.requiredFields.map((s) => `\`${i.bold(s)}\``))} arguments.`) : o.push(`${i.green("at least one")} argument.`) : o.push(`${i.green(`at least ${e.constraints.minFieldCount}`)} arguments.`), o.push(or(i)), o.join(" "); + }); + } + function Gp(e, t) { + let r = e.argumentPath[e.argumentPath.length - 1], n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(), i = []; + if (n) { + let o = n.getDeepFieldValue(e.argumentPath)?.asObject(); + o && (o.markAsError(), i = Object.keys(o.getFields())); + } + t.addErrorMessage((o) => { + let s = [`Argument \`${o.bold(r)}\` of type ${o.bold(e.inputType.name)} needs`]; + return e.constraints.minFieldCount === 1 && e.constraints.maxFieldCount == 1 ? s.push(`${o.green("exactly one")} argument,`) : e.constraints.maxFieldCount == 1 ? s.push(`${o.green("at most one")} argument,`) : s.push(`${o.green(`at most ${e.constraints.maxFieldCount}`)} arguments,`), s.push(`but you provided ${gn("and", i.map((a) => o.red(a)))}. Please choose`), e.constraints.maxFieldCount === 1 ? s.push("one.") : s.push(`${e.constraints.maxFieldCount}.`), s.join(" "); + }); + } + function Ws(e, t) { + for (let r of t.fields) e.hasField(r.name) || e.addSuggestion(new ue(r.name, "true")); + } + function Qp(e, t) { + for (let r of t.fields) r.isRelation && !e.hasField(r.name) && e.addSuggestion(new ue(r.name, "true")); + } + function Jp(e, t) { + for (let r of t.fields) !e.hasField(r.name) && !r.isRelation && e.addSuggestion(new ue(r.name, "true")); + } + function Wp(e, t) { + for (let r of t) e.hasField(r.name) || e.addSuggestion(new ue(r.name, r.typeNames.join(" | "))); + } + function Hs(e, t) { + let [r, n] = ir(e), i = t.arguments.getDeepSubSelectionValue(r)?.asObject(); + if (!i) return { parentKind: "unknown", fieldName: n }; + let o = i.getFieldValue("select")?.asObject(), s = i.getFieldValue("include")?.asObject(), a = i.getFieldValue("omit")?.asObject(), l = o?.getField(n); + return o && l ? { parentKind: "select", parent: o, field: l, fieldName: n } : (l = s?.getField(n), s && l ? { parentKind: "include", field: l, parent: s, fieldName: n } : (l = a?.getField(n), a && l ? { parentKind: "omit", field: l, parent: a, fieldName: n } : { parentKind: "unknown", fieldName: n })); + } + function Ks(e, t) { + if (t.kind === "object") for (let r of t.fields) e.hasField(r.name) || e.addSuggestion(new ue(r.name, r.typeNames.join(" | "))); + } + function ir(e) { + let t = [...e], r = t.pop(); + if (!r) throw new Error("unexpected empty path"); + return [t, r]; + } + function or({ green: e, enabled: t }) { + return "Available options are " + (t ? `listed in ${e("green")}` : "marked with ?") + "."; + } + function gn(e, t) { + if (t.length === 1) return t[0]; + let r = [...t], n = r.pop(); + return `${r.join(", ")} ${e} ${n}`; + } + var Hp = 3; + function Kp(e, t) { + let r = 1 / 0, n; + for (let i of t) { + let o = (0, Gs.default)(e, i); + o > Hp || o < r && (r = o, n = i); + } + return n; + } + function zs(e) { + return e.substring(0, 1).toLowerCase() + e.substring(1); + } + var sr = class { + constructor(t, r, n, i, o) { + this.modelName = t, this.name = r, this.typeName = n, this.isList = i, this.isEnum = o; + } + _toGraphQLInputType() { + let t = this.isList ? "List" : "", r = this.isEnum ? "Enum" : ""; + return `${t}${r}${this.typeName}FieldRefInput<${this.modelName}>`; + } + }; + function It(e) { + return e instanceof sr; + } + var hn = Symbol(); + var Ii = /* @__PURE__ */ new WeakMap(); + var Me = class { + constructor(t) { + t === hn ? Ii.set(this, `Prisma.${this._getName()}`) : Ii.set(this, `new Prisma.${this._getNamespace()}.${this._getName()}()`); + } + _getName() { + return this.constructor.name; + } + toString() { + return Ii.get(this); + } + }; + var ar = class extends Me { + _getNamespace() { + return "NullTypes"; + } + }; + var lr = class extends ar { + }; + Oi(lr, "DbNull"); + var ur = class extends ar { + }; + Oi(ur, "JsonNull"); + var cr = class extends ar { + }; + Oi(cr, "AnyNull"); + var yn = { classes: { DbNull: lr, JsonNull: ur, AnyNull: cr }, instances: { DbNull: new lr(hn), JsonNull: new ur(hn), AnyNull: new cr(hn) } }; + function Oi(e, t) { + Object.defineProperty(e, "name", { value: t, configurable: true }); + } + var Ys = ": "; + var bn = class { + constructor(t, r) { + this.name = t; + this.value = r; + this.hasError = false; + } + markAsError() { + this.hasError = true; + } + getPrintWidth() { + return this.name.length + this.value.getPrintWidth() + Ys.length; + } + write(t) { + let r = new Pe(this.name); + this.hasError && r.underline().setColor(t.context.colors.red), t.write(r).write(Ys).write(this.value); + } + }; + var ki = class { + constructor(t) { + this.errorMessages = []; + this.arguments = t; + } + write(t) { + t.write(this.arguments); + } + addErrorMessage(t) { + this.errorMessages.push(t); + } + renderAllMessages(t) { + return this.errorMessages.map((r) => r(t)).join(` +`); + } + }; + function Ot(e) { + return new ki(Zs(e)); + } + function Zs(e) { + let t = new At(); + for (let [r, n] of Object.entries(e)) { + let i = new bn(r, Xs(n)); + t.addField(i); + } + return t; + } + function Xs(e) { + if (typeof e == "string") return new W(JSON.stringify(e)); + if (typeof e == "number" || typeof e == "boolean") return new W(String(e)); + if (typeof e == "bigint") return new W(`${e}n`); + if (e === null) return new W("null"); + if (e === void 0) return new W("undefined"); + if (vt(e)) return new W(`new Prisma.Decimal("${e.toFixed()}")`); + if (e instanceof Uint8Array) return Buffer.isBuffer(e) ? new W(`Buffer.alloc(${e.byteLength})`) : new W(`new Uint8Array(${e.byteLength})`); + if (e instanceof Date) { + let t = ln(e) ? e.toISOString() : "Invalid Date"; + return new W(`new Date("${t}")`); + } + return e instanceof Me ? new W(`Prisma.${e._getName()}`) : It(e) ? new W(`prisma.${zs(e.modelName)}.$fields.${e.name}`) : Array.isArray(e) ? zp(e) : typeof e == "object" ? Zs(e) : new W(Object.prototype.toString.call(e)); + } + function zp(e) { + let t = new St(); + for (let r of e) t.addItem(Xs(r)); + return t; + } + function En(e, t) { + let r = t === "pretty" ? Us : fn, n = e.renderAllMessages(r), i = new Rt(0, { colors: r }).write(e).toString(); + return { message: n, args: i }; + } + function wn({ args: e, errors: t, errorFormat: r, callsite: n, originalMethod: i, clientVersion: o, globalOmit: s }) { + let a = Ot(e); + for (let p of t) pn(p, a, s); + let { message: l, args: u } = En(a, r), c = Tt({ message: l, callsite: n, originalMethod: i, showColors: r === "pretty", callArguments: u }); + throw new J(c, { clientVersion: o }); + } + var ve = class { + constructor() { + this._map = /* @__PURE__ */ new Map(); + } + get(t) { + return this._map.get(t)?.value; + } + set(t, r) { + this._map.set(t, { value: r }); + } + getOrCreate(t, r) { + let n = this._map.get(t); + if (n) return n.value; + let i = r(); + return this.set(t, i), i; + } + }; + function pr(e) { + let t; + return { get() { + return t || (t = { value: e() }), t.value; + } }; + } + function Te(e) { + return e.replace(/^./, (t) => t.toLowerCase()); + } + function ta(e, t, r) { + let n = Te(r); + return !t.result || !(t.result.$allModels || t.result[n]) ? e : Yp({ ...e, ...ea(t.name, e, t.result.$allModels), ...ea(t.name, e, t.result[n]) }); + } + function Yp(e) { + let t = new ve(), r = (n, i) => t.getOrCreate(n, () => i.has(n) ? [n] : (i.add(n), e[n] ? e[n].needs.flatMap((o) => r(o, i)) : [n])); + return yt(e, (n) => ({ ...n, needs: r(n.name, /* @__PURE__ */ new Set()) })); + } + function ea(e, t, r) { + return r ? yt(r, ({ needs: n, compute: i }, o) => ({ name: o, needs: n ? Object.keys(n).filter((s) => n[s]) : [], compute: Zp(t, o, i) })) : {}; + } + function Zp(e, t, r) { + let n = e?.[t]?.compute; + return n ? (i) => r({ ...i, [t]: n(i) }) : r; + } + function ra(e, t) { + if (!t) return e; + let r = { ...e }; + for (let n of Object.values(t)) if (e[n.name]) for (let i of n.needs) r[i] = true; + return r; + } + function na(e, t) { + if (!t) return e; + let r = { ...e }; + for (let n of Object.values(t)) if (!e[n.name]) for (let i of n.needs) delete r[i]; + return r; + } + var xn = class { + constructor(t, r) { + this.extension = t; + this.previous = r; + this.computedFieldsCache = new ve(); + this.modelExtensionsCache = new ve(); + this.queryCallbacksCache = new ve(); + this.clientExtensions = pr(() => this.extension.client ? { ...this.previous?.getAllClientExtensions(), ...this.extension.client } : this.previous?.getAllClientExtensions()); + this.batchCallbacks = pr(() => { + let t2 = this.previous?.getAllBatchQueryCallbacks() ?? [], r2 = this.extension.query?.$__internalBatch; + return r2 ? t2.concat(r2) : t2; + }); + } + getAllComputedFields(t) { + return this.computedFieldsCache.getOrCreate(t, () => ta(this.previous?.getAllComputedFields(t), this.extension, t)); + } + getAllClientExtensions() { + return this.clientExtensions.get(); + } + getAllModelExtensions(t) { + return this.modelExtensionsCache.getOrCreate(t, () => { + let r = Te(t); + return !this.extension.model || !(this.extension.model[r] || this.extension.model.$allModels) ? this.previous?.getAllModelExtensions(t) : { ...this.previous?.getAllModelExtensions(t), ...this.extension.model.$allModels, ...this.extension.model[r] }; + }); + } + getAllQueryCallbacks(t, r) { + return this.queryCallbacksCache.getOrCreate(`${t}:${r}`, () => { + let n = this.previous?.getAllQueryCallbacks(t, r) ?? [], i = [], o = this.extension.query; + return !o || !(o[t] || o.$allModels || o[r] || o.$allOperations) ? n : (o[t] !== void 0 && (o[t][r] !== void 0 && i.push(o[t][r]), o[t].$allOperations !== void 0 && i.push(o[t].$allOperations)), t !== "$none" && o.$allModels !== void 0 && (o.$allModels[r] !== void 0 && i.push(o.$allModels[r]), o.$allModels.$allOperations !== void 0 && i.push(o.$allModels.$allOperations)), o[r] !== void 0 && i.push(o[r]), o.$allOperations !== void 0 && i.push(o.$allOperations), n.concat(i)); + }); + } + getAllBatchQueryCallbacks() { + return this.batchCallbacks.get(); + } + }; + var kt = class e { + constructor(t) { + this.head = t; + } + static empty() { + return new e(); + } + static single(t) { + return new e(new xn(t)); + } + isEmpty() { + return this.head === void 0; + } + append(t) { + return new e(new xn(t, this.head)); + } + getAllComputedFields(t) { + return this.head?.getAllComputedFields(t); + } + getAllClientExtensions() { + return this.head?.getAllClientExtensions(); + } + getAllModelExtensions(t) { + return this.head?.getAllModelExtensions(t); + } + getAllQueryCallbacks(t, r) { + return this.head?.getAllQueryCallbacks(t, r) ?? []; + } + getAllBatchQueryCallbacks() { + return this.head?.getAllBatchQueryCallbacks() ?? []; + } + }; + var ia = Symbol(); + var dr = class { + constructor(t) { + if (t !== ia) throw new Error("Skip instance can not be constructed directly"); + } + ifUndefined(t) { + return t === void 0 ? Pn : t; + } + }; + var Pn = new dr(ia); + function Re(e) { + return e instanceof dr; + } + var Xp = { findUnique: "findUnique", findUniqueOrThrow: "findUniqueOrThrow", findFirst: "findFirst", findFirstOrThrow: "findFirstOrThrow", findMany: "findMany", count: "aggregate", create: "createOne", createMany: "createMany", createManyAndReturn: "createManyAndReturn", update: "updateOne", updateMany: "updateMany", upsert: "upsertOne", delete: "deleteOne", deleteMany: "deleteMany", executeRaw: "executeRaw", queryRaw: "queryRaw", aggregate: "aggregate", groupBy: "groupBy", runCommandRaw: "runCommandRaw", findRaw: "findRaw", aggregateRaw: "aggregateRaw" }; + var oa = "explicitly `undefined` values are not allowed"; + function vn({ modelName: e, action: t, args: r, runtimeDataModel: n, extensions: i = kt.empty(), callsite: o, clientMethod: s, errorFormat: a, clientVersion: l, previewFeatures: u, globalOmit: c }) { + let p = new Di({ runtimeDataModel: n, modelName: e, action: t, rootArgs: r, callsite: o, extensions: i, selectionPath: [], argumentPath: [], originalMethod: s, errorFormat: a, clientVersion: l, previewFeatures: u, globalOmit: c }); + return { modelName: e, action: Xp[t], query: mr(r, p) }; + } + function mr({ select: e, include: t, ...r } = {}, n) { + let i; + return n.isPreviewFeatureOn("omitApi") && (i = r.omit, delete r.omit), { arguments: aa(r, n), selection: ed(e, t, i, n) }; + } + function ed(e, t, r, n) { + return e ? (t ? n.throwValidationError({ kind: "MutuallyExclusiveFields", firstField: "include", secondField: "select", selectionPath: n.getSelectionPath() }) : r && n.isPreviewFeatureOn("omitApi") && n.throwValidationError({ kind: "MutuallyExclusiveFields", firstField: "omit", secondField: "select", selectionPath: n.getSelectionPath() }), id(e, n)) : td(n, t, r); + } + function td(e, t, r) { + let n = {}; + return e.modelOrType && !e.isRawAction() && (n.$composites = true, n.$scalars = true), t && rd(n, t, e), e.isPreviewFeatureOn("omitApi") && nd(n, r, e), n; + } + function rd(e, t, r) { + for (let [n, i] of Object.entries(t)) { + if (Re(i)) continue; + let o = r.nestSelection(n); + if (_i(i, o), i === false || i === void 0) { + e[n] = false; + continue; + } + let s = r.findField(n); + if (s && s.kind !== "object" && r.throwValidationError({ kind: "IncludeOnScalar", selectionPath: r.getSelectionPath().concat(n), outputType: r.getOutputTypeDescription() }), s) { + e[n] = mr(i === true ? {} : i, o); + continue; + } + if (i === true) { + e[n] = true; + continue; + } + e[n] = mr(i, o); + } + } + function nd(e, t, r) { + let n = r.getComputedFields(), i = { ...r.getGlobalOmit(), ...t }, o = na(i, n); + for (let [s, a] of Object.entries(o)) { + if (Re(a)) continue; + _i(a, r.nestSelection(s)); + let l = r.findField(s); + n?.[s] && !l || (e[s] = !a); + } + } + function id(e, t) { + let r = {}, n = t.getComputedFields(), i = ra(e, n); + for (let [o, s] of Object.entries(i)) { + if (Re(s)) continue; + let a = t.nestSelection(o); + _i(s, a); + let l = t.findField(o); + if (!(n?.[o] && !l)) { + if (s === false || s === void 0 || Re(s)) { + r[o] = false; + continue; + } + if (s === true) { + l?.kind === "object" ? r[o] = mr({}, a) : r[o] = true; + continue; + } + r[o] = mr(s, a); + } + } + return r; + } + function sa(e, t) { + if (e === null) return null; + if (typeof e == "string" || typeof e == "number" || typeof e == "boolean") return e; + if (typeof e == "bigint") return { $type: "BigInt", value: String(e) }; + if (Pt(e)) { + if (ln(e)) return { $type: "DateTime", value: e.toISOString() }; + t.throwValidationError({ kind: "InvalidArgumentValue", selectionPath: t.getSelectionPath(), argumentPath: t.getArgumentPath(), argument: { name: t.getArgumentName(), typeNames: ["Date"] }, underlyingError: "Provided Date object is invalid" }); + } + if (It(e)) return { $type: "FieldRef", value: { _ref: e.name, _container: e.modelName } }; + if (Array.isArray(e)) return od(e, t); + if (ArrayBuffer.isView(e)) return { $type: "Bytes", value: Buffer.from(e).toString("base64") }; + if (sd(e)) return e.values; + if (vt(e)) return { $type: "Decimal", value: e.toFixed() }; + if (e instanceof Me) { + if (e !== yn.instances[e._getName()]) throw new Error("Invalid ObjectEnumValue"); + return { $type: "Enum", value: e._getName() }; + } + if (ad(e)) return e.toJSON(); + if (typeof e == "object") return aa(e, t); + t.throwValidationError({ kind: "InvalidArgumentValue", selectionPath: t.getSelectionPath(), argumentPath: t.getArgumentPath(), argument: { name: t.getArgumentName(), typeNames: [] }, underlyingError: `We could not serialize ${Object.prototype.toString.call(e)} value. Serialize the object to JSON or implement a ".toJSON()" method on it` }); + } + function aa(e, t) { + if (e.$type) return { $type: "Raw", value: e }; + let r = {}; + for (let n in e) { + let i = e[n], o = t.nestArgument(n); + Re(i) || (i !== void 0 ? r[n] = sa(i, o) : t.isPreviewFeatureOn("strictUndefinedChecks") && t.throwValidationError({ kind: "InvalidArgumentValue", argumentPath: o.getArgumentPath(), selectionPath: t.getSelectionPath(), argument: { name: t.getArgumentName(), typeNames: [] }, underlyingError: oa })); + } + return r; + } + function od(e, t) { + let r = []; + for (let n = 0; n < e.length; n++) { + let i = t.nestArgument(String(n)), o = e[n]; + if (o === void 0 || Re(o)) { + let s = o === void 0 ? "undefined" : "Prisma.skip"; + t.throwValidationError({ kind: "InvalidArgumentValue", selectionPath: i.getSelectionPath(), argumentPath: i.getArgumentPath(), argument: { name: `${t.getArgumentName()}[${n}]`, typeNames: [] }, underlyingError: `Can not use \`${s}\` value within array. Use \`null\` or filter out \`${s}\` values` }); + } + r.push(sa(o, i)); + } + return r; + } + function sd(e) { + return typeof e == "object" && e !== null && e.__prismaRawParameters__ === true; + } + function ad(e) { + return typeof e == "object" && e !== null && typeof e.toJSON == "function"; + } + function _i(e, t) { + e === void 0 && t.isPreviewFeatureOn("strictUndefinedChecks") && t.throwValidationError({ kind: "InvalidSelectionValue", selectionPath: t.getSelectionPath(), underlyingError: oa }); + } + var Di = class e { + constructor(t) { + this.params = t; + this.params.modelName && (this.modelOrType = this.params.runtimeDataModel.models[this.params.modelName] ?? this.params.runtimeDataModel.types[this.params.modelName]); + } + throwValidationError(t) { + wn({ errors: [t], originalMethod: this.params.originalMethod, args: this.params.rootArgs ?? {}, callsite: this.params.callsite, errorFormat: this.params.errorFormat, clientVersion: this.params.clientVersion, globalOmit: this.params.globalOmit }); + } + getSelectionPath() { + return this.params.selectionPath; + } + getArgumentPath() { + return this.params.argumentPath; + } + getArgumentName() { + return this.params.argumentPath[this.params.argumentPath.length - 1]; + } + getOutputTypeDescription() { + if (!(!this.params.modelName || !this.modelOrType)) return { name: this.params.modelName, fields: this.modelOrType.fields.map((t) => ({ name: t.name, typeName: "boolean", isRelation: t.kind === "object" })) }; + } + isRawAction() { + return ["executeRaw", "queryRaw", "runCommandRaw", "findRaw", "aggregateRaw"].includes(this.params.action); + } + isPreviewFeatureOn(t) { + return this.params.previewFeatures.includes(t); + } + getComputedFields() { + if (this.params.modelName) return this.params.extensions.getAllComputedFields(this.params.modelName); + } + findField(t) { + return this.modelOrType?.fields.find((r) => r.name === t); + } + nestSelection(t) { + let r = this.findField(t), n = r?.kind === "object" ? r.type : void 0; + return new e({ ...this.params, modelName: n, selectionPath: this.params.selectionPath.concat(t) }); + } + getGlobalOmit() { + return this.params.modelName && this.shouldApplyGlobalOmit() ? this.params.globalOmit?.[xt(this.params.modelName)] ?? {} : {}; + } + shouldApplyGlobalOmit() { + switch (this.params.action) { + case "findFirst": + case "findFirstOrThrow": + case "findUniqueOrThrow": + case "findMany": + case "upsert": + case "findUnique": + case "createManyAndReturn": + case "create": + case "update": + case "delete": + return true; + case "executeRaw": + case "aggregateRaw": + case "runCommandRaw": + case "findRaw": + case "createMany": + case "deleteMany": + case "groupBy": + case "updateMany": + case "count": + case "aggregate": + case "queryRaw": + return false; + default: + Fe(this.params.action, "Unknown action"); + } + } + nestArgument(t) { + return new e({ ...this.params, argumentPath: this.params.argumentPath.concat(t) }); + } + }; + var Dt = class { + constructor(t) { + this._engine = t; + } + prometheus(t) { + return this._engine.metrics({ format: "prometheus", ...t }); + } + json(t) { + return this._engine.metrics({ format: "json", ...t }); + } + }; + function la(e) { + return { models: Fi(e.models), enums: Fi(e.enums), types: Fi(e.types) }; + } + function Fi(e) { + let t = {}; + for (let { name: r, ...n } of e) t[r] = n; + return t; + } + function ua(e, t) { + let r = pr(() => ld(t)); + Object.defineProperty(e, "dmmf", { get: () => r.get() }); + } + function ld(e) { + return { datamodel: { models: Li(e.models), enums: Li(e.enums), types: Li(e.types) } }; + } + function Li(e) { + return Object.entries(e).map(([t, r]) => ({ name: t, ...r })); + } + var Ni = /* @__PURE__ */ new WeakMap(); + var Tn = "$$PrismaTypedSql"; + var Mi = class { + constructor(t, r) { + Ni.set(this, { sql: t, values: r }), Object.defineProperty(this, Tn, { value: Tn }); + } + get sql() { + return Ni.get(this).sql; + } + get values() { + return Ni.get(this).values; + } + }; + function ca(e) { + return (...t) => new Mi(e, t); + } + function pa(e) { + return e != null && e[Tn] === Tn; + } + function fr(e) { + return { ok: false, error: e, map() { + return fr(e); + }, flatMap() { + return fr(e); + } }; + } + var $i = class { + constructor() { + this.registeredErrors = []; + } + consumeError(t) { + return this.registeredErrors[t]; + } + registerNewError(t) { + let r = 0; + for (; this.registeredErrors[r] !== void 0; ) r++; + return this.registeredErrors[r] = { error: t }, r; + } + }; + var qi = (e) => { + let t = new $i(), r = Ce(t, e.transactionContext.bind(e)), n = { adapterName: e.adapterName, errorRegistry: t, queryRaw: Ce(t, e.queryRaw.bind(e)), executeRaw: Ce(t, e.executeRaw.bind(e)), provider: e.provider, transactionContext: async (...i) => (await r(...i)).map((s) => ud(t, s)) }; + return e.getConnectionInfo && (n.getConnectionInfo = pd(t, e.getConnectionInfo.bind(e))), n; + }; + var ud = (e, t) => { + let r = Ce(e, t.startTransaction.bind(t)); + return { adapterName: t.adapterName, provider: t.provider, queryRaw: Ce(e, t.queryRaw.bind(t)), executeRaw: Ce(e, t.executeRaw.bind(t)), startTransaction: async (...n) => (await r(...n)).map((o) => cd(e, o)) }; + }; + var cd = (e, t) => ({ adapterName: t.adapterName, provider: t.provider, options: t.options, queryRaw: Ce(e, t.queryRaw.bind(t)), executeRaw: Ce(e, t.executeRaw.bind(t)), commit: Ce(e, t.commit.bind(t)), rollback: Ce(e, t.rollback.bind(t)) }); + function Ce(e, t) { + return async (...r) => { + try { + return await t(...r); + } catch (n) { + let i = e.registerNewError(n); + return fr({ kind: "GenericJs", id: i }); + } + }; + } + function pd(e, t) { + return (...r) => { + try { + return t(...r); + } catch (n) { + let i = e.registerNewError(n); + return fr({ kind: "GenericJs", id: i }); + } + }; + } + var Wl = k(oi()); + var Hl = __require("async_hooks"); + var Kl = __require("events"); + var zl = k(__require("fs")); + var Fr = k(__require("path")); + var oe = class e { + constructor(t, r) { + if (t.length - 1 !== r.length) throw t.length === 0 ? new TypeError("Expected at least 1 string") : new TypeError(`Expected ${t.length} strings to have ${t.length - 1} values`); + let n = r.reduce((s, a) => s + (a instanceof e ? a.values.length : 1), 0); + this.values = new Array(n), this.strings = new Array(n + 1), this.strings[0] = t[0]; + let i = 0, o = 0; + for (; i < r.length; ) { + let s = r[i++], a = t[i]; + if (s instanceof e) { + this.strings[o] += s.strings[0]; + let l = 0; + for (; l < s.values.length; ) this.values[o++] = s.values[l++], this.strings[o] = s.strings[l]; + this.strings[o] += a; + } else this.values[o++] = s, this.strings[o] = a; + } + } + get sql() { + let t = this.strings.length, r = 1, n = this.strings[0]; + for (; r < t; ) n += `?${this.strings[r++]}`; + return n; + } + get statement() { + let t = this.strings.length, r = 1, n = this.strings[0]; + for (; r < t; ) n += `:${r}${this.strings[r++]}`; + return n; + } + get text() { + let t = this.strings.length, r = 1, n = this.strings[0]; + for (; r < t; ) n += `$${r}${this.strings[r++]}`; + return n; + } + inspect() { + return { sql: this.sql, statement: this.statement, text: this.text, values: this.values }; + } + }; + function da(e, t = ",", r = "", n = "") { + if (e.length === 0) throw new TypeError("Expected `join([])` to be called with an array of multiple elements, but got an empty array"); + return new oe([r, ...Array(e.length - 1).fill(t), n], e); + } + function ji(e) { + return new oe([e], []); + } + var ma = ji(""); + function Vi(e, ...t) { + return new oe(e, t); + } + function gr(e) { + return { getKeys() { + return Object.keys(e); + }, getPropertyValue(t) { + return e[t]; + } }; + } + function re(e, t) { + return { getKeys() { + return [e]; + }, getPropertyValue() { + return t(); + } }; + } + function ot(e) { + let t = new ve(); + return { getKeys() { + return e.getKeys(); + }, getPropertyValue(r) { + return t.getOrCreate(r, () => e.getPropertyValue(r)); + }, getPropertyDescriptor(r) { + return e.getPropertyDescriptor?.(r); + } }; + } + var Rn = { enumerable: true, configurable: true, writable: true }; + function Cn(e) { + let t = new Set(e); + return { getOwnPropertyDescriptor: () => Rn, has: (r, n) => t.has(n), set: (r, n, i) => t.add(n) && Reflect.set(r, n, i), ownKeys: () => [...t] }; + } + var fa = Symbol.for("nodejs.util.inspect.custom"); + function Se(e, t) { + let r = dd(t), n = /* @__PURE__ */ new Set(), i = new Proxy(e, { get(o, s) { + if (n.has(s)) return o[s]; + let a = r.get(s); + return a ? a.getPropertyValue(s) : o[s]; + }, has(o, s) { + if (n.has(s)) return true; + let a = r.get(s); + return a ? a.has?.(s) ?? true : Reflect.has(o, s); + }, ownKeys(o) { + let s = ga(Reflect.ownKeys(o), r), a = ga(Array.from(r.keys()), r); + return [.../* @__PURE__ */ new Set([...s, ...a, ...n])]; + }, set(o, s, a) { + return r.get(s)?.getPropertyDescriptor?.(s)?.writable === false ? false : (n.add(s), Reflect.set(o, s, a)); + }, getOwnPropertyDescriptor(o, s) { + let a = Reflect.getOwnPropertyDescriptor(o, s); + if (a && !a.configurable) return a; + let l = r.get(s); + return l ? l.getPropertyDescriptor ? { ...Rn, ...l?.getPropertyDescriptor(s) } : Rn : a; + }, defineProperty(o, s, a) { + return n.add(s), Reflect.defineProperty(o, s, a); + } }); + return i[fa] = function() { + let o = { ...this }; + return delete o[fa], o; + }, i; + } + function dd(e) { + let t = /* @__PURE__ */ new Map(); + for (let r of e) { + let n = r.getKeys(); + for (let i of n) t.set(i, r); + } + return t; + } + function ga(e, t) { + return e.filter((r) => t.get(r)?.has?.(r) ?? true); + } + function _t(e) { + return { getKeys() { + return e; + }, has() { + return false; + }, getPropertyValue() { + } }; + } + function Ft(e, t) { + return { batch: e, transaction: t?.kind === "batch" ? { isolationLevel: t.options.isolationLevel } : void 0 }; + } + function ha(e) { + if (e === void 0) return ""; + let t = Ot(e); + return new Rt(0, { colors: fn }).write(t).toString(); + } + var md = "P2037"; + function st({ error: e, user_facing_error: t }, r, n) { + return t.error_code ? new V(fd(t, n), { code: t.error_code, clientVersion: r, meta: t.meta, batchRequestIdx: t.batch_request_idx }) : new B(e, { clientVersion: r, batchRequestIdx: t.batch_request_idx }); + } + function fd(e, t) { + let r = e.message; + return (t === "postgresql" || t === "postgres" || t === "mysql") && e.error_code === md && (r += ` +Prisma Accelerate has built-in connection pooling to prevent such errors: https://pris.ly/client/error-accelerate`), r; + } + var hr = ""; + function ya(e) { + var t = e.split(` +`); + return t.reduce(function(r, n) { + var i = yd(n) || Ed(n) || Pd(n) || Cd(n) || Td(n); + return i && r.push(i), r; + }, []); + } + var gd = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack||\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; + var hd = /\((\S*)(?::(\d+))(?::(\d+))\)/; + function yd(e) { + var t = gd.exec(e); + if (!t) return null; + var r = t[2] && t[2].indexOf("native") === 0, n = t[2] && t[2].indexOf("eval") === 0, i = hd.exec(t[2]); + return n && i != null && (t[2] = i[1], t[3] = i[2], t[4] = i[3]), { file: r ? null : t[2], methodName: t[1] || hr, arguments: r ? [t[2]] : [], lineNumber: t[3] ? +t[3] : null, column: t[4] ? +t[4] : null }; + } + var bd = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i; + function Ed(e) { + var t = bd.exec(e); + return t ? { file: t[2], methodName: t[1] || hr, arguments: [], lineNumber: +t[3], column: t[4] ? +t[4] : null } : null; + } + var wd = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i; + var xd = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; + function Pd(e) { + var t = wd.exec(e); + if (!t) return null; + var r = t[3] && t[3].indexOf(" > eval") > -1, n = xd.exec(t[3]); + return r && n != null && (t[3] = n[1], t[4] = n[2], t[5] = null), { file: t[3], methodName: t[1] || hr, arguments: t[2] ? t[2].split(",") : [], lineNumber: t[4] ? +t[4] : null, column: t[5] ? +t[5] : null }; + } + var vd = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i; + function Td(e) { + var t = vd.exec(e); + return t ? { file: t[3], methodName: t[1] || hr, arguments: [], lineNumber: +t[4], column: t[5] ? +t[5] : null } : null; + } + var Rd = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i; + function Cd(e) { + var t = Rd.exec(e); + return t ? { file: t[2], methodName: t[1] || hr, arguments: [], lineNumber: +t[3], column: t[4] ? +t[4] : null } : null; + } + var Bi = class { + getLocation() { + return null; + } + }; + var Ui = class { + constructor() { + this._error = new Error(); + } + getLocation() { + let t = this._error.stack; + if (!t) return null; + let n = ya(t).find((i) => { + if (!i.file) return false; + let o = mi(i.file); + return o !== "" && !o.includes("@prisma") && !o.includes("/packages/client/src/runtime/") && !o.endsWith("/runtime/binary.js") && !o.endsWith("/runtime/library.js") && !o.endsWith("/runtime/edge.js") && !o.endsWith("/runtime/edge-esm.js") && !o.startsWith("internal/") && !i.methodName.includes("new ") && !i.methodName.includes("getCallSite") && !i.methodName.includes("Proxy.") && i.methodName.split(".").length < 4; + }); + return !n || !n.file ? null : { fileName: n.file, lineNumber: n.lineNumber, columnNumber: n.column }; + } + }; + function Ze(e) { + return e === "minimal" ? typeof $EnabledCallSite == "function" && e !== "minimal" ? new $EnabledCallSite() : new Bi() : new Ui(); + } + var ba = { _avg: true, _count: true, _sum: true, _min: true, _max: true }; + function Lt(e = {}) { + let t = Ad(e); + return Object.entries(t).reduce((n, [i, o]) => (ba[i] !== void 0 ? n.select[i] = { select: o } : n[i] = o, n), { select: {} }); + } + function Ad(e = {}) { + return typeof e._count == "boolean" ? { ...e, _count: { _all: e._count } } : e; + } + function Sn(e = {}) { + return (t) => (typeof e._count == "boolean" && (t._count = t._count._all), t); + } + function Ea(e, t) { + let r = Sn(e); + return t({ action: "aggregate", unpacker: r, argsMapper: Lt })(e); + } + function Id(e = {}) { + let { select: t, ...r } = e; + return typeof t == "object" ? Lt({ ...r, _count: t }) : Lt({ ...r, _count: { _all: true } }); + } + function Od(e = {}) { + return typeof e.select == "object" ? (t) => Sn(e)(t)._count : (t) => Sn(e)(t)._count._all; + } + function wa(e, t) { + return t({ action: "count", unpacker: Od(e), argsMapper: Id })(e); + } + function kd(e = {}) { + let t = Lt(e); + if (Array.isArray(t.by)) for (let r of t.by) typeof r == "string" && (t.select[r] = true); + else typeof t.by == "string" && (t.select[t.by] = true); + return t; + } + function Dd(e = {}) { + return (t) => (typeof e?._count == "boolean" && t.forEach((r) => { + r._count = r._count._all; + }), t); + } + function xa(e, t) { + return t({ action: "groupBy", unpacker: Dd(e), argsMapper: kd })(e); + } + function Pa(e, t, r) { + if (t === "aggregate") return (n) => Ea(n, r); + if (t === "count") return (n) => wa(n, r); + if (t === "groupBy") return (n) => xa(n, r); + } + function va(e, t) { + let r = t.fields.filter((i) => !i.relationName), n = wi(r, (i) => i.name); + return new Proxy({}, { get(i, o) { + if (o in i || typeof o == "symbol") return i[o]; + let s = n[o]; + if (s) return new sr(e, o, s.type, s.isList, s.kind === "enum"); + }, ...Cn(Object.keys(n)) }); + } + var Ta = (e) => Array.isArray(e) ? e : e.split("."); + var Gi = (e, t) => Ta(t).reduce((r, n) => r && r[n], e); + var Ra = (e, t, r) => Ta(t).reduceRight((n, i, o, s) => Object.assign({}, Gi(e, s.slice(0, o)), { [i]: n }), r); + function _d(e, t) { + return e === void 0 || t === void 0 ? [] : [...t, "select", e]; + } + function Fd(e, t, r) { + return t === void 0 ? e ?? {} : Ra(t, r, e || true); + } + function Qi(e, t, r, n, i, o) { + let a = e._runtimeDataModel.models[t].fields.reduce((l, u) => ({ ...l, [u.name]: u }), {}); + return (l) => { + let u = Ze(e._errorFormat), c = _d(n, i), p = Fd(l, o, c), d = r({ dataPath: c, callsite: u })(p), f = Ld(e, t); + return new Proxy(d, { get(g, h) { + if (!f.includes(h)) return g[h]; + let T = [a[h].type, r, h], S = [c, p]; + return Qi(e, ...T, ...S); + }, ...Cn([...f, ...Object.getOwnPropertyNames(d)]) }); + }; + } + function Ld(e, t) { + return e._runtimeDataModel.models[t].fields.filter((r) => r.kind === "object").map((r) => r.name); + } + function Ca(e, t, r, n) { + return e === Je.ModelAction.findFirstOrThrow || e === Je.ModelAction.findUniqueOrThrow ? Nd(t, r, n) : n; + } + function Nd(e, t, r) { + return async (n) => { + if ("rejectOnNotFound" in n.args) { + let o = Tt({ originalMethod: n.clientMethod, callsite: n.callsite, message: "'rejectOnNotFound' option is not supported" }); + throw new J(o, { clientVersion: t }); + } + return await r(n).catch((o) => { + throw o instanceof V && o.code === "P2025" ? new Le(`No ${e} found`, t) : o; + }); + }; + } + var Md = ["findUnique", "findUniqueOrThrow", "findFirst", "findFirstOrThrow", "create", "update", "upsert", "delete"]; + var $d = ["aggregate", "count", "groupBy"]; + function Ji(e, t) { + let r = e._extensions.getAllModelExtensions(t) ?? {}, n = [qd(e, t), Vd(e, t), gr(r), re("name", () => t), re("$name", () => t), re("$parent", () => e._appliedParent)]; + return Se({}, n); + } + function qd(e, t) { + let r = Te(t), n = Object.keys(Je.ModelAction).concat("count"); + return { getKeys() { + return n; + }, getPropertyValue(i) { + let o = i, s = (l) => e._request(l); + s = Ca(o, t, e._clientVersion, s); + let a = (l) => (u) => { + let c = Ze(e._errorFormat); + return e._createPrismaPromise((p) => { + let d = { args: u, dataPath: [], action: o, model: t, clientMethod: `${r}.${i}`, jsModelName: r, transaction: p, callsite: c }; + return s({ ...d, ...l }); + }); + }; + return Md.includes(o) ? Qi(e, t, a) : jd(i) ? Pa(e, i, a) : a({}); + } }; + } + function jd(e) { + return $d.includes(e); + } + function Vd(e, t) { + return ot(re("fields", () => { + let r = e._runtimeDataModel.models[t]; + return va(t, r); + })); + } + function Sa(e) { + return e.replace(/^./, (t) => t.toUpperCase()); + } + var Wi = Symbol(); + function yr(e) { + let t = [Bd(e), re(Wi, () => e), re("$parent", () => e._appliedParent)], r = e._extensions.getAllClientExtensions(); + return r && t.push(gr(r)), Se(e, t); + } + function Bd(e) { + let t = Object.keys(e._runtimeDataModel.models), r = t.map(Te), n = [...new Set(t.concat(r))]; + return ot({ getKeys() { + return n; + }, getPropertyValue(i) { + let o = Sa(i); + if (e._runtimeDataModel.models[o] !== void 0) return Ji(e, o); + if (e._runtimeDataModel.models[i] !== void 0) return Ji(e, i); + }, getPropertyDescriptor(i) { + if (!r.includes(i)) return { enumerable: false }; + } }); + } + function Aa(e) { + return e[Wi] ? e[Wi] : e; + } + function Ia(e) { + if (typeof e == "function") return e(this); + if (e.client?.__AccelerateEngine) { + let r = e.client.__AccelerateEngine; + this._originalClient._engine = new r(this._originalClient._accelerateEngineConfig); + } + let t = Object.create(this._originalClient, { _extensions: { value: this._extensions.append(e) }, _appliedParent: { value: this, configurable: true }, $use: { value: void 0 }, $on: { value: void 0 } }); + return yr(t); + } + function Oa({ result: e, modelName: t, select: r, omit: n, extensions: i }) { + let o = i.getAllComputedFields(t); + if (!o) return e; + let s = [], a = []; + for (let l of Object.values(o)) { + if (n) { + if (n[l.name]) continue; + let u = l.needs.filter((c) => n[c]); + u.length > 0 && a.push(_t(u)); + } else if (r) { + if (!r[l.name]) continue; + let u = l.needs.filter((c) => !r[c]); + u.length > 0 && a.push(_t(u)); + } + Ud(e, l.needs) && s.push(Gd(l, Se(e, s))); + } + return s.length > 0 || a.length > 0 ? Se(e, [...s, ...a]) : e; + } + function Ud(e, t) { + return t.every((r) => Ei(e, r)); + } + function Gd(e, t) { + return ot(re(e.name, () => e.compute(t))); + } + function An({ visitor: e, result: t, args: r, runtimeDataModel: n, modelName: i }) { + if (Array.isArray(t)) { + for (let s = 0; s < t.length; s++) t[s] = An({ result: t[s], args: r, modelName: i, runtimeDataModel: n, visitor: e }); + return t; + } + let o = e(t, i, r) ?? t; + return r.include && ka({ includeOrSelect: r.include, result: o, parentModelName: i, runtimeDataModel: n, visitor: e }), r.select && ka({ includeOrSelect: r.select, result: o, parentModelName: i, runtimeDataModel: n, visitor: e }), o; + } + function ka({ includeOrSelect: e, result: t, parentModelName: r, runtimeDataModel: n, visitor: i }) { + for (let [o, s] of Object.entries(e)) { + if (!s || t[o] == null || Re(s)) continue; + let l = n.models[r].fields.find((c) => c.name === o); + if (!l || l.kind !== "object" || !l.relationName) continue; + let u = typeof s == "object" ? s : {}; + t[o] = An({ visitor: i, result: t[o], args: u, modelName: l.type, runtimeDataModel: n }); + } + } + function Da({ result: e, modelName: t, args: r, extensions: n, runtimeDataModel: i, globalOmit: o }) { + return n.isEmpty() || e == null || typeof e != "object" || !i.models[t] ? e : An({ result: e, args: r ?? {}, modelName: t, runtimeDataModel: i, visitor: (a, l, u) => { + let c = Te(l); + return Oa({ result: a, modelName: c, select: u.select, omit: u.select ? void 0 : { ...o?.[c], ...u.omit }, extensions: n }); + } }); + } + function _a(e) { + if (e instanceof oe) return Qd(e); + if (Array.isArray(e)) { + let r = [e[0]]; + for (let n = 1; n < e.length; n++) r[n] = br(e[n]); + return r; + } + let t = {}; + for (let r in e) t[r] = br(e[r]); + return t; + } + function Qd(e) { + return new oe(e.strings, e.values); + } + function br(e) { + if (typeof e != "object" || e == null || e instanceof Me || It(e)) return e; + if (vt(e)) return new xe(e.toFixed()); + if (Pt(e)) return /* @__PURE__ */ new Date(+e); + if (ArrayBuffer.isView(e)) return e.slice(0); + if (Array.isArray(e)) { + let t = e.length, r; + for (r = Array(t); t--; ) r[t] = br(e[t]); + return r; + } + if (typeof e == "object") { + let t = {}; + for (let r in e) r === "__proto__" ? Object.defineProperty(t, r, { value: br(e[r]), configurable: true, enumerable: true, writable: true }) : t[r] = br(e[r]); + return t; + } + Fe(e, "Unknown value"); + } + function La(e, t, r, n = 0) { + return e._createPrismaPromise((i) => { + let o = t.customDataProxyFetch; + return "transaction" in t && i !== void 0 && (t.transaction?.kind === "batch" && t.transaction.lock.then(), t.transaction = i), n === r.length ? e._executeRequest(t) : r[n]({ model: t.model, operation: t.model ? t.action : t.clientMethod, args: _a(t.args ?? {}), __internalParams: t, query: (s, a = t) => { + let l = a.customDataProxyFetch; + return a.customDataProxyFetch = qa(o, l), a.args = s, La(e, a, r, n + 1); + } }); + }); + } + function Na(e, t) { + let { jsModelName: r, action: n, clientMethod: i } = t, o = r ? n : i; + if (e._extensions.isEmpty()) return e._executeRequest(t); + let s = e._extensions.getAllQueryCallbacks(r ?? "$none", o); + return La(e, t, s); + } + function Ma(e) { + return (t) => { + let r = { requests: t }, n = t[0].extensions.getAllBatchQueryCallbacks(); + return n.length ? $a(r, n, 0, e) : e(r); + }; + } + function $a(e, t, r, n) { + if (r === t.length) return n(e); + let i = e.customDataProxyFetch, o = e.requests[0].transaction; + return t[r]({ args: { queries: e.requests.map((s) => ({ model: s.modelName, operation: s.action, args: s.args })), transaction: o ? { isolationLevel: o.kind === "batch" ? o.isolationLevel : void 0 } : void 0 }, __internalParams: e, query(s, a = e) { + let l = a.customDataProxyFetch; + return a.customDataProxyFetch = qa(i, l), $a(a, t, r + 1, n); + } }); + } + var Fa = (e) => e; + function qa(e = Fa, t = Fa) { + return (r) => e(t(r)); + } + var ja = L("prisma:client"); + var Va = { Vercel: "vercel", "Netlify CI": "netlify" }; + function Ba({ postinstall: e, ciName: t, clientVersion: r }) { + if (ja("checkPlatformCaching:postinstall", e), ja("checkPlatformCaching:ciName", t), e === true && t && t in Va) { + let n = `Prisma has detected that this project was built on ${t}, which caches dependencies. This leads to an outdated Prisma Client because Prisma's auto-generation isn't triggered. To fix this, make sure to run the \`prisma generate\` command during the build process. + +Learn how: https://pris.ly/d/${Va[t]}-build`; + throw console.error(n), new R(n, r); + } + } + function Ua(e, t) { + return e ? e.datasources ? e.datasources : e.datasourceUrl ? { [t[0]]: { url: e.datasourceUrl } } : {} : {}; + } + var Jd = "Cloudflare-Workers"; + var Wd = "node"; + function Ga() { + return typeof Netlify == "object" ? "netlify" : typeof EdgeRuntime == "string" ? "edge-light" : globalThis.navigator?.userAgent === Jd ? "workerd" : globalThis.Deno ? "deno" : globalThis.__lagon__ ? "lagon" : globalThis.process?.release?.name === Wd ? "node" : globalThis.Bun ? "bun" : globalThis.fastly ? "fastly" : "unknown"; + } + var Hd = { node: "Node.js", workerd: "Cloudflare Workers", deno: "Deno and Deno Deploy", netlify: "Netlify Edge Functions", "edge-light": "Edge Runtime (Vercel Edge Functions, Vercel Edge Middleware, Next.js (Pages Router) Edge API Routes, Next.js (App Router) Edge Route Handlers or Next.js Middleware)" }; + function In() { + let e = Ga(); + return { id: e, prettyName: Hd[e] || e, isEdge: ["workerd", "deno", "netlify", "edge-light"].includes(e) }; + } + var Ka = k(__require("fs")); + var Er = k(__require("path")); + function On(e) { + let { runtimeBinaryTarget: t } = e; + return `Add "${t}" to \`binaryTargets\` in the "schema.prisma" file and run \`prisma generate\` after saving it: + +${Kd(e)}`; + } + function Kd(e) { + let { generator: t, generatorBinaryTargets: r, runtimeBinaryTarget: n } = e, i = { fromEnvVar: null, value: n }, o = [...r, i]; + return hi({ ...t, binaryTargets: o }); + } + function Xe(e) { + let { runtimeBinaryTarget: t } = e; + return `Prisma Client could not locate the Query Engine for runtime "${t}".`; + } + function et(e) { + let { searchedLocations: t } = e; + return `The following locations have been searched: +${[...new Set(t)].map((i) => ` ${i}`).join(` +`)}`; + } + function Qa(e) { + let { runtimeBinaryTarget: t } = e; + return `${Xe(e)} + +This happened because \`binaryTargets\` have been pinned, but the actual deployment also required "${t}". +${On(e)} + +${et(e)}`; + } + function kn(e) { + return `We would appreciate if you could take the time to share some information with us. +Please help us by answering a few questions: https://pris.ly/${e}`; + } + function Dn(e) { + let { errorStack: t } = e; + return t?.match(/\/\.next|\/next@|\/next\//) ? ` + +We detected that you are using Next.js, learn how to fix this: https://pris.ly/d/engine-not-found-nextjs.` : ""; + } + function Ja(e) { + let { queryEngineName: t } = e; + return `${Xe(e)}${Dn(e)} + +This is likely caused by a bundler that has not copied "${t}" next to the resulting bundle. +Ensure that "${t}" has been copied next to the bundle or in "${e.expectedLocation}". + +${kn("engine-not-found-bundler-investigation")} + +${et(e)}`; + } + function Wa(e) { + let { runtimeBinaryTarget: t, generatorBinaryTargets: r } = e, n = r.find((i) => i.native); + return `${Xe(e)} + +This happened because Prisma Client was generated for "${n?.value ?? "unknown"}", but the actual deployment required "${t}". +${On(e)} + +${et(e)}`; + } + function Ha(e) { + let { queryEngineName: t } = e; + return `${Xe(e)}${Dn(e)} + +This is likely caused by tooling that has not copied "${t}" to the deployment folder. +Ensure that you ran \`prisma generate\` and that "${t}" has been copied to "${e.expectedLocation}". + +${kn("engine-not-found-tooling-investigation")} + +${et(e)}`; + } + var zd = L("prisma:client:engines:resolveEnginePath"); + var Yd = () => new RegExp("runtime[\\\\/]library\\.m?js$"); + async function za(e, t) { + let r = { binary: process.env.PRISMA_QUERY_ENGINE_BINARY, library: process.env.PRISMA_QUERY_ENGINE_LIBRARY }[e] ?? t.prismaPath; + if (r !== void 0) return r; + let { enginePath: n, searchedLocations: i } = await Zd(e, t); + if (zd("enginePath", n), n !== void 0 && e === "binary" && li(n), n !== void 0) return t.prismaPath = n; + let o = await nt(), s = t.generator?.binaryTargets ?? [], a = s.some((d) => d.native), l = !s.some((d) => d.value === o), u = __filename.match(Yd()) === null, c = { searchedLocations: i, generatorBinaryTargets: s, generator: t.generator, runtimeBinaryTarget: o, queryEngineName: Ya(e, o), expectedLocation: Er.default.relative(process.cwd(), t.dirname), errorStack: new Error().stack }, p; + throw a && l ? p = Wa(c) : l ? p = Qa(c) : u ? p = Ja(c) : p = Ha(c), new R(p, t.clientVersion); + } + async function Zd(engineType, config) { + let binaryTarget = await nt(), searchedLocations = [], dirname = eval("__dirname"), searchLocations = [config.dirname, Er.default.resolve(dirname, ".."), config.generator?.output?.value ?? dirname, Er.default.resolve(dirname, "../../../.prisma/client"), "/tmp/prisma-engines", config.cwd]; + __filename.includes("resolveEnginePath") && searchLocations.push(Yo()); + for (let e of searchLocations) { + let t = Ya(engineType, binaryTarget), r = Er.default.join(e, t); + if (searchedLocations.push(e), Ka.default.existsSync(r)) return { enginePath: r, searchedLocations }; + } + return { enginePath: void 0, searchedLocations }; + } + function Ya(e, t) { + return e === "library" ? qr(t, "fs") : `query-engine-${t}${t === "windows" ? ".exe" : ""}`; + } + var Hi = k(bi()); + function Za(e) { + return e ? e.replace(/".*"/g, '"X"').replace(/[\s:\[]([+-]?([0-9]*[.])?[0-9]+)/g, (t) => `${t[0]}5`) : ""; + } + function Xa(e) { + return e.split(` +`).map((t) => t.replace(/^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)\s*/, "").replace(/\+\d+\s*ms$/, "")).join(` +`); + } + var el = k(hs()); + function tl({ title: e, user: t = "prisma", repo: r = "prisma", template: n = "bug_report.yml", body: i }) { + return (0, el.default)({ user: t, repo: r, template: n, title: e, body: i }); + } + function rl({ version: e, binaryTarget: t, title: r, description: n, engineVersion: i, database: o, query: s }) { + let a = So(6e3 - (s?.length ?? 0)), l = Xa((0, Hi.default)(a)), u = n ? `# Description +\`\`\` +${n} +\`\`\`` : "", c = (0, Hi.default)(`Hi Prisma Team! My Prisma Client just crashed. This is the report: +## Versions + +| Name | Version | +|-----------------|--------------------| +| Node | ${process.version?.padEnd(19)}| +| OS | ${t?.padEnd(19)}| +| Prisma Client | ${e?.padEnd(19)}| +| Query Engine | ${i?.padEnd(19)}| +| Database | ${o?.padEnd(19)}| + +${u} + +## Logs +\`\`\` +${l} +\`\`\` + +## Client Snippet +\`\`\`ts +// PLEASE FILL YOUR CODE SNIPPET HERE +\`\`\` + +## Schema +\`\`\`prisma +// PLEASE ADD YOUR SCHEMA HERE IF POSSIBLE +\`\`\` + +## Prisma Engine Query +\`\`\` +${s ? Za(s) : ""} +\`\`\` +`), p = tl({ title: r, body: c }); + return `${r} + +This is a non-recoverable error which probably happens when the Prisma Query Engine has a panic. + +${X(p)} + +If you want the Prisma team to look into it, please open the link above \u{1F64F} +To increase the chance of success, please post your schema and a snippet of +how you used Prisma Client in the issue. +`; + } + function Nt({ inlineDatasources: e, overrideDatasources: t, env: r, clientVersion: n }) { + let i, o = Object.keys(e)[0], s = e[o]?.url, a = t[o]?.url; + if (o === void 0 ? i = void 0 : a ? i = a : s?.value ? i = s.value : s?.fromEnvVar && (i = r[s.fromEnvVar]), s?.fromEnvVar !== void 0 && i === void 0) throw new R(`error: Environment variable not found: ${s.fromEnvVar}.`, n); + if (i === void 0) throw new R("error: Missing URL environment variable, value, or override.", n); + return i; + } + var _n = class extends Error { + constructor(t, r) { + super(t), this.clientVersion = r.clientVersion, this.cause = r.cause; + } + get [Symbol.toStringTag]() { + return this.name; + } + }; + var se = class extends _n { + constructor(t, r) { + super(t, r), this.isRetryable = r.isRetryable ?? true; + } + }; + function A(e, t) { + return { ...e, isRetryable: t }; + } + var Mt = class extends se { + constructor(r) { + super("This request must be retried", A(r, true)); + this.name = "ForcedRetryError"; + this.code = "P5001"; + } + }; + w(Mt, "ForcedRetryError"); + var at = class extends se { + constructor(r, n) { + super(r, A(n, false)); + this.name = "InvalidDatasourceError"; + this.code = "P6001"; + } + }; + w(at, "InvalidDatasourceError"); + var lt = class extends se { + constructor(r, n) { + super(r, A(n, false)); + this.name = "NotImplementedYetError"; + this.code = "P5004"; + } + }; + w(lt, "NotImplementedYetError"); + var q = class extends se { + constructor(t, r) { + super(t, r), this.response = r.response; + let n = this.response.headers.get("prisma-request-id"); + if (n) { + let i = `(The request id was: ${n})`; + this.message = this.message + " " + i; + } + } + }; + var ut = class extends q { + constructor(r) { + super("Schema needs to be uploaded", A(r, true)); + this.name = "SchemaMissingError"; + this.code = "P5005"; + } + }; + w(ut, "SchemaMissingError"); + var Ki = "This request could not be understood by the server"; + var wr = class extends q { + constructor(r, n, i) { + super(n || Ki, A(r, false)); + this.name = "BadRequestError"; + this.code = "P5000"; + i && (this.code = i); + } + }; + w(wr, "BadRequestError"); + var xr = class extends q { + constructor(r, n) { + super("Engine not started: healthcheck timeout", A(r, true)); + this.name = "HealthcheckTimeoutError"; + this.code = "P5013"; + this.logs = n; + } + }; + w(xr, "HealthcheckTimeoutError"); + var Pr = class extends q { + constructor(r, n, i) { + super(n, A(r, true)); + this.name = "EngineStartupError"; + this.code = "P5014"; + this.logs = i; + } + }; + w(Pr, "EngineStartupError"); + var vr = class extends q { + constructor(r) { + super("Engine version is not supported", A(r, false)); + this.name = "EngineVersionNotSupportedError"; + this.code = "P5012"; + } + }; + w(vr, "EngineVersionNotSupportedError"); + var zi = "Request timed out"; + var Tr = class extends q { + constructor(r, n = zi) { + super(n, A(r, false)); + this.name = "GatewayTimeoutError"; + this.code = "P5009"; + } + }; + w(Tr, "GatewayTimeoutError"); + var Xd = "Interactive transaction error"; + var Rr = class extends q { + constructor(r, n = Xd) { + super(n, A(r, false)); + this.name = "InteractiveTransactionError"; + this.code = "P5015"; + } + }; + w(Rr, "InteractiveTransactionError"); + var em = "Request parameters are invalid"; + var Cr = class extends q { + constructor(r, n = em) { + super(n, A(r, false)); + this.name = "InvalidRequestError"; + this.code = "P5011"; + } + }; + w(Cr, "InvalidRequestError"); + var Yi = "Requested resource does not exist"; + var Sr = class extends q { + constructor(r, n = Yi) { + super(n, A(r, false)); + this.name = "NotFoundError"; + this.code = "P5003"; + } + }; + w(Sr, "NotFoundError"); + var Zi = "Unknown server error"; + var $t = class extends q { + constructor(r, n, i) { + super(n || Zi, A(r, true)); + this.name = "ServerError"; + this.code = "P5006"; + this.logs = i; + } + }; + w($t, "ServerError"); + var Xi = "Unauthorized, check your connection string"; + var Ar = class extends q { + constructor(r, n = Xi) { + super(n, A(r, false)); + this.name = "UnauthorizedError"; + this.code = "P5007"; + } + }; + w(Ar, "UnauthorizedError"); + var eo = "Usage exceeded, retry again later"; + var Ir = class extends q { + constructor(r, n = eo) { + super(n, A(r, true)); + this.name = "UsageExceededError"; + this.code = "P5008"; + } + }; + w(Ir, "UsageExceededError"); + async function tm(e) { + let t; + try { + t = await e.text(); + } catch { + return { type: "EmptyError" }; + } + try { + let r = JSON.parse(t); + if (typeof r == "string") switch (r) { + case "InternalDataProxyError": + return { type: "DataProxyError", body: r }; + default: + return { type: "UnknownTextError", body: r }; + } + if (typeof r == "object" && r !== null) { + if ("is_panic" in r && "message" in r && "error_code" in r) return { type: "QueryEngineError", body: r }; + if ("EngineNotStarted" in r || "InteractiveTransactionMisrouted" in r || "InvalidRequestError" in r) { + let n = Object.values(r)[0].reason; + return typeof n == "string" && !["SchemaMissing", "EngineVersionNotSupported"].includes(n) ? { type: "UnknownJsonError", body: r } : { type: "DataProxyError", body: r }; + } + } + return { type: "UnknownJsonError", body: r }; + } catch { + return t === "" ? { type: "EmptyError" } : { type: "UnknownTextError", body: t }; + } + } + async function Or(e, t) { + if (e.ok) return; + let r = { clientVersion: t, response: e }, n = await tm(e); + if (n.type === "QueryEngineError") throw new V(n.body.message, { code: n.body.error_code, clientVersion: t }); + if (n.type === "DataProxyError") { + if (n.body === "InternalDataProxyError") throw new $t(r, "Internal Data Proxy error"); + if ("EngineNotStarted" in n.body) { + if (n.body.EngineNotStarted.reason === "SchemaMissing") return new ut(r); + if (n.body.EngineNotStarted.reason === "EngineVersionNotSupported") throw new vr(r); + if ("EngineStartupError" in n.body.EngineNotStarted.reason) { + let { msg: i, logs: o } = n.body.EngineNotStarted.reason.EngineStartupError; + throw new Pr(r, i, o); + } + if ("KnownEngineStartupError" in n.body.EngineNotStarted.reason) { + let { msg: i, error_code: o } = n.body.EngineNotStarted.reason.KnownEngineStartupError; + throw new R(i, t, o); + } + if ("HealthcheckTimeout" in n.body.EngineNotStarted.reason) { + let { logs: i } = n.body.EngineNotStarted.reason.HealthcheckTimeout; + throw new xr(r, i); + } + } + if ("InteractiveTransactionMisrouted" in n.body) { + let i = { IDParseError: "Could not parse interactive transaction ID", NoQueryEngineFoundError: "Could not find Query Engine for the specified host and transaction ID", TransactionStartError: "Could not start interactive transaction" }; + throw new Rr(r, i[n.body.InteractiveTransactionMisrouted.reason]); + } + if ("InvalidRequestError" in n.body) throw new Cr(r, n.body.InvalidRequestError.reason); + } + if (e.status === 401 || e.status === 403) throw new Ar(r, qt(Xi, n)); + if (e.status === 404) return new Sr(r, qt(Yi, n)); + if (e.status === 429) throw new Ir(r, qt(eo, n)); + if (e.status === 504) throw new Tr(r, qt(zi, n)); + if (e.status >= 500) throw new $t(r, qt(Zi, n)); + if (e.status >= 400) throw new wr(r, qt(Ki, n)); + } + function qt(e, t) { + return t.type === "EmptyError" ? e : `${e}: ${JSON.stringify(t)}`; + } + function nl(e) { + let t = Math.pow(2, e) * 50, r = Math.ceil(Math.random() * t) - Math.ceil(t / 2), n = t + r; + return new Promise((i) => setTimeout(() => i(n), n)); + } + var $e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function il(e) { + let t = new TextEncoder().encode(e), r = "", n = t.byteLength, i = n % 3, o = n - i, s, a, l, u, c; + for (let p = 0; p < o; p = p + 3) c = t[p] << 16 | t[p + 1] << 8 | t[p + 2], s = (c & 16515072) >> 18, a = (c & 258048) >> 12, l = (c & 4032) >> 6, u = c & 63, r += $e[s] + $e[a] + $e[l] + $e[u]; + return i == 1 ? (c = t[o], s = (c & 252) >> 2, a = (c & 3) << 4, r += $e[s] + $e[a] + "==") : i == 2 && (c = t[o] << 8 | t[o + 1], s = (c & 64512) >> 10, a = (c & 1008) >> 4, l = (c & 15) << 2, r += $e[s] + $e[a] + $e[l] + "="), r; + } + function ol(e) { + if (!!e.generator?.previewFeatures.some((r) => r.toLowerCase().includes("metrics"))) throw new R("The `metrics` preview feature is not yet available with Accelerate.\nPlease remove `metrics` from the `previewFeatures` in your schema.\n\nMore information about Accelerate: https://pris.ly/d/accelerate", e.clientVersion); + } + function rm(e) { + return e[0] * 1e3 + e[1] / 1e6; + } + function sl(e) { + return new Date(rm(e)); + } + var al = { "@prisma/debug": "workspace:*", "@prisma/engines-version": "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2", "@prisma/fetch-engine": "workspace:*", "@prisma/get-platform": "workspace:*" }; + var kr = class extends se { + constructor(r, n) { + super(`Cannot fetch data from service: +${r}`, A(n, true)); + this.name = "RequestError"; + this.code = "P5010"; + } + }; + w(kr, "RequestError"); + async function ct(e, t, r = (n) => n) { + let n = t.clientVersion; + try { + return typeof fetch == "function" ? await r(fetch)(e, t) : await r(to)(e, t); + } catch (i) { + let o = i.message ?? "Unknown error"; + throw new kr(o, { clientVersion: n }); + } + } + function im(e) { + return { ...e.headers, "Content-Type": "application/json" }; + } + function om(e) { + return { method: e.method, headers: im(e) }; + } + function sm(e, t) { + return { text: () => Promise.resolve(Buffer.concat(e).toString()), json: () => Promise.resolve().then(() => JSON.parse(Buffer.concat(e).toString())), ok: t.statusCode >= 200 && t.statusCode <= 299, status: t.statusCode, url: t.url, headers: new ro(t.headers) }; + } + async function to(e, t = {}) { + let r = am("https"), n = om(t), i = [], { origin: o } = new URL(e); + return new Promise((s, a) => { + let l = r.request(e, n, (u) => { + let { statusCode: c, headers: { location: p } } = u; + c >= 301 && c <= 399 && p && (p.startsWith("http") === false ? s(to(`${o}${p}`, t)) : s(to(p, t))), u.on("data", (d) => i.push(d)), u.on("end", () => s(sm(i, u))), u.on("error", a); + }); + l.on("error", a), l.end(t.body ?? ""); + }); + } + var am = typeof __require < "u" ? __require : () => { + }; + var ro = class { + constructor(t = {}) { + this.headers = /* @__PURE__ */ new Map(); + for (let [r, n] of Object.entries(t)) if (typeof n == "string") this.headers.set(r, n); + else if (Array.isArray(n)) for (let i of n) this.headers.set(r, i); + } + append(t, r) { + this.headers.set(t, r); + } + delete(t) { + this.headers.delete(t); + } + get(t) { + return this.headers.get(t) ?? null; + } + has(t) { + return this.headers.has(t); + } + set(t, r) { + this.headers.set(t, r); + } + forEach(t, r) { + for (let [n, i] of this.headers) t.call(r, i, n, this); + } + }; + var lm = /^[1-9][0-9]*\.[0-9]+\.[0-9]+$/; + var ll = L("prisma:client:dataproxyEngine"); + async function um(e, t) { + let r = al["@prisma/engines-version"], n = t.clientVersion ?? "unknown"; + if (process.env.PRISMA_CLIENT_DATA_PROXY_CLIENT_VERSION) return process.env.PRISMA_CLIENT_DATA_PROXY_CLIENT_VERSION; + if (e.includes("accelerate") && n !== "0.0.0" && n !== "in-memory") return n; + let [i, o] = n?.split("-") ?? []; + if (o === void 0 && lm.test(i)) return i; + if (o !== void 0 || n === "0.0.0" || n === "in-memory") { + if (e.startsWith("localhost") || e.startsWith("127.0.0.1")) return "0.0.0"; + let [s] = r.split("-") ?? [], [a, l, u] = s.split("."), c = cm(`<=${a}.${l}.${u}`), p = await ct(c, { clientVersion: n }); + if (!p.ok) throw new Error(`Failed to fetch stable Prisma version, unpkg.com status ${p.status} ${p.statusText}, response body: ${await p.text() || ""}`); + let d = await p.text(); + ll("length of body fetched from unpkg.com", d.length); + let f; + try { + f = JSON.parse(d); + } catch (g) { + throw console.error("JSON.parse error: body fetched from unpkg.com: ", d), g; + } + return f.version; + } + throw new lt("Only `major.minor.patch` versions are supported by Accelerate.", { clientVersion: n }); + } + async function ul(e, t) { + let r = await um(e, t); + return ll("version", r), r; + } + function cm(e) { + return encodeURI(`https://unpkg.com/prisma@${e}/package.json`); + } + var cl = 3; + var no = L("prisma:client:dataproxyEngine"); + var io = class { + constructor({ apiKey: t, tracingHelper: r, logLevel: n, logQueries: i, engineHash: o }) { + this.apiKey = t, this.tracingHelper = r, this.logLevel = n, this.logQueries = i, this.engineHash = o; + } + build({ traceparent: t, interactiveTransaction: r } = {}) { + let n = { Authorization: `Bearer ${this.apiKey}`, "Prisma-Engine-Hash": this.engineHash }; + this.tracingHelper.isEnabled() && (n.traceparent = t ?? this.tracingHelper.getTraceParent()), r && (n["X-transaction-id"] = r.id); + let i = this.buildCaptureSettings(); + return i.length > 0 && (n["X-capture-telemetry"] = i.join(", ")), n; + } + buildCaptureSettings() { + let t = []; + return this.tracingHelper.isEnabled() && t.push("tracing"), this.logLevel && t.push(this.logLevel), this.logQueries && t.push("query"), t; + } + }; + var Dr = class { + constructor(t) { + this.name = "DataProxyEngine"; + ol(t), this.config = t, this.env = { ...t.env, ...typeof process < "u" ? process.env : {} }, this.inlineSchema = il(t.inlineSchema), this.inlineDatasources = t.inlineDatasources, this.inlineSchemaHash = t.inlineSchemaHash, this.clientVersion = t.clientVersion, this.engineHash = t.engineVersion, this.logEmitter = t.logEmitter, this.tracingHelper = t.tracingHelper; + } + apiKey() { + return this.headerBuilder.apiKey; + } + version() { + return this.engineHash; + } + async start() { + this.startPromise !== void 0 && await this.startPromise, this.startPromise = (async () => { + let [t, r] = this.extractHostAndApiKey(); + this.host = t, this.headerBuilder = new io({ apiKey: r, tracingHelper: this.tracingHelper, logLevel: this.config.logLevel, logQueries: this.config.logQueries, engineHash: this.engineHash }), this.remoteClientVersion = await ul(t, this.config), no("host", this.host); + })(), await this.startPromise; + } + async stop() { + } + propagateResponseExtensions(t) { + t?.logs?.length && t.logs.forEach((r) => { + switch (r.level) { + case "debug": + case "error": + case "trace": + case "warn": + case "info": + break; + case "query": { + let n = typeof r.attributes.query == "string" ? r.attributes.query : ""; + if (!this.tracingHelper.isEnabled()) { + let [i] = n.split("/* traceparent"); + n = i; + } + this.logEmitter.emit("query", { query: n, timestamp: sl(r.timestamp), duration: Number(r.attributes.duration_ms), params: r.attributes.params, target: r.attributes.target }); + } + } + }), t?.traces?.length && this.tracingHelper.createEngineSpan({ span: true, spans: t.traces }); + } + onBeforeExit() { + throw new Error('"beforeExit" hook is not applicable to the remote query engine'); + } + async url(t) { + return await this.start(), `https://${this.host}/${this.remoteClientVersion}/${this.inlineSchemaHash}/${t}`; + } + async uploadSchema() { + let t = { name: "schemaUpload", internal: true }; + return this.tracingHelper.runInChildSpan(t, async () => { + let r = await ct(await this.url("schema"), { method: "PUT", headers: this.headerBuilder.build(), body: this.inlineSchema, clientVersion: this.clientVersion }); + r.ok || no("schema response status", r.status); + let n = await Or(r, this.clientVersion); + if (n) throw this.logEmitter.emit("warn", { message: `Error while uploading schema: ${n.message}`, timestamp: /* @__PURE__ */ new Date(), target: "" }), n; + this.logEmitter.emit("info", { message: `Schema (re)uploaded (hash: ${this.inlineSchemaHash})`, timestamp: /* @__PURE__ */ new Date(), target: "" }); + }); + } + request(t, { traceparent: r, interactiveTransaction: n, customDataProxyFetch: i }) { + return this.requestInternal({ body: t, traceparent: r, interactiveTransaction: n, customDataProxyFetch: i }); + } + async requestBatch(t, { traceparent: r, transaction: n, customDataProxyFetch: i }) { + let o = n?.kind === "itx" ? n.options : void 0, s = Ft(t, n), { batchResult: a, elapsed: l } = await this.requestInternal({ body: s, customDataProxyFetch: i, interactiveTransaction: o, traceparent: r }); + return a.map((u) => "errors" in u && u.errors.length > 0 ? st(u.errors[0], this.clientVersion, this.config.activeProvider) : { data: u, elapsed: l }); + } + requestInternal({ body: t, traceparent: r, customDataProxyFetch: n, interactiveTransaction: i }) { + return this.withRetry({ actionGerund: "querying", callback: async ({ logHttpCall: o }) => { + let s = i ? `${i.payload.endpoint}/graphql` : await this.url("graphql"); + o(s); + let a = await ct(s, { method: "POST", headers: this.headerBuilder.build({ traceparent: r, interactiveTransaction: i }), body: JSON.stringify(t), clientVersion: this.clientVersion }, n); + a.ok || no("graphql response status", a.status), await this.handleError(await Or(a, this.clientVersion)); + let l = await a.json(), u = l.extensions; + if (u && this.propagateResponseExtensions(u), l.errors) throw l.errors.length === 1 ? st(l.errors[0], this.config.clientVersion, this.config.activeProvider) : new B(l.errors, { clientVersion: this.config.clientVersion }); + return l; + } }); + } + async transaction(t, r, n) { + let i = { start: "starting", commit: "committing", rollback: "rolling back" }; + return this.withRetry({ actionGerund: `${i[t]} transaction`, callback: async ({ logHttpCall: o }) => { + if (t === "start") { + let s = JSON.stringify({ max_wait: n.maxWait, timeout: n.timeout, isolation_level: n.isolationLevel }), a = await this.url("transaction/start"); + o(a); + let l = await ct(a, { method: "POST", headers: this.headerBuilder.build({ traceparent: r.traceparent }), body: s, clientVersion: this.clientVersion }); + await this.handleError(await Or(l, this.clientVersion)); + let u = await l.json(), c = u.extensions; + c && this.propagateResponseExtensions(c); + let p = u.id, d = u["data-proxy"].endpoint; + return { id: p, payload: { endpoint: d } }; + } else { + let s = `${n.payload.endpoint}/${t}`; + o(s); + let a = await ct(s, { method: "POST", headers: this.headerBuilder.build({ traceparent: r.traceparent }), clientVersion: this.clientVersion }); + await this.handleError(await Or(a, this.clientVersion)); + let u = (await a.json()).extensions; + u && this.propagateResponseExtensions(u); + return; + } + } }); + } + extractHostAndApiKey() { + let t = { clientVersion: this.clientVersion }, r = Object.keys(this.inlineDatasources)[0], n = Nt({ inlineDatasources: this.inlineDatasources, overrideDatasources: this.config.overrideDatasources, clientVersion: this.clientVersion, env: this.env }), i; + try { + i = new URL(n); + } catch { + throw new at(`Error validating datasource \`${r}\`: the URL must start with the protocol \`prisma://\``, t); + } + let { protocol: o, host: s, searchParams: a } = i; + if (o !== "prisma:" && o !== "prisma+postgres:") throw new at(`Error validating datasource \`${r}\`: the URL must start with the protocol \`prisma://\``, t); + let l = a.get("api_key"); + if (l === null || l.length < 1) throw new at(`Error validating datasource \`${r}\`: the URL must contain a valid API key`, t); + return [s, l]; + } + metrics() { + throw new lt("Metrics are not yet supported for Accelerate", { clientVersion: this.clientVersion }); + } + async withRetry(t) { + for (let r = 0; ; r++) { + let n = (i) => { + this.logEmitter.emit("info", { message: `Calling ${i} (n=${r})`, timestamp: /* @__PURE__ */ new Date(), target: "" }); + }; + try { + return await t.callback({ logHttpCall: n }); + } catch (i) { + if (!(i instanceof se) || !i.isRetryable) throw i; + if (r >= cl) throw i instanceof Mt ? i.cause : i; + this.logEmitter.emit("warn", { message: `Attempt ${r + 1}/${cl} failed for ${t.actionGerund}: ${i.message ?? "(unknown)"}`, timestamp: /* @__PURE__ */ new Date(), target: "" }); + let o = await nl(r); + this.logEmitter.emit("warn", { message: `Retrying after ${o}ms`, timestamp: /* @__PURE__ */ new Date(), target: "" }); + } + } + } + async handleError(t) { + if (t instanceof ut) throw await this.uploadSchema(), new Mt({ clientVersion: this.clientVersion, cause: t }); + if (t) throw t; + } + applyPendingMigrations() { + throw new Error("Method not implemented."); + } + }; + function pl(e) { + if (e?.kind === "itx") return e.options.id; + } + var so = k(__require("os")); + var dl = k(__require("path")); + var oo = Symbol("PrismaLibraryEngineCache"); + function pm() { + let e = globalThis; + return e[oo] === void 0 && (e[oo] = {}), e[oo]; + } + function dm(e) { + let t = pm(); + if (t[e] !== void 0) return t[e]; + let r = dl.default.toNamespacedPath(e), n = { exports: {} }, i = 0; + return process.platform !== "win32" && (i = so.default.constants.dlopen.RTLD_LAZY | so.default.constants.dlopen.RTLD_DEEPBIND), process.dlopen(n, r, i), t[e] = n.exports, n.exports; + } + var ml = { async loadLibrary(e) { + let t = await Yn(), r = await za("library", e); + try { + return e.tracingHelper.runInChildSpan({ name: "loadLibrary", internal: true }, () => dm(r)); + } catch (n) { + let i = ui({ e: n, platformInfo: t, id: r }); + throw new R(i, e.clientVersion); + } + } }; + var ao; + var fl = { async loadLibrary(e) { + let { clientVersion: t, adapter: r, engineWasm: n } = e; + if (r === void 0) throw new R(`The \`adapter\` option for \`PrismaClient\` is required in this context (${In().prettyName})`, t); + if (n === void 0) throw new R("WASM engine was unexpectedly `undefined`", t); + ao === void 0 && (ao = (async () => { + let o = n.getRuntime(), s = await n.getQueryEngineWasmModule(); + if (s == null) throw new R("The loaded wasm module was unexpectedly `undefined` or `null` once loaded", t); + let a = { "./query_engine_bg.js": o }, l = new WebAssembly.Instance(s, a); + return o.__wbg_set_wasm(l.exports), o.QueryEngine; + })()); + let i = await ao; + return { debugPanic() { + return Promise.reject("{}"); + }, dmmf() { + return Promise.resolve("{}"); + }, version() { + return { commit: "unknown", version: "unknown" }; + }, QueryEngine: i }; + } }; + var mm = "P2036"; + var Ae = L("prisma:client:libraryEngine"); + function fm(e) { + return e.item_type === "query" && "query" in e; + } + function gm(e) { + return "level" in e ? e.level === "error" && e.message === "PANIC" : false; + } + var gl = [...Jn, "native"]; + var _r = class { + constructor(t, r) { + this.name = "LibraryEngine"; + this.libraryLoader = r ?? ml, t.engineWasm !== void 0 && (this.libraryLoader = r ?? fl), this.config = t, this.libraryStarted = false, this.logQueries = t.logQueries ?? false, this.logLevel = t.logLevel ?? "error", this.logEmitter = t.logEmitter, this.datamodel = t.inlineSchema, t.enableDebugLogs && (this.logLevel = "debug"); + let n = Object.keys(t.overrideDatasources)[0], i = t.overrideDatasources[n]?.url; + n !== void 0 && i !== void 0 && (this.datasourceOverrides = { [n]: i }), this.libraryInstantiationPromise = this.instantiateLibrary(); + } + async applyPendingMigrations() { + throw new Error("Cannot call this method from this type of engine instance"); + } + async transaction(t, r, n) { + await this.start(); + let i = JSON.stringify(r), o; + if (t === "start") { + let a = JSON.stringify({ max_wait: n.maxWait, timeout: n.timeout, isolation_level: n.isolationLevel }); + o = await this.engine?.startTransaction(a, i); + } else t === "commit" ? o = await this.engine?.commitTransaction(n.id, i) : t === "rollback" && (o = await this.engine?.rollbackTransaction(n.id, i)); + let s = this.parseEngineResponse(o); + if (hm(s)) { + let a = this.getExternalAdapterError(s); + throw a ? a.error : new V(s.message, { code: s.error_code, clientVersion: this.config.clientVersion, meta: s.meta }); + } + return s; + } + async instantiateLibrary() { + if (Ae("internalSetup"), this.libraryInstantiationPromise) return this.libraryInstantiationPromise; + Qn(), this.binaryTarget = await this.getCurrentBinaryTarget(), await this.loadEngine(), this.version(); + } + async getCurrentBinaryTarget() { + { + if (this.binaryTarget) return this.binaryTarget; + let t = await nt(); + if (!gl.includes(t)) throw new R(`Unknown ${ce("PRISMA_QUERY_ENGINE_LIBRARY")} ${ce(H(t))}. Possible binaryTargets: ${qe(gl.join(", "))} or a path to the query engine library. +You may have to run ${qe("prisma generate")} for your changes to take effect.`, this.config.clientVersion); + return t; + } + } + parseEngineResponse(t) { + if (!t) throw new B("Response from the Engine was empty", { clientVersion: this.config.clientVersion }); + try { + return JSON.parse(t); + } catch { + throw new B("Unable to JSON.parse response from engine", { clientVersion: this.config.clientVersion }); + } + } + async loadEngine() { + if (!this.engine) { + this.QueryEngineConstructor || (this.library = await this.libraryLoader.loadLibrary(this.config), this.QueryEngineConstructor = this.library.QueryEngine); + try { + let t = new WeakRef(this), { adapter: r } = this.config; + r && Ae("Using driver adapter: %O", r), this.engine = new this.QueryEngineConstructor({ datamodel: this.datamodel, env: process.env, logQueries: this.config.logQueries ?? false, ignoreEnvVarErrors: true, datasourceOverrides: this.datasourceOverrides ?? {}, logLevel: this.logLevel, configDir: this.config.cwd, engineProtocol: "json" }, (n) => { + t.deref()?.logger(n); + }, r); + } catch (t) { + let r = t, n = this.parseInitError(r.message); + throw typeof n == "string" ? r : new R(n.message, this.config.clientVersion, n.error_code); + } + } + } + logger(t) { + let r = this.parseEngineResponse(t); + if (r) { + if ("span" in r) { + this.config.tracingHelper.createEngineSpan(r); + return; + } + r.level = r?.level.toLowerCase() ?? "unknown", fm(r) ? this.logEmitter.emit("query", { timestamp: /* @__PURE__ */ new Date(), query: r.query, params: r.params, duration: Number(r.duration_ms), target: r.module_path }) : gm(r) ? this.loggerRustPanic = new le(lo(this, `${r.message}: ${r.reason} in ${r.file}:${r.line}:${r.column}`), this.config.clientVersion) : this.logEmitter.emit(r.level, { timestamp: /* @__PURE__ */ new Date(), message: r.message, target: r.module_path }); + } + } + parseInitError(t) { + try { + return JSON.parse(t); + } catch { + } + return t; + } + parseRequestError(t) { + try { + return JSON.parse(t); + } catch { + } + return t; + } + onBeforeExit() { + throw new Error('"beforeExit" hook is not applicable to the library engine since Prisma 5.0.0, it is only relevant and implemented for the binary engine. Please add your event listener to the `process` object directly instead.'); + } + async start() { + if (await this.libraryInstantiationPromise, await this.libraryStoppingPromise, this.libraryStartingPromise) return Ae(`library already starting, this.libraryStarted: ${this.libraryStarted}`), this.libraryStartingPromise; + if (this.libraryStarted) return; + let t = async () => { + Ae("library starting"); + try { + let r = { traceparent: this.config.tracingHelper.getTraceParent() }; + await this.engine?.connect(JSON.stringify(r)), this.libraryStarted = true, Ae("library started"); + } catch (r) { + let n = this.parseInitError(r.message); + throw typeof n == "string" ? r : new R(n.message, this.config.clientVersion, n.error_code); + } finally { + this.libraryStartingPromise = void 0; + } + }; + return this.libraryStartingPromise = this.config.tracingHelper.runInChildSpan("connect", t), this.libraryStartingPromise; + } + async stop() { + if (await this.libraryStartingPromise, await this.executingQueryPromise, this.libraryStoppingPromise) return Ae("library is already stopping"), this.libraryStoppingPromise; + if (!this.libraryStarted) return; + let t = async () => { + await new Promise((n) => setTimeout(n, 5)), Ae("library stopping"); + let r = { traceparent: this.config.tracingHelper.getTraceParent() }; + await this.engine?.disconnect(JSON.stringify(r)), this.libraryStarted = false, this.libraryStoppingPromise = void 0, Ae("library stopped"); + }; + return this.libraryStoppingPromise = this.config.tracingHelper.runInChildSpan("disconnect", t), this.libraryStoppingPromise; + } + version() { + return this.versionInfo = this.library?.version(), this.versionInfo?.version ?? "unknown"; + } + debugPanic(t) { + return this.library?.debugPanic(t); + } + async request(t, { traceparent: r, interactiveTransaction: n }) { + Ae(`sending request, this.libraryStarted: ${this.libraryStarted}`); + let i = JSON.stringify({ traceparent: r }), o = JSON.stringify(t); + try { + await this.start(), this.executingQueryPromise = this.engine?.query(o, i, n?.id), this.lastQuery = o; + let s = this.parseEngineResponse(await this.executingQueryPromise); + if (s.errors) throw s.errors.length === 1 ? this.buildQueryError(s.errors[0]) : new B(JSON.stringify(s.errors), { clientVersion: this.config.clientVersion }); + if (this.loggerRustPanic) throw this.loggerRustPanic; + return { data: s, elapsed: 0 }; + } catch (s) { + if (s instanceof R) throw s; + if (s.code === "GenericFailure" && s.message?.startsWith("PANIC:")) throw new le(lo(this, s.message), this.config.clientVersion); + let a = this.parseRequestError(s.message); + throw typeof a == "string" ? s : new B(`${a.message} +${a.backtrace}`, { clientVersion: this.config.clientVersion }); + } + } + async requestBatch(t, { transaction: r, traceparent: n }) { + Ae("requestBatch"); + let i = Ft(t, r); + await this.start(), this.lastQuery = JSON.stringify(i), this.executingQueryPromise = this.engine.query(this.lastQuery, JSON.stringify({ traceparent: n }), pl(r)); + let o = await this.executingQueryPromise, s = this.parseEngineResponse(o); + if (s.errors) throw s.errors.length === 1 ? this.buildQueryError(s.errors[0]) : new B(JSON.stringify(s.errors), { clientVersion: this.config.clientVersion }); + let { batchResult: a, errors: l } = s; + if (Array.isArray(a)) return a.map((u) => u.errors && u.errors.length > 0 ? this.loggerRustPanic ?? this.buildQueryError(u.errors[0]) : { data: u, elapsed: 0 }); + throw l && l.length === 1 ? new Error(l[0].error) : new Error(JSON.stringify(s)); + } + buildQueryError(t) { + if (t.user_facing_error.is_panic) return new le(lo(this, t.user_facing_error.message), this.config.clientVersion); + let r = this.getExternalAdapterError(t.user_facing_error); + return r ? r.error : st(t, this.config.clientVersion, this.config.activeProvider); + } + getExternalAdapterError(t) { + if (t.error_code === mm && this.config.adapter) { + let r = t.meta?.id; + Yr(typeof r == "number", "Malformed external JS error received from the engine"); + let n = this.config.adapter.errorRegistry.consumeError(r); + return Yr(n, "External error with reported id was not registered"), n; + } + } + async metrics(t) { + await this.start(); + let r = await this.engine.metrics(JSON.stringify(t)); + return t.format === "prometheus" ? r : this.parseEngineResponse(r); + } + }; + function hm(e) { + return typeof e == "object" && e !== null && e.error_code !== void 0; + } + function lo(e, t) { + return rl({ binaryTarget: e.binaryTarget, title: t, version: e.config.clientVersion, engineVersion: e.versionInfo?.commit, database: e.config.activeProvider, query: e.lastQuery }); + } + function hl({ copyEngine: e = true }, t) { + let r; + try { + r = Nt({ inlineDatasources: t.inlineDatasources, overrideDatasources: t.overrideDatasources, env: { ...t.env, ...process.env }, clientVersion: t.clientVersion }); + } catch { + } + let n = !!(r?.startsWith("prisma://") || r?.startsWith("prisma+postgres://")); + e && n && tr("recommend--no-engine", "In production, we recommend using `prisma generate --no-engine` (See: `prisma generate --help`)"); + let i = Yt(t.generator), o = n || !e, s = !!t.adapter, a = i === "library", l = i === "binary"; + if (o && s || s && false) { + let u; + throw e ? r?.startsWith("prisma://") ? u = ["Prisma Client was configured to use the `adapter` option but the URL was a `prisma://` URL.", "Please either use the `prisma://` URL or remove the `adapter` from the Prisma Client constructor."] : u = ["Prisma Client was configured to use both the `adapter` and Accelerate, please chose one."] : u = ["Prisma Client was configured to use the `adapter` option but `prisma generate` was run with `--no-engine`.", "Please run `prisma generate` without `--no-engine` to be able to use Prisma Client with the adapter."], new J(u.join(` +`), { clientVersion: t.clientVersion }); + } + if (o) return new Dr(t); + if (a) return new _r(t); + throw new J("Invalid client engine type, please use `library` or `binary`", { clientVersion: t.clientVersion }); + } + function Fn({ generator: e }) { + return e?.previewFeatures ?? []; + } + var yl = (e) => ({ command: e }); + var bl = (e) => e.strings.reduce((t, r, n) => `${t}@P${n}${r}`); + function jt(e) { + try { + return El(e, "fast"); + } catch { + return El(e, "slow"); + } + } + function El(e, t) { + return JSON.stringify(e.map((r) => xl(r, t))); + } + function xl(e, t) { + return Array.isArray(e) ? e.map((r) => xl(r, t)) : typeof e == "bigint" ? { prisma__type: "bigint", prisma__value: e.toString() } : Pt(e) ? { prisma__type: "date", prisma__value: e.toJSON() } : xe.isDecimal(e) ? { prisma__type: "decimal", prisma__value: e.toJSON() } : Buffer.isBuffer(e) ? { prisma__type: "bytes", prisma__value: e.toString("base64") } : ym(e) || ArrayBuffer.isView(e) ? { prisma__type: "bytes", prisma__value: Buffer.from(e).toString("base64") } : typeof e == "object" && t === "slow" ? Pl(e) : e; + } + function ym(e) { + return e instanceof ArrayBuffer || e instanceof SharedArrayBuffer ? true : typeof e == "object" && e !== null ? e[Symbol.toStringTag] === "ArrayBuffer" || e[Symbol.toStringTag] === "SharedArrayBuffer" : false; + } + function Pl(e) { + if (typeof e != "object" || e === null) return e; + if (typeof e.toJSON == "function") return e.toJSON(); + if (Array.isArray(e)) return e.map(wl); + let t = {}; + for (let r of Object.keys(e)) t[r] = wl(e[r]); + return t; + } + function wl(e) { + return typeof e == "bigint" ? e.toString() : Pl(e); + } + var bm = ["$connect", "$disconnect", "$on", "$transaction", "$use", "$extends"]; + var vl = bm; + var Em = /^(\s*alter\s)/i; + var Tl = L("prisma:client"); + function uo(e, t, r, n) { + if (!(e !== "postgresql" && e !== "cockroachdb") && r.length > 0 && Em.exec(t)) throw new Error(`Running ALTER using ${n} is not supported +Using the example below you can still execute your query with Prisma, but please note that it is vulnerable to SQL injection attacks and requires you to take care of input sanitization. + +Example: + await prisma.$executeRawUnsafe(\`ALTER USER prisma WITH PASSWORD '\${password}'\`) + +More Information: https://pris.ly/d/execute-raw +`); + } + var co = ({ clientMethod: e, activeProvider: t }) => (r) => { + let n = "", i; + if (pa(r)) n = r.sql, i = { values: jt(r.values), __prismaRawParameters__: true }; + else if (Array.isArray(r)) { + let [o, ...s] = r; + n = o, i = { values: jt(s || []), __prismaRawParameters__: true }; + } else switch (t) { + case "sqlite": + case "mysql": { + n = r.sql, i = { values: jt(r.values), __prismaRawParameters__: true }; + break; + } + case "cockroachdb": + case "postgresql": + case "postgres": { + n = r.text, i = { values: jt(r.values), __prismaRawParameters__: true }; + break; + } + case "sqlserver": { + n = bl(r), i = { values: jt(r.values), __prismaRawParameters__: true }; + break; + } + default: + throw new Error(`The ${t} provider does not support ${e}`); + } + return i?.values ? Tl(`prisma.${e}(${n}, ${i.values})`) : Tl(`prisma.${e}(${n})`), { query: n, parameters: i }; + }; + var Rl = { requestArgsToMiddlewareArgs(e) { + return [e.strings, ...e.values]; + }, middlewareArgsToRequestArgs(e) { + let [t, ...r] = e; + return new oe(t, r); + } }; + var Cl = { requestArgsToMiddlewareArgs(e) { + return [e]; + }, middlewareArgsToRequestArgs(e) { + return e[0]; + } }; + function po(e) { + return function(r) { + let n, i = (o = e) => { + try { + return o === void 0 || o?.kind === "itx" ? n ??= Sl(r(o)) : Sl(r(o)); + } catch (s) { + return Promise.reject(s); + } + }; + return { then(o, s) { + return i().then(o, s); + }, catch(o) { + return i().catch(o); + }, finally(o) { + return i().finally(o); + }, requestTransaction(o) { + let s = i(o); + return s.requestTransaction ? s.requestTransaction(o) : s; + }, [Symbol.toStringTag]: "PrismaPromise" }; + }; + } + function Sl(e) { + return typeof e.then == "function" ? e : Promise.resolve(e); + } + var Al = { isEnabled() { + return false; + }, getTraceParent() { + return "00-10-10-00"; + }, async createEngineSpan() { + }, getActiveContext() { + }, runInChildSpan(e, t) { + return t(); + } }; + var mo = class { + isEnabled() { + return this.getGlobalTracingHelper().isEnabled(); + } + getTraceParent(t) { + return this.getGlobalTracingHelper().getTraceParent(t); + } + createEngineSpan(t) { + return this.getGlobalTracingHelper().createEngineSpan(t); + } + getActiveContext() { + return this.getGlobalTracingHelper().getActiveContext(); + } + runInChildSpan(t, r) { + return this.getGlobalTracingHelper().runInChildSpan(t, r); + } + getGlobalTracingHelper() { + return globalThis.PRISMA_INSTRUMENTATION?.helper ?? Al; + } + }; + function Il(e) { + return e.includes("tracing") ? new mo() : Al; + } + function Ol(e, t = () => { + }) { + let r, n = new Promise((i) => r = i); + return { then(i) { + return --e === 0 && r(t()), i?.(n); + } }; + } + function kl(e) { + return typeof e == "string" ? e : e.reduce((t, r) => { + let n = typeof r == "string" ? r : r.level; + return n === "query" ? t : t && (r === "info" || t === "info") ? "info" : n; + }, void 0); + } + var Ln = class { + constructor() { + this._middlewares = []; + } + use(t) { + this._middlewares.push(t); + } + get(t) { + return this._middlewares[t]; + } + has(t) { + return !!this._middlewares[t]; + } + length() { + return this._middlewares.length; + } + }; + var Fl = k(bi()); + function Nn(e) { + return typeof e.batchRequestIdx == "number"; + } + function Dl(e) { + if (e.action !== "findUnique" && e.action !== "findUniqueOrThrow") return; + let t = []; + return e.modelName && t.push(e.modelName), e.query.arguments && t.push(fo(e.query.arguments)), t.push(fo(e.query.selection)), t.join(""); + } + function fo(e) { + return `(${Object.keys(e).sort().map((r) => { + let n = e[r]; + return typeof n == "object" && n !== null ? `(${r} ${fo(n)})` : r; + }).join(" ")})`; + } + var wm = { aggregate: false, aggregateRaw: false, createMany: true, createManyAndReturn: true, createOne: true, deleteMany: true, deleteOne: true, executeRaw: true, findFirst: false, findFirstOrThrow: false, findMany: false, findRaw: false, findUnique: false, findUniqueOrThrow: false, groupBy: false, queryRaw: false, runCommandRaw: true, updateMany: true, updateOne: true, upsertOne: true }; + function go(e) { + return wm[e]; + } + var Mn = class { + constructor(t) { + this.options = t; + this.tickActive = false; + this.batches = {}; + } + request(t) { + let r = this.options.batchBy(t); + return r ? (this.batches[r] || (this.batches[r] = [], this.tickActive || (this.tickActive = true, process.nextTick(() => { + this.dispatchBatches(), this.tickActive = false; + }))), new Promise((n, i) => { + this.batches[r].push({ request: t, resolve: n, reject: i }); + })) : this.options.singleLoader(t); + } + dispatchBatches() { + for (let t in this.batches) { + let r = this.batches[t]; + delete this.batches[t], r.length === 1 ? this.options.singleLoader(r[0].request).then((n) => { + n instanceof Error ? r[0].reject(n) : r[0].resolve(n); + }).catch((n) => { + r[0].reject(n); + }) : (r.sort((n, i) => this.options.batchOrder(n.request, i.request)), this.options.batchLoader(r.map((n) => n.request)).then((n) => { + if (n instanceof Error) for (let i = 0; i < r.length; i++) r[i].reject(n); + else for (let i = 0; i < r.length; i++) { + let o = n[i]; + o instanceof Error ? r[i].reject(o) : r[i].resolve(o); + } + }).catch((n) => { + for (let i = 0; i < r.length; i++) r[i].reject(n); + })); + } + } + get [Symbol.toStringTag]() { + return "DataLoader"; + } + }; + function pt(e, t) { + if (t === null) return t; + switch (e) { + case "bigint": + return BigInt(t); + case "bytes": + return Buffer.from(t, "base64"); + case "decimal": + return new xe(t); + case "datetime": + case "date": + return new Date(t); + case "time": + return /* @__PURE__ */ new Date(`1970-01-01T${t}Z`); + case "bigint-array": + return t.map((r) => pt("bigint", r)); + case "bytes-array": + return t.map((r) => pt("bytes", r)); + case "decimal-array": + return t.map((r) => pt("decimal", r)); + case "datetime-array": + return t.map((r) => pt("datetime", r)); + case "date-array": + return t.map((r) => pt("date", r)); + case "time-array": + return t.map((r) => pt("time", r)); + default: + return t; + } + } + function _l(e) { + let t = [], r = xm(e); + for (let n = 0; n < e.rows.length; n++) { + let i = e.rows[n], o = { ...r }; + for (let s = 0; s < i.length; s++) o[e.columns[s]] = pt(e.types[s], i[s]); + t.push(o); + } + return t; + } + function xm(e) { + let t = {}; + for (let r = 0; r < e.columns.length; r++) t[e.columns[r]] = null; + return t; + } + var Pm = L("prisma:client:request_handler"); + var $n = class { + constructor(t, r) { + this.logEmitter = r, this.client = t, this.dataloader = new Mn({ batchLoader: Ma(async ({ requests: n, customDataProxyFetch: i }) => { + let { transaction: o, otelParentCtx: s } = n[0], a = n.map((p) => p.protocolQuery), l = this.client._tracingHelper.getTraceParent(s), u = n.some((p) => go(p.protocolQuery.action)); + return (await this.client._engine.requestBatch(a, { traceparent: l, transaction: vm(o), containsWrite: u, customDataProxyFetch: i })).map((p, d) => { + if (p instanceof Error) return p; + try { + return this.mapQueryEngineResult(n[d], p); + } catch (f) { + return f; + } + }); + }), singleLoader: async (n) => { + let i = n.transaction?.kind === "itx" ? Ll(n.transaction) : void 0, o = await this.client._engine.request(n.protocolQuery, { traceparent: this.client._tracingHelper.getTraceParent(), interactiveTransaction: i, isWrite: go(n.protocolQuery.action), customDataProxyFetch: n.customDataProxyFetch }); + return this.mapQueryEngineResult(n, o); + }, batchBy: (n) => n.transaction?.id ? `transaction-${n.transaction.id}` : Dl(n.protocolQuery), batchOrder(n, i) { + return n.transaction?.kind === "batch" && i.transaction?.kind === "batch" ? n.transaction.index - i.transaction.index : 0; + } }); + } + async request(t) { + try { + return await this.dataloader.request(t); + } catch (r) { + let { clientMethod: n, callsite: i, transaction: o, args: s, modelName: a } = t; + this.handleAndLogRequestError({ error: r, clientMethod: n, callsite: i, transaction: o, args: s, modelName: a, globalOmit: t.globalOmit }); + } + } + mapQueryEngineResult({ dataPath: t, unpacker: r }, n) { + let i = n?.data, o = n?.elapsed, s = this.unpack(i, t, r); + return process.env.PRISMA_CLIENT_GET_TIME ? { data: s, elapsed: o } : s; + } + handleAndLogRequestError(t) { + try { + this.handleRequestError(t); + } catch (r) { + throw this.logEmitter && this.logEmitter.emit("error", { message: r.message, target: t.clientMethod, timestamp: /* @__PURE__ */ new Date() }), r; + } + } + handleRequestError({ error: t, clientMethod: r, callsite: n, transaction: i, args: o, modelName: s, globalOmit: a }) { + if (Pm(t), Tm(t, i) || t instanceof Le) throw t; + if (t instanceof V && Rm(t)) { + let u = Nl(t.meta); + wn({ args: o, errors: [u], callsite: n, errorFormat: this.client._errorFormat, originalMethod: r, clientVersion: this.client._clientVersion, globalOmit: a }); + } + let l = t.message; + if (n && (l = Tt({ callsite: n, originalMethod: r, isPanic: t.isPanic, showColors: this.client._errorFormat === "pretty", message: l })), l = this.sanitizeMessage(l), t.code) { + let u = s ? { modelName: s, ...t.meta } : t.meta; + throw new V(l, { code: t.code, clientVersion: this.client._clientVersion, meta: u, batchRequestIdx: t.batchRequestIdx }); + } else { + if (t.isPanic) throw new le(l, this.client._clientVersion); + if (t instanceof B) throw new B(l, { clientVersion: this.client._clientVersion, batchRequestIdx: t.batchRequestIdx }); + if (t instanceof R) throw new R(l, this.client._clientVersion); + if (t instanceof le) throw new le(l, this.client._clientVersion); + } + throw t.clientVersion = this.client._clientVersion, t; + } + sanitizeMessage(t) { + return this.client._errorFormat && this.client._errorFormat !== "pretty" ? (0, Fl.default)(t) : t; + } + unpack(t, r, n) { + if (!t || (t.data && (t = t.data), !t)) return t; + let i = Object.keys(t)[0], o = Object.values(t)[0], s = r.filter((u) => u !== "select" && u !== "include"), a = Gi(o, s), l = i === "queryRaw" ? _l(a) : wt(a); + return n ? n(l) : l; + } + get [Symbol.toStringTag]() { + return "RequestHandler"; + } + }; + function vm(e) { + if (e) { + if (e.kind === "batch") return { kind: "batch", options: { isolationLevel: e.isolationLevel } }; + if (e.kind === "itx") return { kind: "itx", options: Ll(e) }; + Fe(e, "Unknown transaction kind"); + } + } + function Ll(e) { + return { id: e.id, payload: e.payload }; + } + function Tm(e, t) { + return Nn(e) && t?.kind === "batch" && e.batchRequestIdx !== t.index; + } + function Rm(e) { + return e.code === "P2009" || e.code === "P2012"; + } + function Nl(e) { + if (e.kind === "Union") return { kind: "Union", errors: e.errors.map(Nl) }; + if (Array.isArray(e.selectionPath)) { + let [, ...t] = e.selectionPath; + return { ...e, selectionPath: t }; + } + return e; + } + var Ml = "5.22.0"; + var $l = Ml; + var Ul = k(Ai()); + var F = class extends Error { + constructor(t) { + super(t + ` +Read more at https://pris.ly/d/client-constructor`), this.name = "PrismaClientConstructorValidationError"; + } + get [Symbol.toStringTag]() { + return "PrismaClientConstructorValidationError"; + } + }; + w(F, "PrismaClientConstructorValidationError"); + var ql = ["datasources", "datasourceUrl", "errorFormat", "adapter", "log", "transactionOptions", "omit", "__internal"]; + var jl = ["pretty", "colorless", "minimal"]; + var Vl = ["info", "query", "warn", "error"]; + var Sm = { datasources: (e, { datasourceNames: t }) => { + if (e) { + if (typeof e != "object" || Array.isArray(e)) throw new F(`Invalid value ${JSON.stringify(e)} for "datasources" provided to PrismaClient constructor`); + for (let [r, n] of Object.entries(e)) { + if (!t.includes(r)) { + let i = Vt(r, t) || ` Available datasources: ${t.join(", ")}`; + throw new F(`Unknown datasource ${r} provided to PrismaClient constructor.${i}`); + } + if (typeof n != "object" || Array.isArray(n)) throw new F(`Invalid value ${JSON.stringify(e)} for datasource "${r}" provided to PrismaClient constructor. +It should have this form: { url: "CONNECTION_STRING" }`); + if (n && typeof n == "object") for (let [i, o] of Object.entries(n)) { + if (i !== "url") throw new F(`Invalid value ${JSON.stringify(e)} for datasource "${r}" provided to PrismaClient constructor. +It should have this form: { url: "CONNECTION_STRING" }`); + if (typeof o != "string") throw new F(`Invalid value ${JSON.stringify(o)} for datasource "${r}" provided to PrismaClient constructor. +It should have this form: { url: "CONNECTION_STRING" }`); + } + } + } + }, adapter: (e, t) => { + if (e === null) return; + if (e === void 0) throw new F('"adapter" property must not be undefined, use null to conditionally disable driver adapters.'); + if (!Fn(t).includes("driverAdapters")) throw new F('"adapter" property can only be provided to PrismaClient constructor when "driverAdapters" preview feature is enabled.'); + if (Yt() === "binary") throw new F('Cannot use a driver adapter with the "binary" Query Engine. Please use the "library" Query Engine.'); + }, datasourceUrl: (e) => { + if (typeof e < "u" && typeof e != "string") throw new F(`Invalid value ${JSON.stringify(e)} for "datasourceUrl" provided to PrismaClient constructor. +Expected string or undefined.`); + }, errorFormat: (e) => { + if (e) { + if (typeof e != "string") throw new F(`Invalid value ${JSON.stringify(e)} for "errorFormat" provided to PrismaClient constructor.`); + if (!jl.includes(e)) { + let t = Vt(e, jl); + throw new F(`Invalid errorFormat ${e} provided to PrismaClient constructor.${t}`); + } + } + }, log: (e) => { + if (!e) return; + if (!Array.isArray(e)) throw new F(`Invalid value ${JSON.stringify(e)} for "log" provided to PrismaClient constructor.`); + function t(r) { + if (typeof r == "string" && !Vl.includes(r)) { + let n = Vt(r, Vl); + throw new F(`Invalid log level "${r}" provided to PrismaClient constructor.${n}`); + } + } + for (let r of e) { + t(r); + let n = { level: t, emit: (i) => { + let o = ["stdout", "event"]; + if (!o.includes(i)) { + let s = Vt(i, o); + throw new F(`Invalid value ${JSON.stringify(i)} for "emit" in logLevel provided to PrismaClient constructor.${s}`); + } + } }; + if (r && typeof r == "object") for (let [i, o] of Object.entries(r)) if (n[i]) n[i](o); + else throw new F(`Invalid property ${i} for "log" provided to PrismaClient constructor`); + } + }, transactionOptions: (e) => { + if (!e) return; + let t = e.maxWait; + if (t != null && t <= 0) throw new F(`Invalid value ${t} for maxWait in "transactionOptions" provided to PrismaClient constructor. maxWait needs to be greater than 0`); + let r = e.timeout; + if (r != null && r <= 0) throw new F(`Invalid value ${r} for timeout in "transactionOptions" provided to PrismaClient constructor. timeout needs to be greater than 0`); + }, omit: (e, t) => { + if (typeof e != "object") throw new F('"omit" option is expected to be an object.'); + if (e === null) throw new F('"omit" option can not be `null`'); + let r = []; + for (let [n, i] of Object.entries(e)) { + let o = Im(n, t.runtimeDataModel); + if (!o) { + r.push({ kind: "UnknownModel", modelKey: n }); + continue; + } + for (let [s, a] of Object.entries(i)) { + let l = o.fields.find((u) => u.name === s); + if (!l) { + r.push({ kind: "UnknownField", modelKey: n, fieldName: s }); + continue; + } + if (l.relationName) { + r.push({ kind: "RelationInOmit", modelKey: n, fieldName: s }); + continue; + } + typeof a != "boolean" && r.push({ kind: "InvalidFieldValue", modelKey: n, fieldName: s }); + } + } + if (r.length > 0) throw new F(Om(e, r)); + }, __internal: (e) => { + if (!e) return; + let t = ["debug", "engine", "configOverride"]; + if (typeof e != "object") throw new F(`Invalid value ${JSON.stringify(e)} for "__internal" to PrismaClient constructor`); + for (let [r] of Object.entries(e)) if (!t.includes(r)) { + let n = Vt(r, t); + throw new F(`Invalid property ${JSON.stringify(r)} for "__internal" provided to PrismaClient constructor.${n}`); + } + } }; + function Gl(e, t) { + for (let [r, n] of Object.entries(e)) { + if (!ql.includes(r)) { + let i = Vt(r, ql); + throw new F(`Unknown property ${r} provided to PrismaClient constructor.${i}`); + } + Sm[r](n, t); + } + if (e.datasourceUrl && e.datasources) throw new F('Can not use "datasourceUrl" and "datasources" options at the same time. Pick one of them'); + } + function Vt(e, t) { + if (t.length === 0 || typeof e != "string") return ""; + let r = Am(e, t); + return r ? ` Did you mean "${r}"?` : ""; + } + function Am(e, t) { + if (t.length === 0) return null; + let r = t.map((i) => ({ value: i, distance: (0, Ul.default)(e, i) })); + r.sort((i, o) => i.distance < o.distance ? -1 : 1); + let n = r[0]; + return n.distance < 3 ? n.value : null; + } + function Im(e, t) { + return Bl(t.models, e) ?? Bl(t.types, e); + } + function Bl(e, t) { + let r = Object.keys(e).find((n) => xt(n) === t); + if (r) return e[r]; + } + function Om(e, t) { + let r = Ot(e); + for (let o of t) switch (o.kind) { + case "UnknownModel": + r.arguments.getField(o.modelKey)?.markAsError(), r.addErrorMessage(() => `Unknown model name: ${o.modelKey}.`); + break; + case "UnknownField": + r.arguments.getDeepField([o.modelKey, o.fieldName])?.markAsError(), r.addErrorMessage(() => `Model "${o.modelKey}" does not have a field named "${o.fieldName}".`); + break; + case "RelationInOmit": + r.arguments.getDeepField([o.modelKey, o.fieldName])?.markAsError(), r.addErrorMessage(() => 'Relations are already excluded by default and can not be specified in "omit".'); + break; + case "InvalidFieldValue": + r.arguments.getDeepFieldValue([o.modelKey, o.fieldName])?.markAsError(), r.addErrorMessage(() => "Omit field option value must be a boolean."); + break; + } + let { message: n, args: i } = En(r, "colorless"); + return `Error validating "omit" option: + +${i} + +${n}`; + } + function Ql(e) { + return e.length === 0 ? Promise.resolve([]) : new Promise((t, r) => { + let n = new Array(e.length), i = null, o = false, s = 0, a = () => { + o || (s++, s === e.length && (o = true, i ? r(i) : t(n))); + }, l = (u) => { + o || (o = true, r(u)); + }; + for (let u = 0; u < e.length; u++) e[u].then((c) => { + n[u] = c, a(); + }, (c) => { + if (!Nn(c)) { + l(c); + return; + } + c.batchRequestIdx === u ? l(c) : (i || (i = c), a()); + }); + }); + } + var tt = L("prisma:client"); + typeof globalThis == "object" && (globalThis.NODE_CLIENT = true); + var km = { requestArgsToMiddlewareArgs: (e) => e, middlewareArgsToRequestArgs: (e) => e }; + var Dm = Symbol.for("prisma.client.transaction.id"); + var _m = { id: 0, nextId() { + return ++this.id; + } }; + function Yl(e) { + class t { + constructor(n) { + this._originalClient = this; + this._middlewares = new Ln(); + this._createPrismaPromise = po(); + this.$extends = Ia; + e = n?.__internal?.configOverride?.(e) ?? e, Ba(e), n && Gl(n, e); + let i = new Kl.EventEmitter().on("error", () => { + }); + this._extensions = kt.empty(), this._previewFeatures = Fn(e), this._clientVersion = e.clientVersion ?? $l, this._activeProvider = e.activeProvider, this._globalOmit = n?.omit, this._tracingHelper = Il(this._previewFeatures); + let o = { rootEnvPath: e.relativeEnvPaths.rootEnvPath && Fr.default.resolve(e.dirname, e.relativeEnvPaths.rootEnvPath), schemaEnvPath: e.relativeEnvPaths.schemaEnvPath && Fr.default.resolve(e.dirname, e.relativeEnvPaths.schemaEnvPath) }, s; + if (n?.adapter) { + s = qi(n.adapter); + let l = e.activeProvider === "postgresql" ? "postgres" : e.activeProvider; + if (s.provider !== l) throw new R(`The Driver Adapter \`${s.adapterName}\`, based on \`${s.provider}\`, is not compatible with the provider \`${l}\` specified in the Prisma schema.`, this._clientVersion); + if (n.datasources || n.datasourceUrl !== void 0) throw new R("Custom datasource configuration is not compatible with Prisma Driver Adapters. Please define the database connection string directly in the Driver Adapter configuration.", this._clientVersion); + } + let a = !s && zt(o, { conflictCheck: "none" }) || e.injectableEdgeEnv?.(); + try { + let l = n ?? {}, u = l.__internal ?? {}, c = u.debug === true; + c && L.enable("prisma:client"); + let p = Fr.default.resolve(e.dirname, e.relativePath); + zl.default.existsSync(p) || (p = e.dirname), tt("dirname", e.dirname), tt("relativePath", e.relativePath), tt("cwd", p); + let d = u.engine || {}; + if (l.errorFormat ? this._errorFormat = l.errorFormat : process.env.NODE_ENV === "production" ? this._errorFormat = "minimal" : process.env.NO_COLOR ? this._errorFormat = "colorless" : this._errorFormat = "colorless", this._runtimeDataModel = e.runtimeDataModel, this._engineConfig = { cwd: p, dirname: e.dirname, enableDebugLogs: c, allowTriggerPanic: d.allowTriggerPanic, datamodelPath: Fr.default.join(e.dirname, e.filename ?? "schema.prisma"), prismaPath: d.binaryPath ?? void 0, engineEndpoint: d.endpoint, generator: e.generator, showColors: this._errorFormat === "pretty", logLevel: l.log && kl(l.log), logQueries: l.log && !!(typeof l.log == "string" ? l.log === "query" : l.log.find((f) => typeof f == "string" ? f === "query" : f.level === "query")), env: a?.parsed ?? {}, flags: [], engineWasm: e.engineWasm, clientVersion: e.clientVersion, engineVersion: e.engineVersion, previewFeatures: this._previewFeatures, activeProvider: e.activeProvider, inlineSchema: e.inlineSchema, overrideDatasources: Ua(l, e.datasourceNames), inlineDatasources: e.inlineDatasources, inlineSchemaHash: e.inlineSchemaHash, tracingHelper: this._tracingHelper, transactionOptions: { maxWait: l.transactionOptions?.maxWait ?? 2e3, timeout: l.transactionOptions?.timeout ?? 5e3, isolationLevel: l.transactionOptions?.isolationLevel }, logEmitter: i, isBundled: e.isBundled, adapter: s }, this._accelerateEngineConfig = { ...this._engineConfig, accelerateUtils: { resolveDatasourceUrl: Nt, getBatchRequestPayload: Ft, prismaGraphQLToJSError: st, PrismaClientUnknownRequestError: B, PrismaClientInitializationError: R, PrismaClientKnownRequestError: V, debug: L("prisma:client:accelerateEngine"), engineVersion: Wl.version, clientVersion: e.clientVersion } }, tt("clientVersion", e.clientVersion), this._engine = hl(e, this._engineConfig), this._requestHandler = new $n(this, i), l.log) for (let f of l.log) { + let g = typeof f == "string" ? f : f.emit === "stdout" ? f.level : null; + g && this.$on(g, (h) => { + er.log(`${er.tags[g] ?? ""}`, h.message || h.query); + }); + } + this._metrics = new Dt(this._engine); + } catch (l) { + throw l.clientVersion = this._clientVersion, l; + } + return this._appliedParent = yr(this); + } + get [Symbol.toStringTag]() { + return "PrismaClient"; + } + $use(n) { + this._middlewares.use(n); + } + $on(n, i) { + n === "beforeExit" ? this._engine.onBeforeExit(i) : n && this._engineConfig.logEmitter.on(n, i); + } + $connect() { + try { + return this._engine.start(); + } catch (n) { + throw n.clientVersion = this._clientVersion, n; + } + } + async $disconnect() { + try { + await this._engine.stop(); + } catch (n) { + throw n.clientVersion = this._clientVersion, n; + } finally { + Ao(); + } + } + $executeRawInternal(n, i, o, s) { + let a = this._activeProvider; + return this._request({ action: "executeRaw", args: o, transaction: n, clientMethod: i, argsMapper: co({ clientMethod: i, activeProvider: a }), callsite: Ze(this._errorFormat), dataPath: [], middlewareArgsMapper: s }); + } + $executeRaw(n, ...i) { + return this._createPrismaPromise((o) => { + if (n.raw !== void 0 || n.sql !== void 0) { + let [s, a] = Jl(n, i); + return uo(this._activeProvider, s.text, s.values, Array.isArray(n) ? "prisma.$executeRaw``" : "prisma.$executeRaw(sql``)"), this.$executeRawInternal(o, "$executeRaw", s, a); + } + throw new J("`$executeRaw` is a tag function, please use it like the following:\n```\nconst result = await prisma.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};`\n```\n\nOr read our docs at https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#executeraw\n", { clientVersion: this._clientVersion }); + }); + } + $executeRawUnsafe(n, ...i) { + return this._createPrismaPromise((o) => (uo(this._activeProvider, n, i, "prisma.$executeRawUnsafe(, [...values])"), this.$executeRawInternal(o, "$executeRawUnsafe", [n, ...i]))); + } + $runCommandRaw(n) { + if (e.activeProvider !== "mongodb") throw new J(`The ${e.activeProvider} provider does not support $runCommandRaw. Use the mongodb provider.`, { clientVersion: this._clientVersion }); + return this._createPrismaPromise((i) => this._request({ args: n, clientMethod: "$runCommandRaw", dataPath: [], action: "runCommandRaw", argsMapper: yl, callsite: Ze(this._errorFormat), transaction: i })); + } + async $queryRawInternal(n, i, o, s) { + let a = this._activeProvider; + return this._request({ action: "queryRaw", args: o, transaction: n, clientMethod: i, argsMapper: co({ clientMethod: i, activeProvider: a }), callsite: Ze(this._errorFormat), dataPath: [], middlewareArgsMapper: s }); + } + $queryRaw(n, ...i) { + return this._createPrismaPromise((o) => { + if (n.raw !== void 0 || n.sql !== void 0) return this.$queryRawInternal(o, "$queryRaw", ...Jl(n, i)); + throw new J("`$queryRaw` is a tag function, please use it like the following:\n```\nconst result = await prisma.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};`\n```\n\nOr read our docs at https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#queryraw\n", { clientVersion: this._clientVersion }); + }); + } + $queryRawTyped(n) { + return this._createPrismaPromise((i) => { + if (!this._hasPreviewFlag("typedSql")) throw new J("`typedSql` preview feature must be enabled in order to access $queryRawTyped API", { clientVersion: this._clientVersion }); + return this.$queryRawInternal(i, "$queryRawTyped", n); + }); + } + $queryRawUnsafe(n, ...i) { + return this._createPrismaPromise((o) => this.$queryRawInternal(o, "$queryRawUnsafe", [n, ...i])); + } + _transactionWithArray({ promises: n, options: i }) { + let o = _m.nextId(), s = Ol(n.length), a = n.map((l, u) => { + if (l?.[Symbol.toStringTag] !== "PrismaPromise") throw new Error("All elements of the array need to be Prisma Client promises. Hint: Please make sure you are not awaiting the Prisma client calls you intended to pass in the $transaction function."); + let c = i?.isolationLevel ?? this._engineConfig.transactionOptions.isolationLevel, p = { kind: "batch", id: o, index: u, isolationLevel: c, lock: s }; + return l.requestTransaction?.(p) ?? l; + }); + return Ql(a); + } + async _transactionWithCallback({ callback: n, options: i }) { + let o = { traceparent: this._tracingHelper.getTraceParent() }, s = { maxWait: i?.maxWait ?? this._engineConfig.transactionOptions.maxWait, timeout: i?.timeout ?? this._engineConfig.transactionOptions.timeout, isolationLevel: i?.isolationLevel ?? this._engineConfig.transactionOptions.isolationLevel }, a = await this._engine.transaction("start", o, s), l; + try { + let u = { kind: "itx", ...a }; + l = await n(this._createItxClient(u)), await this._engine.transaction("commit", o, a); + } catch (u) { + throw await this._engine.transaction("rollback", o, a).catch(() => { + }), u; + } + return l; + } + _createItxClient(n) { + return yr(Se(Aa(this), [re("_appliedParent", () => this._appliedParent._createItxClient(n)), re("_createPrismaPromise", () => po(n)), re(Dm, () => n.id), _t(vl)])); + } + $transaction(n, i) { + let o; + typeof n == "function" ? this._engineConfig.adapter?.adapterName === "@prisma/adapter-d1" ? o = () => { + throw new Error("Cloudflare D1 does not support interactive transactions. We recommend you to refactor your queries with that limitation in mind, and use batch transactions with `prisma.$transactions([])` where applicable."); + } : o = () => this._transactionWithCallback({ callback: n, options: i }) : o = () => this._transactionWithArray({ promises: n, options: i }); + let s = { name: "transaction", attributes: { method: "$transaction" } }; + return this._tracingHelper.runInChildSpan(s, o); + } + _request(n) { + n.otelParentCtx = this._tracingHelper.getActiveContext(); + let i = n.middlewareArgsMapper ?? km, o = { args: i.requestArgsToMiddlewareArgs(n.args), dataPath: n.dataPath, runInTransaction: !!n.transaction, action: n.action, model: n.model }, s = { middleware: { name: "middleware", middleware: true, attributes: { method: "$use" }, active: false }, operation: { name: "operation", attributes: { method: o.action, model: o.model, name: o.model ? `${o.model}.${o.action}` : o.action } } }, a = -1, l = async (u) => { + let c = this._middlewares.get(++a); + if (c) return this._tracingHelper.runInChildSpan(s.middleware, (O) => c(u, (T) => (O?.end(), l(T)))); + let { runInTransaction: p, args: d, ...f } = u, g = { ...n, ...f }; + d && (g.args = i.middlewareArgsToRequestArgs(d)), n.transaction !== void 0 && p === false && delete g.transaction; + let h = await Na(this, g); + return g.model ? Da({ result: h, modelName: g.model, args: g.args, extensions: this._extensions, runtimeDataModel: this._runtimeDataModel, globalOmit: this._globalOmit }) : h; + }; + return this._tracingHelper.runInChildSpan(s.operation, () => new Hl.AsyncResource("prisma-client-request").runInAsyncScope(() => l(o))); + } + async _executeRequest({ args: n, clientMethod: i, dataPath: o, callsite: s, action: a, model: l, argsMapper: u, transaction: c, unpacker: p, otelParentCtx: d, customDataProxyFetch: f }) { + try { + n = u ? u(n) : n; + let g = { name: "serialize" }, h = this._tracingHelper.runInChildSpan(g, () => vn({ modelName: l, runtimeDataModel: this._runtimeDataModel, action: a, args: n, clientMethod: i, callsite: s, extensions: this._extensions, errorFormat: this._errorFormat, clientVersion: this._clientVersion, previewFeatures: this._previewFeatures, globalOmit: this._globalOmit })); + return L.enabled("prisma:client") && (tt("Prisma Client call:"), tt(`prisma.${i}(${ha(n)})`), tt("Generated request:"), tt(JSON.stringify(h, null, 2) + ` +`)), c?.kind === "batch" && await c.lock, this._requestHandler.request({ protocolQuery: h, modelName: l, action: a, clientMethod: i, dataPath: o, callsite: s, args: n, extensions: this._extensions, transaction: c, unpacker: p, otelParentCtx: d, otelChildCtx: this._tracingHelper.getActiveContext(), globalOmit: this._globalOmit, customDataProxyFetch: f }); + } catch (g) { + throw g.clientVersion = this._clientVersion, g; + } + } + get $metrics() { + if (!this._hasPreviewFlag("metrics")) throw new J("`metrics` preview feature must be enabled in order to access metrics API", { clientVersion: this._clientVersion }); + return this._metrics; + } + _hasPreviewFlag(n) { + return !!this._engineConfig.previewFeatures?.includes(n); + } + $applyPendingMigrations() { + return this._engine.applyPendingMigrations(); + } + } + return t; + } + function Jl(e, t) { + return Fm(e) ? [new oe(e, t), Rl] : [e, Cl]; + } + function Fm(e) { + return Array.isArray(e) && Array.isArray(e.raw); + } + var Lm = /* @__PURE__ */ new Set(["toJSON", "$$typeof", "asymmetricMatch", Symbol.iterator, Symbol.toStringTag, Symbol.isConcatSpreadable, Symbol.toPrimitive]); + function Zl(e) { + return new Proxy(e, { get(t, r) { + if (r in t) return t[r]; + if (!Lm.has(r)) throw new TypeError(`Invalid enum value: ${String(r)}`); + } }); + } + function Xl(e) { + zt(e, { conflictCheck: "warn" }); + } + } +}); + +// node_modules/.prisma/client/index.js +var require_client = __commonJS({ + "node_modules/.prisma/client/index.js"(exports2) { + Object.defineProperty(exports2, "__esModule", { value: true }); + var { + PrismaClientKnownRequestError: PrismaClientKnownRequestError2, + PrismaClientUnknownRequestError: PrismaClientUnknownRequestError2, + PrismaClientRustPanicError: PrismaClientRustPanicError2, + PrismaClientInitializationError: PrismaClientInitializationError2, + PrismaClientValidationError: PrismaClientValidationError2, + NotFoundError: NotFoundError3, + getPrismaClient: getPrismaClient2, + sqltag: sqltag2, + empty: empty2, + join: join2, + raw: raw2, + skip: skip2, + Decimal: Decimal2, + Debug: Debug2, + objectEnumValues: objectEnumValues2, + makeStrictEnum: makeStrictEnum2, + Extensions: Extensions2, + warnOnce: warnOnce2, + defineDmmfProperty: defineDmmfProperty2, + Public: Public2, + getRuntime: getRuntime2 + } = require_library(); + var Prisma = {}; + exports2.Prisma = Prisma; + exports2.$Enums = {}; + Prisma.prismaVersion = { + client: "5.22.0", + engine: "605197351a3c8bdd595af2d2a9bc3025bca48ea2" + }; + Prisma.PrismaClientKnownRequestError = PrismaClientKnownRequestError2; + Prisma.PrismaClientUnknownRequestError = PrismaClientUnknownRequestError2; + Prisma.PrismaClientRustPanicError = PrismaClientRustPanicError2; + Prisma.PrismaClientInitializationError = PrismaClientInitializationError2; + Prisma.PrismaClientValidationError = PrismaClientValidationError2; + Prisma.NotFoundError = NotFoundError3; + Prisma.Decimal = Decimal2; + Prisma.sql = sqltag2; + Prisma.empty = empty2; + Prisma.join = join2; + Prisma.raw = raw2; + Prisma.validator = Public2.validator; + Prisma.getExtensionContext = Extensions2.getExtensionContext; + Prisma.defineExtension = Extensions2.defineExtension; + Prisma.DbNull = objectEnumValues2.instances.DbNull; + Prisma.JsonNull = objectEnumValues2.instances.JsonNull; + Prisma.AnyNull = objectEnumValues2.instances.AnyNull; + Prisma.NullTypes = { + DbNull: objectEnumValues2.classes.DbNull, + JsonNull: objectEnumValues2.classes.JsonNull, + AnyNull: objectEnumValues2.classes.AnyNull + }; + var path = __require("path"); + exports2.Prisma.TransactionIsolationLevel = makeStrictEnum2({ + Serializable: "Serializable" + }); + exports2.Prisma.BlockCheckpointScalarFieldEnum = { + id: "id", + network: "network", + blockNumber: "blockNumber", + timestamp: "timestamp" + }; + exports2.Prisma.SortOrder = { + asc: "asc", + desc: "desc" + }; + exports2.Prisma.ModelName = { + BlockCheckpoint: "BlockCheckpoint" + }; + var config3 = { + "generator": { + "name": "client", + "provider": { + "fromEnvVar": null, + "value": "prisma-client-js" + }, + "output": { + "value": "/Users/oleg/Documents/Code/concero/v2-operators/node_modules/@prisma/client", + "fromEnvVar": null + }, + "config": { + "engineType": "library" + }, + "binaryTargets": [ + { + "fromEnvVar": null, + "value": "darwin-arm64", + "native": true + } + ], + "previewFeatures": [], + "sourceFilePath": "/Users/oleg/Documents/Code/concero/v2-operators/prisma/schema.prisma" + }, + "relativeEnvPaths": { + "rootEnvPath": null, + "schemaEnvPath": "../../../.env" + }, + "relativePath": "../../../prisma", + "clientVersion": "5.22.0", + "engineVersion": "605197351a3c8bdd595af2d2a9bc3025bca48ea2", + "datasourceNames": [ + "db" + ], + "activeProvider": "sqlite", + "postinstall": false, + "inlineDatasources": { + "db": { + "url": { + "fromEnvVar": null, + "value": "file:./block-checkpoints.db" + } + } + }, + "inlineSchema": 'generator client {\n provider = "prisma-client-js"\n}\n\ndatasource db {\n provider = "sqlite"\n url = "file:./block-checkpoints.db"\n}\n\nmodel BlockCheckpoint {\n id Int @id @default(autoincrement())\n network String @unique\n blockNumber BigInt\n timestamp DateTime @default(now())\n}\n', + "inlineSchemaHash": "bd1c73e8e712d1b9b3e8c8468e4ed2988c6ff6026cedd767f8cb6f8ca4afe408", + "copyEngine": true + }; + var fs2 = __require("fs"); + config3.dirname = __dirname; + if (!fs2.existsSync(path.join(__dirname, "schema.prisma"))) { + const alternativePaths = [ + "node_modules/.prisma/client", + ".prisma/client" + ]; + const alternativePath = alternativePaths.find((altPath) => { + return fs2.existsSync(path.join(process.cwd(), altPath, "schema.prisma")); + }) ?? alternativePaths[0]; + config3.dirname = path.join(process.cwd(), alternativePath); + config3.isBundled = true; + } + config3.runtimeDataModel = JSON.parse('{"models":{"BlockCheckpoint":{"dbName":null,"fields":[{"name":"id","kind":"scalar","isList":false,"isRequired":true,"isUnique":false,"isId":true,"isReadOnly":false,"hasDefaultValue":true,"type":"Int","default":{"name":"autoincrement","args":[]},"isGenerated":false,"isUpdatedAt":false},{"name":"network","kind":"scalar","isList":false,"isRequired":true,"isUnique":true,"isId":false,"isReadOnly":false,"hasDefaultValue":false,"type":"String","isGenerated":false,"isUpdatedAt":false},{"name":"blockNumber","kind":"scalar","isList":false,"isRequired":true,"isUnique":false,"isId":false,"isReadOnly":false,"hasDefaultValue":false,"type":"BigInt","isGenerated":false,"isUpdatedAt":false},{"name":"timestamp","kind":"scalar","isList":false,"isRequired":true,"isUnique":false,"isId":false,"isReadOnly":false,"hasDefaultValue":true,"type":"DateTime","default":{"name":"now","args":[]},"isGenerated":false,"isUpdatedAt":false}],"primaryKey":null,"uniqueFields":[],"uniqueIndexes":[],"isGenerated":false}},"enums":{},"types":{}}'); + defineDmmfProperty2(exports2.Prisma, config3.runtimeDataModel); + config3.engineWasm = void 0; + var { warnEnvConflicts: warnEnvConflicts2 } = require_library(); + warnEnvConflicts2({ + rootEnvPath: config3.relativeEnvPaths.rootEnvPath && path.resolve(config3.dirname, config3.relativeEnvPaths.rootEnvPath), + schemaEnvPath: config3.relativeEnvPaths.schemaEnvPath && path.resolve(config3.dirname, config3.relativeEnvPaths.schemaEnvPath) + }); + var PrismaClient2 = getPrismaClient2(config3); + exports2.PrismaClient = PrismaClient2; + Object.assign(exports2, Prisma); + path.join(__dirname, "libquery_engine-darwin-arm64.dylib.node"); + path.join(process.cwd(), "node_modules/.prisma/client/libquery_engine-darwin-arm64.dylib.node"); + path.join(__dirname, "schema.prisma"); + path.join(process.cwd(), "node_modules/.prisma/client/schema.prisma"); + } +}); + +// node_modules/.prisma/client/default.js +var require_default = __commonJS({ + "node_modules/.prisma/client/default.js"(exports2, module2) { + module2.exports = { ...require_client() }; + } +}); + +// node_modules/@prisma/client/default.js +var require_default2 = __commonJS({ + "node_modules/@prisma/client/default.js"(exports2, module2) { + module2.exports = { + ...require_default() + }; + } +}); + +// src/common/utils/configureDotEnv.ts +var dotenv = __toESM(require_main(), 1); +var ENV_FILES = [".env", ".env.wallets", ".env.deployments.testnet", ".env.deployments.mainnet"]; +function configureDotEnv(basePath = "./") { + const normalizedBasePath = basePath.endsWith("/") ? basePath : `${basePath}/`; + ENV_FILES.forEach((file) => { + dotenv.config({ path: `${normalizedBasePath}${file}` }); + }); +} +configureDotEnv(); + +// node_modules/axios/lib/helpers/bind.js +function bind(fn2, thisArg) { + return function wrap() { + return fn2.apply(thisArg, arguments); + }; +} + +// node_modules/axios/lib/utils.js +var { toString } = Object.prototype; +var { getPrototypeOf } = Object; +var { iterator, toStringTag } = Symbol; +var kindOf = /* @__PURE__ */ ((cache) => (thing) => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(/* @__PURE__ */ Object.create(null)); +var kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type; +}; +var typeOfTest = (type) => (thing) => typeof thing === type; +var { isArray } = Array; +var isUndefined = typeOfTest("undefined"); +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); +} +var isArrayBuffer = kindOfTest("ArrayBuffer"); +function isArrayBufferView(val) { + let result; + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + result = ArrayBuffer.isView(val); + } else { + result = val && val.buffer && isArrayBuffer(val.buffer); + } + return result; +} +var isString = typeOfTest("string"); +var isFunction = typeOfTest("function"); +var isNumber = typeOfTest("number"); +var isObject = (thing) => thing !== null && typeof thing === "object"; +var isBoolean = (thing) => thing === true || thing === false; +var isPlainObject = (val) => { + if (kindOf(val) !== "object") { + return false; + } + const prototype3 = getPrototypeOf(val); + return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(toStringTag in val) && !(iterator in val); +}; +var isDate = kindOfTest("Date"); +var isFile = kindOfTest("File"); +var isBlob = kindOfTest("Blob"); +var isFileList = kindOfTest("FileList"); +var isStream = (val) => isObject(val) && isFunction(val.pipe); +var isFormData = (thing) => { + let kind; + return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance + kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]")); +}; +var isURLSearchParams = kindOfTest("URLSearchParams"); +var [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest); +var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); +function forEach(obj, fn2, { allOwnKeys = false } = {}) { + if (obj === null || typeof obj === "undefined") { + return; + } + let i; + let l; + if (typeof obj !== "object") { + obj = [obj]; + } + if (isArray(obj)) { + for (i = 0, l = obj.length; i < l; i++) { + fn2.call(null, obj[i], i, obj); + } + } else { + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + fn2.call(null, obj[key], key, obj); + } + } +} +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; +} +var _global = (() => { + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; +})(); +var isContextDefined = (context) => !isUndefined(context) && context !== _global; +function merge() { + const { caseless } = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; +} +var extend = (a, b2, thisArg, { allOwnKeys } = {}) => { + forEach(b2, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, { allOwnKeys }); + return a; +}; +var stripBOM = (content) => { + if (content.charCodeAt(0) === 65279) { + content = content.slice(1); + } + return content; +}; +var inherits = (constructor, superConstructor, props, descriptors2) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors2); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, "super", { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +}; +var toFlatObject = (sourceObj, destObj, filter2, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + destObj = destObj || {}; + if (sourceObj == null) return destObj; + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter2 !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype); + return destObj; +}; +var endsWith = (str, searchString, position) => { + str = String(str); + if (position === void 0 || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +}; +var toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +}; +var isTypedArray = /* @__PURE__ */ ((TypedArray) => { + return (thing) => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); +var forEachEntry = (obj, fn2) => { + const generator = obj && obj[iterator]; + const _iterator = generator.call(obj); + let result; + while ((result = _iterator.next()) && !result.done) { + const pair = result.value; + fn2.call(obj, pair[0], pair[1]); + } +}; +var matchAll = (regExp, str) => { + let matches; + const arr = []; + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + return arr; +}; +var isHTMLForm = kindOfTest("HTMLFormElement"); +var toCamelCase = (str) => { + return str.toLowerCase().replace( + /[-_\s]([a-z\d])(\w*)/g, + function replacer(m2, p1, p2) { + return p1.toUpperCase() + p2; + } + ); +}; +var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype); +var isRegExp = kindOfTest("RegExp"); +var reduceDescriptors = (obj, reducer) => { + const descriptors2 = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + forEach(descriptors2, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + Object.defineProperties(obj, reducedDescriptors); +}; +var freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) { + return false; + } + const value = obj[name]; + if (!isFunction(value)) return; + descriptor.enumerable = false; + if ("writable" in descriptor) { + descriptor.writable = false; + return; + } + if (!descriptor.set) { + descriptor.set = () => { + throw Error("Can not rewrite read-only method '" + name + "'"); + }; + } + }); +}; +var toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + const define2 = (arr) => { + arr.forEach((value) => { + obj[value] = true; + }); + }; + isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); + return obj; +}; +var noop = () => { +}; +var toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; +}; +function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]); +} +var toJSONObject = (obj) => { + const stack = new Array(10); + const visit = (source, i) => { + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + if (!("toJSON" in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + stack[i] = void 0; + return target; + } + } + return source; + }; + return visit(obj, 0); +}; +var isAsyncFn = kindOfTest("AsyncFunction"); +var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); +var _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener("message", ({ source, data }) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + }; + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); +})( + typeof setImmediate === "function", + isFunction(_global.postMessage) +); +var asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate; +var isIterable = (thing) => thing != null && isFunction(thing[iterator]); +var utils_default = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, + // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap, + isIterable +}; + +// node_modules/axios/lib/core/AxiosError.js +function AxiosError(message, code, config3, request, response) { + Error.call(this); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.message = message; + this.name = "AxiosError"; + code && (this.code = code); + config3 && (this.config = config3); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; + } +} +utils_default.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils_default.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } +}); +var prototype = AxiosError.prototype; +var descriptors = {}; +[ + "ERR_BAD_OPTION_VALUE", + "ERR_BAD_OPTION", + "ECONNABORTED", + "ETIMEDOUT", + "ERR_NETWORK", + "ERR_FR_TOO_MANY_REDIRECTS", + "ERR_DEPRECATED", + "ERR_BAD_RESPONSE", + "ERR_BAD_REQUEST", + "ERR_CANCELED", + "ERR_NOT_SUPPORT", + "ERR_INVALID_URL" + // eslint-disable-next-line func-names +].forEach((code) => { + descriptors[code] = { value: code }; +}); +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(prototype, "isAxiosError", { value: true }); +AxiosError.from = (error, code, config3, request, response, customProps) => { + const axiosError = Object.create(prototype); + utils_default.toFlatObject(error, axiosError, function filter2(obj) { + return obj !== Error.prototype; + }, (prop) => { + return prop !== "isAxiosError"; + }); + AxiosError.call(axiosError, error.message, code, config3, request, response); + axiosError.cause = error; + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; +}; +var AxiosError_default = AxiosError; + +// node_modules/axios/lib/platform/node/classes/FormData.js +var import_form_data = __toESM(require_form_data(), 1); +var FormData_default = import_form_data.default; + +// node_modules/axios/lib/helpers/toFormData.js +function isVisitable(thing) { + return utils_default.isPlainObject(thing) || utils_default.isArray(thing); +} +function removeBrackets(key) { + return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key; +} +function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + token = removeBrackets(token); + return !dots && i ? "[" + token + "]" : token; + }).join(dots ? "." : ""); +} +function isFlatArray(arr) { + return utils_default.isArray(arr) && !arr.some(isVisitable); +} +var predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); +function toFormData(obj, formData, options) { + if (!utils_default.isObject(obj)) { + throw new TypeError("target must be an object"); + } + formData = formData || new (FormData_default || FormData)(); + options = utils_default.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + return !utils_default.isUndefined(source[option]); + }); + const metaTokens = options.metaTokens; + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; + const useBlob = _Blob && utils_default.isSpecCompliantForm(formData); + if (!utils_default.isFunction(visitor)) { + throw new TypeError("visitor must be a function"); + } + function convertValue(value) { + if (value === null) return ""; + if (utils_default.isDate(value)) { + return value.toISOString(); + } + if (!useBlob && utils_default.isBlob(value)) { + throw new AxiosError_default("Blob is not supported. Use a Buffer instead."); + } + if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) { + return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); + } + return value; + } + function defaultVisitor(value, key, path) { + let arr = value; + if (value && !path && typeof value === "object") { + if (utils_default.endsWith(key, "{}")) { + key = metaTokens ? key : key.slice(0, -2); + value = JSON.stringify(value); + } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) { + key = removeBrackets(key); + arr.forEach(function each(el2, index2) { + !(utils_default.isUndefined(el2) || el2 === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index2, dots) : indexes === null ? key : key + "[]", + convertValue(el2) + ); + }); + return false; + } + } + if (isVisitable(value)) { + return true; + } + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; + } + const stack = []; + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + function build(value, path) { + if (utils_default.isUndefined(value)) return; + if (stack.indexOf(value) !== -1) { + throw Error("Circular reference detected in " + path.join(".")); + } + stack.push(value); + utils_default.forEach(value, function each(el2, key) { + const result = !(utils_default.isUndefined(el2) || el2 === null) && visitor.call( + formData, + el2, + utils_default.isString(key) ? key.trim() : key, + path, + exposedHelpers + ); + if (result === true) { + build(el2, path ? path.concat(key) : [key]); + } + }); + stack.pop(); + } + if (!utils_default.isObject(obj)) { + throw new TypeError("data must be an object"); + } + build(obj); + return formData; +} +var toFormData_default = toFormData; + +// node_modules/axios/lib/helpers/AxiosURLSearchParams.js +function encode(str) { + const charMap = { + "!": "%21", + "'": "%27", + "(": "%28", + ")": "%29", + "~": "%7E", + "%20": "+", + "%00": "\0" + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); +} +function AxiosURLSearchParams(params, options) { + this._pairs = []; + params && toFormData_default(params, this, options); +} +var prototype2 = AxiosURLSearchParams.prototype; +prototype2.append = function append(name, value) { + this._pairs.push([name, value]); +}; +prototype2.toString = function toString2(encoder5) { + const _encode = encoder5 ? function(value) { + return encoder5.call(this, value, encode); + } : encode; + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + "=" + _encode(pair[1]); + }, "").join("&"); +}; +var AxiosURLSearchParams_default = AxiosURLSearchParams; + +// node_modules/axios/lib/helpers/buildURL.js +function encode2(val) { + return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); +} +function buildURL(url2, params, options) { + if (!params) { + return url2; + } + const _encode = options && options.encode || encode2; + if (utils_default.isFunction(options)) { + options = { + serialize: options + }; + } + const serializeFn = options && options.serialize; + let serializedParams; + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, options).toString(_encode); + } + if (serializedParams) { + const hashmarkIndex = url2.indexOf("#"); + if (hashmarkIndex !== -1) { + url2 = url2.slice(0, hashmarkIndex); + } + url2 += (url2.indexOf("?") === -1 ? "?" : "&") + serializedParams; + } + return url2; +} + +// node_modules/axios/lib/core/InterceptorManager.js +var InterceptorManager = class { + constructor() { + this.handlers = []; + } + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id2) { + if (this.handlers[id2]) { + this.handlers[id2] = null; + } + } + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn2) { + utils_default.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn2(h); + } + }); + } +}; +var InterceptorManager_default = InterceptorManager; + +// node_modules/axios/lib/defaults/transitional.js +var transitional_default = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}; + +// node_modules/axios/lib/platform/node/index.js +import crypto2 from "crypto"; + +// node_modules/axios/lib/platform/node/classes/URLSearchParams.js +import url from "url"; +var URLSearchParams_default = url.URLSearchParams; + +// node_modules/axios/lib/platform/node/index.js +var ALPHA = "abcdefghijklmnopqrstuvwxyz"; +var DIGIT = "0123456789"; +var ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT +}; +var generateString = (size5 = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ""; + const { length } = alphabet; + const randomValues = new Uint32Array(size5); + crypto2.randomFillSync(randomValues); + for (let i = 0; i < size5; i++) { + str += alphabet[randomValues[i] % length]; + } + return str; +}; +var node_default = { + isNode: true, + classes: { + URLSearchParams: URLSearchParams_default, + FormData: FormData_default, + Blob: typeof Blob !== "undefined" && Blob || null + }, + ALPHABET, + generateString, + protocols: ["http", "https", "file", "data"] +}; + +// node_modules/axios/lib/platform/common/utils.js +var utils_exports = {}; +__export(utils_exports, { + hasBrowserEnv: () => hasBrowserEnv, + hasStandardBrowserEnv: () => hasStandardBrowserEnv, + hasStandardBrowserWebWorkerEnv: () => hasStandardBrowserWebWorkerEnv, + navigator: () => _navigator, + origin: () => origin +}); +var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; +var _navigator = typeof navigator === "object" && navigator || void 0; +var hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0); +var hasStandardBrowserWebWorkerEnv = (() => { + return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; +})(); +var origin = hasBrowserEnv && window.location.href || "http://localhost"; + +// node_modules/axios/lib/platform/index.js +var platform_default = { + ...utils_exports, + ...node_default +}; + +// node_modules/axios/lib/helpers/toURLEncodedForm.js +function toURLEncodedForm(data, options) { + return toFormData_default(data, new platform_default.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform_default.isNode && utils_default.isBuffer(value)) { + this.append(key, value.toString("base64")); + return false; + } + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); +} + +// node_modules/axios/lib/helpers/formDataToJSON.js +function parsePropPath(name) { + return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match) => { + return match[0] === "[]" ? "" : match[1] || match[0]; + }); +} +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} +function formDataToJSON(formData) { + function buildPath(path, value, target, index2) { + let name = path[index2++]; + if (name === "__proto__") return true; + const isNumericKey = Number.isFinite(+name); + const isLast = index2 >= path.length; + name = !name && utils_default.isArray(target) ? target.length : name; + if (isLast) { + if (utils_default.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + return !isNumericKey; + } + if (!target[name] || !utils_default.isObject(target[name])) { + target[name] = []; + } + const result = buildPath(path, value, target[name], index2); + if (result && utils_default.isArray(target[name])) { + target[name] = arrayToObject(target[name]); + } + return !isNumericKey; + } + if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) { + const obj = {}; + utils_default.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + return obj; + } + return null; +} +var formDataToJSON_default = formDataToJSON; + +// node_modules/axios/lib/defaults/index.js +function stringifySafely(rawValue, parser, encoder5) { + if (utils_default.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils_default.trim(rawValue); + } catch (e) { + if (e.name !== "SyntaxError") { + throw e; + } + } + } + return (encoder5 || JSON.stringify)(rawValue); +} +var defaults = { + transitional: transitional_default, + adapter: ["xhr", "http", "fetch"], + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ""; + const hasJSONContentType = contentType.indexOf("application/json") > -1; + const isObjectPayload = utils_default.isObject(data); + if (isObjectPayload && utils_default.isHTMLForm(data)) { + data = new FormData(data); + } + const isFormData2 = utils_default.isFormData(data); + if (isFormData2) { + return hasJSONContentType ? JSON.stringify(formDataToJSON_default(data)) : data; + } + if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data) || utils_default.isReadableStream(data)) { + return data; + } + if (utils_default.isArrayBufferView(data)) { + return data.buffer; + } + if (utils_default.isURLSearchParams(data)) { + headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); + return data.toString(); + } + let isFileList2; + if (isObjectPayload) { + if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + if ((isFileList2 = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { + const _FormData = this.env && this.env.FormData; + return toFormData_default( + isFileList2 ? { "files[]": data } : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + if (isObjectPayload || hasJSONContentType) { + headers.setContentType("application/json", false); + return stringifySafely(data); + } + return data; + }], + transformResponse: [function transformResponse(data) { + const transitional2 = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing; + const JSONRequested = this.responseType === "json"; + if (utils_default.isResponse(data) || utils_default.isReadableStream(data)) { + return data; + } + if (data && utils_default.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { + const silentJSONParsing = transitional2 && transitional2.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === "SyntaxError") { + throw AxiosError_default.from(e, AxiosError_default.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + return data; + }], + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + xsrfCookieName: "XSRF-TOKEN", + xsrfHeaderName: "X-XSRF-TOKEN", + maxContentLength: -1, + maxBodyLength: -1, + env: { + FormData: platform_default.classes.FormData, + Blob: platform_default.classes.Blob + }, + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + headers: { + common: { + "Accept": "application/json, text/plain, */*", + "Content-Type": void 0 + } + } +}; +utils_default.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { + defaults.headers[method] = {}; +}); +var defaults_default = defaults; + +// node_modules/axios/lib/helpers/parseHeaders.js +var ignoreDuplicateOf = utils_default.toObjectSet([ + "age", + "authorization", + "content-length", + "content-type", + "etag", + "expires", + "from", + "host", + "if-modified-since", + "if-unmodified-since", + "last-modified", + "location", + "max-forwards", + "proxy-authorization", + "referer", + "retry-after", + "user-agent" +]); +var parseHeaders_default = (rawHeaders) => { + const parsed = {}; + let key; + let val; + let i; + rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { + i = line.indexOf(":"); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + if (!key || parsed[key] && ignoreDuplicateOf[key]) { + return; + } + if (key === "set-cookie") { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; + } + }); + return parsed; +}; + +// node_modules/axios/lib/core/AxiosHeaders.js +var $internals = Symbol("internals"); +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + return utils_default.isArray(value) ? value.map(normalizeValue) : String(value); +} +function parseTokens(str) { + const tokens = /* @__PURE__ */ Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + while (match = tokensRE.exec(str)) { + tokens[match[1]] = match[2]; + } + return tokens; +} +var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); +function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) { + if (utils_default.isFunction(filter2)) { + return filter2.call(this, value, header); + } + if (isHeaderNameFilter) { + value = header; + } + if (!utils_default.isString(value)) return; + if (utils_default.isString(filter2)) { + return value.indexOf(filter2) !== -1; + } + if (utils_default.isRegExp(filter2)) { + return filter2.test(value); + } +} +function formatHeader(header) { + return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str) => { + return char.toUpperCase() + str; + }); +} +function buildAccessors(obj, header) { + const accessorName = utils_default.toCamelCase(" " + header); + ["get", "set", "has"].forEach((methodName) => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); +} +var AxiosHeaders = class { + constructor(headers) { + headers && this.set(headers); + } + set(header, valueOrRewrite, rewrite) { + const self2 = this; + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + if (!lHeader) { + throw new Error("header name must be a non-empty string"); + } + const key = utils_default.findKey(self2, lHeader); + if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { + self2[key || _header] = normalizeValue(_value); + } + } + const setHeaders = (headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + if (utils_default.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders_default(header), valueOrRewrite); + } else if (utils_default.isObject(header) && utils_default.isIterable(header)) { + let obj = {}, dest, key; + for (const entry of header) { + if (!utils_default.isArray(entry)) { + throw TypeError("Object iterator must return a key-value pair"); + } + obj[key = entry[0]] = (dest = obj[key]) ? utils_default.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1]; + } + setHeaders(obj, valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + return this; + } + get(header, parser) { + header = normalizeHeader(header); + if (header) { + const key = utils_default.findKey(this, header); + if (key) { + const value = this[key]; + if (!parser) { + return value; + } + if (parser === true) { + return parseTokens(value); + } + if (utils_default.isFunction(parser)) { + return parser.call(this, value, key); + } + if (utils_default.isRegExp(parser)) { + return parser.exec(value); + } + throw new TypeError("parser must be boolean|regexp|function"); + } + } + } + has(header, matcher) { + header = normalizeHeader(header); + if (header) { + const key = utils_default.findKey(this, header); + return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + return false; + } + delete(header, matcher) { + const self2 = this; + let deleted = false; + function deleteHeader(_header) { + _header = normalizeHeader(_header); + if (_header) { + const key = utils_default.findKey(self2, _header); + if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { + delete self2[key]; + deleted = true; + } + } + } + if (utils_default.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + return deleted; + } + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + while (i--) { + const key = keys[i]; + if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + return deleted; + } + normalize(format) { + const self2 = this; + const headers = {}; + utils_default.forEach(this, (value, header) => { + const key = utils_default.findKey(headers, header); + if (key) { + self2[key] = normalizeValue(value); + delete self2[header]; + return; + } + const normalized = format ? formatHeader(header) : String(header).trim(); + if (normalized !== header) { + delete self2[header]; + } + self2[normalized] = normalizeValue(value); + headers[normalized] = true; + }); + return this; + } + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + toJSON(asStrings) { + const obj = /* @__PURE__ */ Object.create(null); + utils_default.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value); + }); + return obj; + } + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); + } + getSetCookie() { + return this.get("set-cookie") || []; + } + get [Symbol.toStringTag]() { + return "AxiosHeaders"; + } + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + static concat(first, ...targets) { + const computed = new this(first); + targets.forEach((target) => computed.set(target)); + return computed; + } + static accessor(header) { + const internals = this[$internals] = this[$internals] = { + accessors: {} + }; + const accessors = internals.accessors; + const prototype3 = this.prototype; + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + if (!accessors[lHeader]) { + buildAccessors(prototype3, _header); + accessors[lHeader] = true; + } + } + utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + return this; + } +}; +AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); +utils_default.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + }; +}); +utils_default.freezeMethods(AxiosHeaders); +var AxiosHeaders_default = AxiosHeaders; + +// node_modules/axios/lib/core/transformData.js +function transformData(fns, response) { + const config3 = this || defaults_default; + const context = response || config3; + const headers = AxiosHeaders_default.from(context.headers); + let data = context.data; + utils_default.forEach(fns, function transform(fn2) { + data = fn2.call(config3, data, headers.normalize(), response ? response.status : void 0); + }); + headers.normalize(); + return data; +} + +// node_modules/axios/lib/cancel/isCancel.js +function isCancel(value) { + return !!(value && value.__CANCEL__); +} + +// node_modules/axios/lib/cancel/CanceledError.js +function CanceledError(message, config3, request) { + AxiosError_default.call(this, message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config3, request); + this.name = "CanceledError"; +} +utils_default.inherits(CanceledError, AxiosError_default, { + __CANCEL__: true +}); +var CanceledError_default = CanceledError; + +// node_modules/axios/lib/core/settle.js +function settle(resolve, reject, response) { + const validateStatus2 = response.config.validateStatus; + if (!response.status || !validateStatus2 || validateStatus2(response.status)) { + resolve(response); + } else { + reject(new AxiosError_default( + "Request failed with status code " + response.status, + [AxiosError_default.ERR_BAD_REQUEST, AxiosError_default.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +} + +// node_modules/axios/lib/helpers/isAbsoluteURL.js +function isAbsoluteURL(url2) { + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url2); +} + +// node_modules/axios/lib/helpers/combineURLs.js +function combineURLs(baseURL, relativeURL) { + return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; +} + +// node_modules/axios/lib/core/buildFullPath.js +function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) { + let isRelativeUrl = !isAbsoluteURL(requestedURL); + if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +} + +// node_modules/axios/lib/adapters/http.js +var import_proxy_from_env = __toESM(require_proxy_from_env(), 1); +var import_follow_redirects = __toESM(require_follow_redirects(), 1); +import http from "http"; +import https from "https"; +import util2 from "util"; +import zlib from "zlib"; + +// node_modules/axios/lib/env/data.js +var VERSION = "1.9.0"; + +// node_modules/axios/lib/helpers/parseProtocol.js +function parseProtocol(url2) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url2); + return match && match[1] || ""; +} + +// node_modules/axios/lib/helpers/fromDataURI.js +var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; +function fromDataURI(uri, asBlob, options) { + const _Blob = options && options.Blob || platform_default.classes.Blob; + const protocol = parseProtocol(uri); + if (asBlob === void 0 && _Blob) { + asBlob = true; + } + if (protocol === "data") { + uri = protocol.length ? uri.slice(protocol.length + 1) : uri; + const match = DATA_URL_PATTERN.exec(uri); + if (!match) { + throw new AxiosError_default("Invalid URL", AxiosError_default.ERR_INVALID_URL); + } + const mime = match[1]; + const isBase64 = match[2]; + const body = match[3]; + const buffer2 = Buffer.from(decodeURIComponent(body), isBase64 ? "base64" : "utf8"); + if (asBlob) { + if (!_Blob) { + throw new AxiosError_default("Blob is not supported", AxiosError_default.ERR_NOT_SUPPORT); + } + return new _Blob([buffer2], { type: mime }); + } + return buffer2; + } + throw new AxiosError_default("Unsupported protocol " + protocol, AxiosError_default.ERR_NOT_SUPPORT); +} + +// node_modules/axios/lib/adapters/http.js +import stream3 from "stream"; + +// node_modules/axios/lib/helpers/AxiosTransformStream.js +import stream from "stream"; +var kInternals = Symbol("internals"); +var AxiosTransformStream = class extends stream.Transform { + constructor(options) { + options = utils_default.toFlatObject(options, { + maxRate: 0, + chunkSize: 64 * 1024, + minChunkSize: 100, + timeWindow: 500, + ticksRate: 2, + samplesCount: 15 + }, null, (prop, source) => { + return !utils_default.isUndefined(source[prop]); + }); + super({ + readableHighWaterMark: options.chunkSize + }); + const internals = this[kInternals] = { + timeWindow: options.timeWindow, + chunkSize: options.chunkSize, + maxRate: options.maxRate, + minChunkSize: options.minChunkSize, + bytesSeen: 0, + isCaptured: false, + notifiedBytesLoaded: 0, + ts: Date.now(), + bytes: 0, + onReadCallback: null + }; + this.on("newListener", (event) => { + if (event === "progress") { + if (!internals.isCaptured) { + internals.isCaptured = true; + } + } + }); + } + _read(size5) { + const internals = this[kInternals]; + if (internals.onReadCallback) { + internals.onReadCallback(); + } + return super._read(size5); + } + _transform(chunk, encoding, callback) { + const internals = this[kInternals]; + const maxRate = internals.maxRate; + const readableHighWaterMark = this.readableHighWaterMark; + const timeWindow = internals.timeWindow; + const divider = 1e3 / timeWindow; + const bytesThreshold = maxRate / divider; + const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; + const pushChunk = (_chunk, _callback) => { + const bytes = Buffer.byteLength(_chunk); + internals.bytesSeen += bytes; + internals.bytes += bytes; + internals.isCaptured && this.emit("progress", internals.bytesSeen); + if (this.push(_chunk)) { + process.nextTick(_callback); + } else { + internals.onReadCallback = () => { + internals.onReadCallback = null; + process.nextTick(_callback); + }; + } + }; + const transformChunk = (_chunk, _callback) => { + const chunkSize = Buffer.byteLength(_chunk); + let chunkRemainder = null; + let maxChunkSize = readableHighWaterMark; + let bytesLeft; + let passed = 0; + if (maxRate) { + const now = Date.now(); + if (!internals.ts || (passed = now - internals.ts) >= timeWindow) { + internals.ts = now; + bytesLeft = bytesThreshold - internals.bytes; + internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; + passed = 0; + } + bytesLeft = bytesThreshold - internals.bytes; + } + if (maxRate) { + if (bytesLeft <= 0) { + return setTimeout(() => { + _callback(null, _chunk); + }, timeWindow - passed); + } + if (bytesLeft < maxChunkSize) { + maxChunkSize = bytesLeft; + } + } + if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) { + chunkRemainder = _chunk.subarray(maxChunkSize); + _chunk = _chunk.subarray(0, maxChunkSize); + } + pushChunk(_chunk, chunkRemainder ? () => { + process.nextTick(_callback, null, chunkRemainder); + } : _callback); + }; + transformChunk(chunk, function transformNextChunk(err, _chunk) { + if (err) { + return callback(err); + } + if (_chunk) { + transformChunk(_chunk, transformNextChunk); + } else { + callback(null); + } + }); + } +}; +var AxiosTransformStream_default = AxiosTransformStream; + +// node_modules/axios/lib/adapters/http.js +import { EventEmitter } from "events"; + +// node_modules/axios/lib/helpers/formDataToStream.js +import util from "util"; +import { Readable } from "stream"; + +// node_modules/axios/lib/helpers/readBlob.js +var { asyncIterator } = Symbol; +var readBlob = async function* (blob) { + if (blob.stream) { + yield* blob.stream(); + } else if (blob.arrayBuffer) { + yield await blob.arrayBuffer(); + } else if (blob[asyncIterator]) { + yield* blob[asyncIterator](); + } else { + yield blob; + } +}; +var readBlob_default = readBlob; + +// node_modules/axios/lib/helpers/formDataToStream.js +var BOUNDARY_ALPHABET = platform_default.ALPHABET.ALPHA_DIGIT + "-_"; +var textEncoder = typeof TextEncoder === "function" ? new TextEncoder() : new util.TextEncoder(); +var CRLF = "\r\n"; +var CRLF_BYTES = textEncoder.encode(CRLF); +var CRLF_BYTES_COUNT = 2; +var FormDataPart = class { + constructor(name, value) { + const { escapeName } = this.constructor; + const isStringValue = utils_default.isString(value); + let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF}`; + if (isStringValue) { + value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); + } else { + headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; + } + this.headers = textEncoder.encode(headers + CRLF); + this.contentLength = isStringValue ? value.byteLength : value.size; + this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; + this.name = name; + this.value = value; + } + async *encode() { + yield this.headers; + const { value } = this; + if (utils_default.isTypedArray(value)) { + yield value; + } else { + yield* readBlob_default(value); + } + yield CRLF_BYTES; + } + static escapeName(name) { + return String(name).replace(/[\r\n"]/g, (match) => ({ + "\r": "%0D", + "\n": "%0A", + '"': "%22" + })[match]); + } +}; +var formDataToStream = (form, headersHandler, options) => { + const { + tag = "form-data-boundary", + size: size5 = 25, + boundary = tag + "-" + platform_default.generateString(size5, BOUNDARY_ALPHABET) + } = options || {}; + if (!utils_default.isFormData(form)) { + throw TypeError("FormData instance required"); + } + if (boundary.length < 1 || boundary.length > 70) { + throw Error("boundary must be 10-70 characters long"); + } + const boundaryBytes = textEncoder.encode("--" + boundary + CRLF); + const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF); + let contentLength = footerBytes.byteLength; + const parts = Array.from(form.entries()).map(([name, value]) => { + const part = new FormDataPart(name, value); + contentLength += part.size; + return part; + }); + contentLength += boundaryBytes.byteLength * parts.length; + contentLength = utils_default.toFiniteNumber(contentLength); + const computedHeaders = { + "Content-Type": `multipart/form-data; boundary=${boundary}` + }; + if (Number.isFinite(contentLength)) { + computedHeaders["Content-Length"] = contentLength; + } + headersHandler && headersHandler(computedHeaders); + return Readable.from(async function* () { + for (const part of parts) { + yield boundaryBytes; + yield* part.encode(); + } + yield footerBytes; + }()); +}; +var formDataToStream_default = formDataToStream; + +// node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js +import stream2 from "stream"; +var ZlibHeaderTransformStream = class extends stream2.Transform { + __transform(chunk, encoding, callback) { + this.push(chunk); + callback(); + } + _transform(chunk, encoding, callback) { + if (chunk.length !== 0) { + this._transform = this.__transform; + if (chunk[0] !== 120) { + const header = Buffer.alloc(2); + header[0] = 120; + header[1] = 156; + this.push(header, encoding); + } + } + this.__transform(chunk, encoding, callback); + } +}; +var ZlibHeaderTransformStream_default = ZlibHeaderTransformStream; + +// node_modules/axios/lib/helpers/callbackify.js +var callbackify = (fn2, reducer) => { + return utils_default.isAsyncFn(fn2) ? function(...args) { + const cb = args.pop(); + fn2.apply(this, args).then((value) => { + try { + reducer ? cb(null, ...reducer(value)) : cb(null, value); + } catch (err) { + cb(err); + } + }, cb); + } : fn2; +}; +var callbackify_default = callbackify; + +// node_modules/axios/lib/helpers/speedometer.js +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + min = min !== void 0 ? min : 1e3; + return function push(chunkLength) { + const now = Date.now(); + const startedAt = timestamps[tail]; + if (!firstSampleTS) { + firstSampleTS = now; + } + bytes[head] = chunkLength; + timestamps[head] = now; + let i = tail; + let bytesCount = 0; + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + head = (head + 1) % samplesCount; + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + if (now - firstSampleTS < min) { + return; + } + const passed = startedAt && now - startedAt; + return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; + }; +} +var speedometer_default = speedometer; + +// node_modules/axios/lib/helpers/throttle.js +function throttle(fn2, freq) { + let timestamp = 0; + let threshold = 1e3 / freq; + let lastArgs; + let timer; + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn2.apply(null, args); + }; + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if (passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs); + }, threshold - passed); + } + } + }; + const flush = () => lastArgs && invoke(lastArgs); + return [throttled, flush]; +} +var throttle_default = throttle; + +// node_modules/axios/lib/helpers/progressEventReducer.js +var progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer_default(50, 250); + return throttle_default((e) => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : void 0; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange2 = loaded <= total; + bytesNotified = loaded; + const data = { + loaded, + total, + progress: total ? loaded / total : void 0, + bytes: progressBytes, + rate: rate ? rate : void 0, + estimated: rate && total && inRange2 ? (total - loaded) / rate : void 0, + event: e, + lengthComputable: total != null, + [isDownloadStream ? "download" : "upload"]: true + }; + listener(data); + }, freq); +}; +var progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; +}; +var asyncDecorator = (fn2) => (...args) => utils_default.asap(() => fn2(...args)); + +// node_modules/axios/lib/adapters/http.js +var zlibOptions = { + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH +}; +var brotliOptions = { + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH +}; +var isBrotliSupported = utils_default.isFunction(zlib.createBrotliDecompress); +var { http: httpFollow, https: httpsFollow } = import_follow_redirects.default; +var isHttps = /https:?/; +var supportedProtocols = platform_default.protocols.map((protocol) => { + return protocol + ":"; +}); +var flushOnFinish = (stream4, [throttled, flush]) => { + stream4.on("end", flush).on("error", flush); + return throttled; +}; +function dispatchBeforeRedirect(options, responseDetails) { + if (options.beforeRedirects.proxy) { + options.beforeRedirects.proxy(options); + } + if (options.beforeRedirects.config) { + options.beforeRedirects.config(options, responseDetails); + } +} +function setProxy(options, configProxy, location) { + let proxy = configProxy; + if (!proxy && proxy !== false) { + const proxyUrl = import_proxy_from_env.default.getProxyForUrl(location); + if (proxyUrl) { + proxy = new URL(proxyUrl); + } + } + if (proxy) { + if (proxy.username) { + proxy.auth = (proxy.username || "") + ":" + (proxy.password || ""); + } + if (proxy.auth) { + if (proxy.auth.username || proxy.auth.password) { + proxy.auth = (proxy.auth.username || "") + ":" + (proxy.auth.password || ""); + } + const base64 = Buffer.from(proxy.auth, "utf8").toString("base64"); + options.headers["Proxy-Authorization"] = "Basic " + base64; + } + options.headers.host = options.hostname + (options.port ? ":" + options.port : ""); + const proxyHost = proxy.hostname || proxy.host; + options.hostname = proxyHost; + options.host = proxyHost; + options.port = proxy.port; + options.path = location; + if (proxy.protocol) { + options.protocol = proxy.protocol.includes(":") ? proxy.protocol : `${proxy.protocol}:`; + } + } + options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { + setProxy(redirectOptions, configProxy, redirectOptions.href); + }; +} +var isHttpAdapterSupported = typeof process !== "undefined" && utils_default.kindOf(process) === "process"; +var wrapAsync = (asyncExecutor) => { + return new Promise((resolve, reject) => { + let onDone; + let isDone; + const done = (value, isRejected) => { + if (isDone) return; + isDone = true; + onDone && onDone(value, isRejected); + }; + const _resolve = (value) => { + done(value); + resolve(value); + }; + const _reject = (reason) => { + done(reason, true); + reject(reason); + }; + asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject); + }); +}; +var resolveFamily = ({ address, family }) => { + if (!utils_default.isString(address)) { + throw TypeError("address must be a string"); + } + return { + address, + family: family || (address.indexOf(".") < 0 ? 6 : 4) + }; +}; +var buildAddressEntry = (address, family) => resolveFamily(utils_default.isObject(address) ? address : { address, family }); +var http_default = isHttpAdapterSupported && function httpAdapter(config3) { + return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { + let { data, lookup, family } = config3; + const { responseType, responseEncoding } = config3; + const method = config3.method.toUpperCase(); + let isDone; + let rejected = false; + let req; + if (lookup) { + const _lookup = callbackify_default(lookup, (value) => utils_default.isArray(value) ? value : [value]); + lookup = (hostname, opt, cb) => { + _lookup(hostname, opt, (err, arg0, arg1) => { + if (err) { + return cb(err); + } + const addresses = utils_default.isArray(arg0) ? arg0.map((addr) => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; + opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); + }); + }; + } + const emitter = new EventEmitter(); + const onFinished = () => { + if (config3.cancelToken) { + config3.cancelToken.unsubscribe(abort); + } + if (config3.signal) { + config3.signal.removeEventListener("abort", abort); + } + emitter.removeAllListeners(); + }; + onDone((value, isRejected) => { + isDone = true; + if (isRejected) { + rejected = true; + onFinished(); + } + }); + function abort(reason) { + emitter.emit("abort", !reason || reason.type ? new CanceledError_default(null, config3, req) : reason); + } + emitter.once("abort", reject); + if (config3.cancelToken || config3.signal) { + config3.cancelToken && config3.cancelToken.subscribe(abort); + if (config3.signal) { + config3.signal.aborted ? abort() : config3.signal.addEventListener("abort", abort); + } + } + const fullPath = buildFullPath(config3.baseURL, config3.url, config3.allowAbsoluteUrls); + const parsed = new URL(fullPath, platform_default.hasBrowserEnv ? platform_default.origin : void 0); + const protocol = parsed.protocol || supportedProtocols[0]; + if (protocol === "data:") { + let convertedData; + if (method !== "GET") { + return settle(resolve, reject, { + status: 405, + statusText: "method not allowed", + headers: {}, + config: config3 + }); + } + try { + convertedData = fromDataURI(config3.url, responseType === "blob", { + Blob: config3.env && config3.env.Blob + }); + } catch (err) { + throw AxiosError_default.from(err, AxiosError_default.ERR_BAD_REQUEST, config3); + } + if (responseType === "text") { + convertedData = convertedData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === "utf8") { + convertedData = utils_default.stripBOM(convertedData); + } + } else if (responseType === "stream") { + convertedData = stream3.Readable.from(convertedData); + } + return settle(resolve, reject, { + data: convertedData, + status: 200, + statusText: "OK", + headers: new AxiosHeaders_default(), + config: config3 + }); + } + if (supportedProtocols.indexOf(protocol) === -1) { + return reject(new AxiosError_default( + "Unsupported protocol " + protocol, + AxiosError_default.ERR_BAD_REQUEST, + config3 + )); + } + const headers = AxiosHeaders_default.from(config3.headers).normalize(); + headers.set("User-Agent", "axios/" + VERSION, false); + const { onUploadProgress, onDownloadProgress } = config3; + const maxRate = config3.maxRate; + let maxUploadRate = void 0; + let maxDownloadRate = void 0; + if (utils_default.isSpecCompliantForm(data)) { + const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); + data = formDataToStream_default(data, (formHeaders) => { + headers.set(formHeaders); + }, { + tag: `axios-${VERSION}-boundary`, + boundary: userBoundary && userBoundary[1] || void 0 + }); + } else if (utils_default.isFormData(data) && utils_default.isFunction(data.getHeaders)) { + headers.set(data.getHeaders()); + if (!headers.hasContentLength()) { + try { + const knownLength = await util2.promisify(data.getLength).call(data); + Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); + } catch (e) { + } + } + } else if (utils_default.isBlob(data) || utils_default.isFile(data)) { + data.size && headers.setContentType(data.type || "application/octet-stream"); + headers.setContentLength(data.size || 0); + data = stream3.Readable.from(readBlob_default(data)); + } else if (data && !utils_default.isStream(data)) { + if (Buffer.isBuffer(data)) { + } else if (utils_default.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils_default.isString(data)) { + data = Buffer.from(data, "utf-8"); + } else { + return reject(new AxiosError_default( + "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream", + AxiosError_default.ERR_BAD_REQUEST, + config3 + )); + } + headers.setContentLength(data.length, false); + if (config3.maxBodyLength > -1 && data.length > config3.maxBodyLength) { + return reject(new AxiosError_default( + "Request body larger than maxBodyLength limit", + AxiosError_default.ERR_BAD_REQUEST, + config3 + )); + } + } + const contentLength = utils_default.toFiniteNumber(headers.getContentLength()); + if (utils_default.isArray(maxRate)) { + maxUploadRate = maxRate[0]; + maxDownloadRate = maxRate[1]; + } else { + maxUploadRate = maxDownloadRate = maxRate; + } + if (data && (onUploadProgress || maxUploadRate)) { + if (!utils_default.isStream(data)) { + data = stream3.Readable.from(data, { objectMode: false }); + } + data = stream3.pipeline([data, new AxiosTransformStream_default({ + maxRate: utils_default.toFiniteNumber(maxUploadRate) + })], utils_default.noop); + onUploadProgress && data.on("progress", flushOnFinish( + data, + progressEventDecorator( + contentLength, + progressEventReducer(asyncDecorator(onUploadProgress), false, 3) + ) + )); + } + let auth = void 0; + if (config3.auth) { + const username = config3.auth.username || ""; + const password = config3.auth.password || ""; + auth = username + ":" + password; + } + if (!auth && parsed.username) { + const urlUsername = parsed.username; + const urlPassword = parsed.password; + auth = urlUsername + ":" + urlPassword; + } + auth && headers.delete("authorization"); + let path; + try { + path = buildURL( + parsed.pathname + parsed.search, + config3.params, + config3.paramsSerializer + ).replace(/^\?/, ""); + } catch (err) { + const customErr = new Error(err.message); + customErr.config = config3; + customErr.url = config3.url; + customErr.exists = true; + return reject(customErr); + } + headers.set( + "Accept-Encoding", + "gzip, compress, deflate" + (isBrotliSupported ? ", br" : ""), + false + ); + const options = { + path, + method, + headers: headers.toJSON(), + agents: { http: config3.httpAgent, https: config3.httpsAgent }, + auth, + protocol, + family, + beforeRedirect: dispatchBeforeRedirect, + beforeRedirects: {} + }; + !utils_default.isUndefined(lookup) && (options.lookup = lookup); + if (config3.socketPath) { + options.socketPath = config3.socketPath; + } else { + options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; + options.port = parsed.port; + setProxy(options, config3.proxy, protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options.path); + } + let transport; + const isHttpsRequest = isHttps.test(options.protocol); + options.agent = isHttpsRequest ? config3.httpsAgent : config3.httpAgent; + if (config3.transport) { + transport = config3.transport; + } else if (config3.maxRedirects === 0) { + transport = isHttpsRequest ? https : http; + } else { + if (config3.maxRedirects) { + options.maxRedirects = config3.maxRedirects; + } + if (config3.beforeRedirect) { + options.beforeRedirects.config = config3.beforeRedirect; + } + transport = isHttpsRequest ? httpsFollow : httpFollow; + } + if (config3.maxBodyLength > -1) { + options.maxBodyLength = config3.maxBodyLength; + } else { + options.maxBodyLength = Infinity; + } + if (config3.insecureHTTPParser) { + options.insecureHTTPParser = config3.insecureHTTPParser; + } + req = transport.request(options, function handleResponse(res) { + if (req.destroyed) return; + const streams = [res]; + const responseLength = +res.headers["content-length"]; + if (onDownloadProgress || maxDownloadRate) { + const transformStream = new AxiosTransformStream_default({ + maxRate: utils_default.toFiniteNumber(maxDownloadRate) + }); + onDownloadProgress && transformStream.on("progress", flushOnFinish( + transformStream, + progressEventDecorator( + responseLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) + ) + )); + streams.push(transformStream); + } + let responseStream = res; + const lastRequest = res.req || req; + if (config3.decompress !== false && res.headers["content-encoding"]) { + if (method === "HEAD" || res.statusCode === 204) { + delete res.headers["content-encoding"]; + } + switch ((res.headers["content-encoding"] || "").toLowerCase()) { + /*eslint default-case:0*/ + case "gzip": + case "x-gzip": + case "compress": + case "x-compress": + streams.push(zlib.createUnzip(zlibOptions)); + delete res.headers["content-encoding"]; + break; + case "deflate": + streams.push(new ZlibHeaderTransformStream_default()); + streams.push(zlib.createUnzip(zlibOptions)); + delete res.headers["content-encoding"]; + break; + case "br": + if (isBrotliSupported) { + streams.push(zlib.createBrotliDecompress(brotliOptions)); + delete res.headers["content-encoding"]; + } + } + } + responseStream = streams.length > 1 ? stream3.pipeline(streams, utils_default.noop) : streams[0]; + const offListeners = stream3.finished(responseStream, () => { + offListeners(); + onFinished(); + }); + const response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: new AxiosHeaders_default(res.headers), + config: config3, + request: lastRequest + }; + if (responseType === "stream") { + response.data = responseStream; + settle(resolve, reject, response); + } else { + const responseBuffer = []; + let totalResponseBytes = 0; + responseStream.on("data", function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; + if (config3.maxContentLength > -1 && totalResponseBytes > config3.maxContentLength) { + rejected = true; + responseStream.destroy(); + reject(new AxiosError_default( + "maxContentLength size of " + config3.maxContentLength + " exceeded", + AxiosError_default.ERR_BAD_RESPONSE, + config3, + lastRequest + )); + } + }); + responseStream.on("aborted", function handlerStreamAborted() { + if (rejected) { + return; + } + const err = new AxiosError_default( + "stream has been aborted", + AxiosError_default.ERR_BAD_RESPONSE, + config3, + lastRequest + ); + responseStream.destroy(err); + reject(err); + }); + responseStream.on("error", function handleStreamError(err) { + if (req.destroyed) return; + reject(AxiosError_default.from(err, null, config3, lastRequest)); + }); + responseStream.on("end", function handleStreamEnd() { + try { + let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (responseType !== "arraybuffer") { + responseData = responseData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === "utf8") { + responseData = utils_default.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + return reject(AxiosError_default.from(err, null, config3, response.request, response)); + } + settle(resolve, reject, response); + }); + } + emitter.once("abort", (err) => { + if (!responseStream.destroyed) { + responseStream.emit("error", err); + responseStream.destroy(); + } + }); + }); + emitter.once("abort", (err) => { + reject(err); + req.destroy(err); + }); + req.on("error", function handleRequestError(err) { + reject(AxiosError_default.from(err, null, config3, req)); + }); + req.on("socket", function handleRequestSocket(socket) { + socket.setKeepAlive(true, 1e3 * 60); + }); + if (config3.timeout) { + const timeout = parseInt(config3.timeout, 10); + if (Number.isNaN(timeout)) { + reject(new AxiosError_default( + "error trying to parse `config.timeout` to int", + AxiosError_default.ERR_BAD_OPTION_VALUE, + config3, + req + )); + return; + } + req.setTimeout(timeout, function handleRequestTimeout() { + if (isDone) return; + let timeoutErrorMessage = config3.timeout ? "timeout of " + config3.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = config3.transitional || transitional_default; + if (config3.timeoutErrorMessage) { + timeoutErrorMessage = config3.timeoutErrorMessage; + } + reject(new AxiosError_default( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, + config3, + req + )); + abort(); + }); + } + if (utils_default.isStream(data)) { + let ended = false; + let errored = false; + data.on("end", () => { + ended = true; + }); + data.once("error", (err) => { + errored = true; + req.destroy(err); + }); + data.on("close", () => { + if (!ended && !errored) { + abort(new CanceledError_default("Request stream has been aborted", config3, req)); + } + }); + data.pipe(req); + } else { + req.end(data); + } + }); +}; + +// node_modules/axios/lib/helpers/isURLSameOrigin.js +var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url2) => { + url2 = new URL(url2, platform_default.origin); + return origin2.protocol === url2.protocol && origin2.host === url2.host && (isMSIE || origin2.port === url2.port); +})( + new URL(platform_default.origin), + platform_default.navigator && /(msie|trident)/i.test(platform_default.navigator.userAgent) +) : () => true; + +// node_modules/axios/lib/helpers/cookies.js +var cookies_default = platform_default.hasStandardBrowserEnv ? ( + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + "=" + encodeURIComponent(value)]; + utils_default.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); + utils_default.isString(path) && cookie.push("path=" + path); + utils_default.isString(domain) && cookie.push("domain=" + domain); + secure === true && cookie.push("secure"); + document.cookie = cookie.join("; "); + }, + read(name) { + const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)")); + return match ? decodeURIComponent(match[3]) : null; + }, + remove(name) { + this.write(name, "", Date.now() - 864e5); + } + } +) : ( + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() { + }, + read() { + return null; + }, + remove() { + } + } +); + +// node_modules/axios/lib/core/mergeConfig.js +var headersToObject = (thing) => thing instanceof AxiosHeaders_default ? { ...thing } : thing; +function mergeConfig(config1, config22) { + config22 = config22 || {}; + const config3 = {}; + function getMergedValue(target, source, prop, caseless) { + if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) { + return utils_default.merge.call({ caseless }, target, source); + } else if (utils_default.isPlainObject(source)) { + return utils_default.merge({}, source); + } else if (utils_default.isArray(source)) { + return source.slice(); + } + return source; + } + function mergeDeepProperties(a, b2, prop, caseless) { + if (!utils_default.isUndefined(b2)) { + return getMergedValue(a, b2, prop, caseless); + } else if (!utils_default.isUndefined(a)) { + return getMergedValue(void 0, a, prop, caseless); + } + } + function valueFromConfig2(a, b2) { + if (!utils_default.isUndefined(b2)) { + return getMergedValue(void 0, b2); + } + } + function defaultToConfig2(a, b2) { + if (!utils_default.isUndefined(b2)) { + return getMergedValue(void 0, b2); + } else if (!utils_default.isUndefined(a)) { + return getMergedValue(void 0, a); + } + } + function mergeDirectKeys(a, b2, prop) { + if (prop in config22) { + return getMergedValue(a, b2); + } else if (prop in config1) { + return getMergedValue(void 0, a); + } + } + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b2, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b2), prop, true) + }; + utils_default.forEach(Object.keys(Object.assign({}, config1, config22)), function computeConfigValue(prop) { + const merge2 = mergeMap[prop] || mergeDeepProperties; + const configValue = merge2(config1[prop], config22[prop], prop); + utils_default.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config3[prop] = configValue); + }); + return config3; +} + +// node_modules/axios/lib/helpers/resolveConfig.js +var resolveConfig_default = (config3) => { + const newConfig = mergeConfig({}, config3); + let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; + newConfig.headers = headers = AxiosHeaders_default.from(headers); + newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config3.params, config3.paramsSerializer); + if (auth) { + headers.set( + "Authorization", + "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : "")) + ); + } + let contentType; + if (utils_default.isFormData(data)) { + if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(void 0); + } else if ((contentType = headers.getContentType()) !== false) { + const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; + headers.setContentType([type || "multipart/form-data", ...tokens].join("; ")); + } + } + if (platform_default.hasStandardBrowserEnv) { + withXSRFToken && utils_default.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin_default(newConfig.url)) { + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies_default.read(xsrfCookieName); + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + return newConfig; +}; + +// node_modules/axios/lib/adapters/xhr.js +var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; +var xhr_default = isXHRAdapterSupported && function(config3) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig_default(config3); + let requestData = _config.data; + const requestHeaders = AxiosHeaders_default.from(_config.headers).normalize(); + let { responseType, onUploadProgress, onDownloadProgress } = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + function done() { + flushUpload && flushUpload(); + flushDownload && flushDownload(); + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + _config.signal && _config.signal.removeEventListener("abort", onCanceled); + } + let request = new XMLHttpRequest(); + request.open(_config.method.toUpperCase(), _config.url, true); + request.timeout = _config.timeout; + function onloadend() { + if (!request) { + return; + } + const responseHeaders = AxiosHeaders_default.from( + "getAllResponseHeaders" in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config3, + request + }; + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + request = null; + } + if ("onloadend" in request) { + request.onloadend = onloadend; + } else { + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { + return; + } + setTimeout(onloadend); + }; + } + request.onabort = function handleAbort() { + if (!request) { + return; + } + reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config3, request)); + request = null; + }; + request.onerror = function handleError() { + reject(new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config3, request)); + request = null; + }; + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = _config.transitional || transitional_default; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new AxiosError_default( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, + config3, + request + )); + request = null; + }; + requestData === void 0 && requestHeaders.setContentType(null); + if ("setRequestHeader" in request) { + utils_default.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + if (!utils_default.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + if (responseType && responseType !== "json") { + request.responseType = _config.responseType; + } + if (onDownloadProgress) { + [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true); + request.addEventListener("progress", downloadThrottled); + } + if (onUploadProgress && request.upload) { + [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress); + request.upload.addEventListener("progress", uploadThrottled); + request.upload.addEventListener("loadend", flushUpload); + } + if (_config.cancelToken || _config.signal) { + onCanceled = (cancel) => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError_default(null, config3, request) : cancel); + request.abort(); + request = null; + }; + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled); + } + } + const protocol = parseProtocol(_config.url); + if (protocol && platform_default.protocols.indexOf(protocol) === -1) { + reject(new AxiosError_default("Unsupported protocol " + protocol + ":", AxiosError_default.ERR_BAD_REQUEST, config3)); + return; + } + request.send(requestData || null); + }); +}; + +// node_modules/axios/lib/helpers/composeSignals.js +var composeSignals = (signals, timeout) => { + const { length } = signals = signals ? signals.filter(Boolean) : []; + if (timeout || length) { + let controller = new AbortController(); + let aborted; + const onabort = function(reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof AxiosError_default ? err : new CanceledError_default(err instanceof Error ? err.message : err)); + } + }; + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new AxiosError_default(`timeout ${timeout} of ms exceeded`, AxiosError_default.ETIMEDOUT)); + }, timeout); + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach((signal2) => { + signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort); + }); + signals = null; + } + }; + signals.forEach((signal2) => signal2.addEventListener("abort", onabort)); + const { signal } = controller; + signal.unsubscribe = () => utils_default.asap(unsubscribe); + return signal; + } +}; +var composeSignals_default = composeSignals; + +// node_modules/axios/lib/helpers/trackStream.js +var streamChunk = function* (chunk, chunkSize) { + let len = chunk.byteLength; + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + let pos = 0; + let end; + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } +}; +var readBytes = async function* (iterable, chunkSize) { + for await (const chunk of readStream(iterable)) { + yield* streamChunk(chunk, chunkSize); + } +}; +var readStream = async function* (stream4) { + if (stream4[Symbol.asyncIterator]) { + yield* stream4; + return; + } + const reader = stream4.getReader(); + try { + for (; ; ) { + const { done, value } = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } +}; +var trackStream = (stream4, chunkSize, onProgress, onFinish) => { + const iterator2 = readBytes(stream4, chunkSize); + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + }; + return new ReadableStream({ + async pull(controller) { + try { + const { done: done2, value } = await iterator2.next(); + if (done2) { + _onFinish(); + controller.close(); + return; + } + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; + } + }, + cancel(reason) { + _onFinish(reason); + return iterator2.return(); + } + }, { + highWaterMark: 2 + }); +}; + +// node_modules/axios/lib/adapters/fetch.js +var isFetchSupported = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function"; +var isReadableStreamSupported = isFetchSupported && typeof ReadableStream === "function"; +var encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder5) => (str) => encoder5.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Response(str).arrayBuffer())); +var test = (fn2, ...args) => { + try { + return !!fn2(...args); + } catch (e) { + return false; + } +}; +var supportsRequestStream = isReadableStreamSupported && test(() => { + let duplexAccessed = false; + const hasContentType = new Request(platform_default.origin, { + body: new ReadableStream(), + method: "POST", + get duplex() { + duplexAccessed = true; + return "half"; + } + }).headers.has("Content-Type"); + return duplexAccessed && !hasContentType; +}); +var DEFAULT_CHUNK_SIZE = 64 * 1024; +var supportsResponseStream = isReadableStreamSupported && test(() => utils_default.isReadableStream(new Response("").body)); +var resolvers = { + stream: supportsResponseStream && ((res) => res.body) +}; +isFetchSupported && ((res) => { + ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => { + !resolvers[type] && (resolvers[type] = utils_default.isFunction(res[type]) ? (res2) => res2[type]() : (_, config3) => { + throw new AxiosError_default(`Response type '${type}' is not supported`, AxiosError_default.ERR_NOT_SUPPORT, config3); + }); + }); +})(new Response()); +var getBodyLength = async (body) => { + if (body == null) { + return 0; + } + if (utils_default.isBlob(body)) { + return body.size; + } + if (utils_default.isSpecCompliantForm(body)) { + const _request = new Request(platform_default.origin, { + method: "POST", + body + }); + return (await _request.arrayBuffer()).byteLength; + } + if (utils_default.isArrayBufferView(body) || utils_default.isArrayBuffer(body)) { + return body.byteLength; + } + if (utils_default.isURLSearchParams(body)) { + body = body + ""; + } + if (utils_default.isString(body)) { + return (await encodeText(body)).byteLength; + } +}; +var resolveBodyLength = async (headers, body) => { + const length = utils_default.toFiniteNumber(headers.getContentLength()); + return length == null ? getBodyLength(body) : length; +}; +var fetch_default = isFetchSupported && (async (config3) => { + let { + url: url2, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = "same-origin", + fetchOptions + } = resolveConfig_default(config3); + responseType = responseType ? (responseType + "").toLowerCase() : "text"; + let composedSignal = composeSignals_default([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + let request; + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + let requestContentLength; + try { + if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) { + let _request = new Request(url2, { + method: "POST", + body: data, + duplex: "half" + }); + let contentTypeHeader; + if (utils_default.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) { + headers.setContentType(contentTypeHeader); + } + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } + } + if (!utils_default.isString(withCredentials)) { + withCredentials = withCredentials ? "include" : "omit"; + } + const isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url2, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : void 0 + }); + let response = await fetch(request); + const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response"); + if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) { + const options = {}; + ["status", "statusText", "headers"].forEach((prop) => { + options[prop] = response[prop]; + }); + const responseContentLength = utils_default.toFiniteNumber(response.headers.get("content-length")); + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + responseType = responseType || "text"; + let responseData = await resolvers[utils_default.findKey(resolvers, responseType) || "text"](response, config3); + !isStreamResponse && unsubscribe && unsubscribe(); + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders_default.from(response.headers), + status: response.status, + statusText: response.statusText, + config: config3, + request + }); + }); + } catch (err) { + unsubscribe && unsubscribe(); + if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config3, request), + { + cause: err.cause || err + } + ); + } + throw AxiosError_default.from(err, err && err.code, config3, request); + } +}); + +// node_modules/axios/lib/adapters/adapters.js +var knownAdapters = { + http: http_default, + xhr: xhr_default, + fetch: fetch_default +}; +utils_default.forEach(knownAdapters, (fn2, value) => { + if (fn2) { + try { + Object.defineProperty(fn2, "name", { value }); + } catch (e) { + } + Object.defineProperty(fn2, "adapterName", { value }); + } +}); +var renderReason = (reason) => `- ${reason}`; +var isResolvedHandle = (adapter) => utils_default.isFunction(adapter) || adapter === null || adapter === false; +var adapters_default = { + getAdapter: (adapters) => { + adapters = utils_default.isArray(adapters) ? adapters : [adapters]; + const { length } = adapters; + let nameOrAdapter; + let adapter; + const rejectedReasons = {}; + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id2; + adapter = nameOrAdapter; + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id2 = String(nameOrAdapter)).toLowerCase()]; + if (adapter === void 0) { + throw new AxiosError_default(`Unknown adapter '${id2}'`); + } + } + if (adapter) { + break; + } + rejectedReasons[id2 || "#" + i] = adapter; + } + if (!adapter) { + const reasons = Object.entries(rejectedReasons).map( + ([id2, state]) => `adapter ${id2} ` + (state === false ? "is not supported by the environment" : "is not available in the build") + ); + let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"; + throw new AxiosError_default( + `There is no suitable adapter to dispatch the request ` + s, + "ERR_NOT_SUPPORT" + ); + } + return adapter; + }, + adapters: knownAdapters +}; + +// node_modules/axios/lib/core/dispatchRequest.js +function throwIfCancellationRequested(config3) { + if (config3.cancelToken) { + config3.cancelToken.throwIfRequested(); + } + if (config3.signal && config3.signal.aborted) { + throw new CanceledError_default(null, config3); + } +} +function dispatchRequest(config3) { + throwIfCancellationRequested(config3); + config3.headers = AxiosHeaders_default.from(config3.headers); + config3.data = transformData.call( + config3, + config3.transformRequest + ); + if (["post", "put", "patch"].indexOf(config3.method) !== -1) { + config3.headers.setContentType("application/x-www-form-urlencoded", false); + } + const adapter = adapters_default.getAdapter(config3.adapter || defaults_default.adapter); + return adapter(config3).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config3); + response.data = transformData.call( + config3, + config3.transformResponse, + response + ); + response.headers = AxiosHeaders_default.from(response.headers); + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config3); + if (reason && reason.response) { + reason.response.data = transformData.call( + config3, + config3.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders_default.from(reason.response.headers); + } + } + return Promise.reject(reason); + }); +} + +// node_modules/axios/lib/helpers/validator.js +var validators = {}; +["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => { + validators[type] = function validator(thing) { + return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type; + }; +}); +var deprecatedWarnings = {}; +validators.transitional = function transitional(validator, version4, message) { + function formatMessage(opt, desc) { + return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); + } + return (value, opt, opts) => { + if (validator === false) { + throw new AxiosError_default( + formatMessage(opt, " has been removed" + (version4 ? " in " + version4 : "")), + AxiosError_default.ERR_DEPRECATED + ); + } + if (version4 && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + console.warn( + formatMessage( + opt, + " has been deprecated since v" + version4 + " and will be removed in the near future" + ) + ); + } + return validator ? validator(value, opt, opts) : true; + }; +}; +validators.spelling = function spelling(correctSpelling) { + return (value, opt) => { + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + }; +}; +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== "object") { + throw new AxiosError_default("options must be an object", AxiosError_default.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === void 0 || validator(value, opt, options); + if (result !== true) { + throw new AxiosError_default("option " + opt + " must be " + result, AxiosError_default.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError_default("Unknown option " + opt, AxiosError_default.ERR_BAD_OPTION); + } + } +} +var validator_default = { + assertOptions, + validators +}; + +// node_modules/axios/lib/core/Axios.js +var validators2 = validator_default.validators; +var Axios = class { + constructor(instanceConfig) { + this.defaults = instanceConfig || {}; + this.interceptors = { + request: new InterceptorManager_default(), + response: new InterceptorManager_default() + }; + } + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config3) { + try { + return await this._request(configOrUrl, config3); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error(); + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; + try { + if (!err.stack) { + err.stack = stack; + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { + err.stack += "\n" + stack; + } + } catch (e) { + } + } + throw err; + } + } + _request(configOrUrl, config3) { + if (typeof configOrUrl === "string") { + config3 = config3 || {}; + config3.url = configOrUrl; + } else { + config3 = configOrUrl || {}; + } + config3 = mergeConfig(this.defaults, config3); + const { transitional: transitional2, paramsSerializer, headers } = config3; + if (transitional2 !== void 0) { + validator_default.assertOptions(transitional2, { + silentJSONParsing: validators2.transitional(validators2.boolean), + forcedJSONParsing: validators2.transitional(validators2.boolean), + clarifyTimeoutError: validators2.transitional(validators2.boolean) + }, false); + } + if (paramsSerializer != null) { + if (utils_default.isFunction(paramsSerializer)) { + config3.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator_default.assertOptions(paramsSerializer, { + encode: validators2.function, + serialize: validators2.function + }, true); + } + } + if (config3.allowAbsoluteUrls !== void 0) { + } else if (this.defaults.allowAbsoluteUrls !== void 0) { + config3.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; + } else { + config3.allowAbsoluteUrls = true; + } + validator_default.assertOptions(config3, { + baseUrl: validators2.spelling("baseURL"), + withXsrfToken: validators2.spelling("withXSRFToken") + }, true); + config3.method = (config3.method || this.defaults.method || "get").toLowerCase(); + let contextHeaders = headers && utils_default.merge( + headers.common, + headers[config3.method] + ); + headers && utils_default.forEach( + ["delete", "get", "head", "post", "put", "patch", "common"], + (method) => { + delete headers[method]; + } + ); + config3.headers = AxiosHeaders_default.concat(contextHeaders, headers); + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config3) === false) { + return; + } + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + let promise; + let i = 0; + let len; + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), void 0]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + promise = Promise.resolve(config3); + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + return promise; + } + len = requestInterceptorChain.length; + let newConfig = config3; + i = 0; + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + i = 0; + len = responseInterceptorChain.length; + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + return promise; + } + getUri(config3) { + config3 = mergeConfig(this.defaults, config3); + const fullPath = buildFullPath(config3.baseURL, config3.url, config3.allowAbsoluteUrls); + return buildURL(fullPath, config3.params, config3.paramsSerializer); + } +}; +utils_default.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) { + Axios.prototype[method] = function(url2, config3) { + return this.request(mergeConfig(config3 || {}, { + method, + url: url2, + data: (config3 || {}).data + })); + }; +}); +utils_default.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { + function generateHTTPMethod(isForm) { + return function httpMethod(url2, data, config3) { + return this.request(mergeConfig(config3 || {}, { + method, + headers: isForm ? { + "Content-Type": "multipart/form-data" + } : {}, + url: url2, + data + })); + }; + } + Axios.prototype[method] = generateHTTPMethod(); + Axios.prototype[method + "Form"] = generateHTTPMethod(true); +}); +var Axios_default = Axios; + +// node_modules/axios/lib/cancel/CancelToken.js +var CancelToken = class _CancelToken { + constructor(executor) { + if (typeof executor !== "function") { + throw new TypeError("executor must be a function."); + } + let resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + const token = this; + this.promise.then((cancel) => { + if (!token._listeners) return; + let i = token._listeners.length; + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + this.promise.then = (onfulfilled) => { + let _resolve; + const promise = new Promise((resolve) => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + return promise; + }; + executor(function cancel(message, config3, request) { + if (token.reason) { + return; + } + token.reason = new CanceledError_default(message, config3, request); + resolvePromise(token.reason); + }); + } + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } + } + /** + * Subscribe to the cancel signal + */ + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } + } + /** + * Unsubscribe from the cancel signal + */ + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index2 = this._listeners.indexOf(listener); + if (index2 !== -1) { + this._listeners.splice(index2, 1); + } + } + toAbortSignal() { + const controller = new AbortController(); + const abort = (err) => { + controller.abort(err); + }; + this.subscribe(abort); + controller.signal.unsubscribe = () => this.unsubscribe(abort); + return controller.signal; + } + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new _CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; + } +}; +var CancelToken_default = CancelToken; + +// node_modules/axios/lib/helpers/spread.js +function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +} + +// node_modules/axios/lib/helpers/isAxiosError.js +function isAxiosError(payload) { + return utils_default.isObject(payload) && payload.isAxiosError === true; +} + +// node_modules/axios/lib/helpers/HttpStatusCode.js +var HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511 +}; +Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; +}); +var HttpStatusCode_default = HttpStatusCode; + +// node_modules/axios/lib/axios.js +function createInstance(defaultConfig) { + const context = new Axios_default(defaultConfig); + const instance = bind(Axios_default.prototype.request, context); + utils_default.extend(instance, Axios_default.prototype, context, { allOwnKeys: true }); + utils_default.extend(instance, context, null, { allOwnKeys: true }); + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + return instance; +} +var axios = createInstance(defaults_default); +axios.Axios = Axios_default; +axios.CanceledError = CanceledError_default; +axios.CancelToken = CancelToken_default; +axios.isCancel = isCancel; +axios.VERSION = VERSION; +axios.toFormData = toFormData_default; +axios.AxiosError = AxiosError_default; +axios.Cancel = axios.CanceledError; +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = spread; +axios.isAxiosError = isAxiosError; +axios.mergeConfig = mergeConfig; +axios.AxiosHeaders = AxiosHeaders_default; +axios.formToJSON = (thing) => formDataToJSON_default(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing); +axios.getAdapter = adapters_default.getAdapter; +axios.HttpStatusCode = HttpStatusCode_default; +axios.default = axios; +var axios_default = axios; + +// node_modules/axios/index.js +var { + Axios: Axios2, + AxiosError: AxiosError2, + CanceledError: CanceledError2, + isCancel: isCancel2, + CancelToken: CancelToken2, + VERSION: VERSION2, + all: all2, + Cancel, + isAxiosError: isAxiosError2, + spread: spread2, + toFormData: toFormData2, + AxiosHeaders: AxiosHeaders2, + HttpStatusCode: HttpStatusCode2, + formToJSON, + getAdapter, + mergeConfig: mergeConfig2 +} = axios_default; + +// src/constants/appErrors.ts +var appErrors = { + ["ViemCreateClientFailed" /* ViemCreateClientFailed */]: { + message: "Failed to create viem client", + isOperational: false + }, + ["FailedHTTPRequest" /* FailedHTTPRequest */]: { + message: "Failed to make HTTP request", + isOperational: true + }, + ["UnknownError" /* UnknownError */]: { + message: "An unknown error occurred", + isOperational: false + }, + ["UnhandledRejection" /* UnhandledRejection */]: { + message: "Unhandled promise rejection", + isOperational: true + }, + ["UncaughtException" /* UncaughtException */]: { + message: "Uncaught exception", + isOperational: true + }, + ["EnvKeyMissing" /* EnvKeyMissing */]: { + message: "Missing or empty required environment variable", + isOperational: false + }, + ["ChainNotFound" /* ChainNotFound */]: { + message: "Chain not found", + isOperational: false + }, + ["InsufficientGas" /* InsufficientGas */]: { + message: "Insufficient gas", + isOperational: false + }, + ["InvalidNetworkMode" /* InvalidNetworkMode */]: { + message: "Invalid network mode", + isOperational: false + }, + ["ContractCallError" /* ContractCallError */]: { + message: "Failed to call contract", + isOperational: true + }, + ["LogDecodingFailed" /* LogDecodingFailed */]: { + message: "Failed to decode log", + isOperational: true + } +}; + +// src/constants/eventEmitter.ts +import { EventEmitter as EventEmitter2 } from "node:events"; +var eventEmitter = new EventEmitter2(); + +// src/abi/ConceroRouter.json +var abi = [ + { + inputs: [ + { + internalType: "uint24", + name: "chainSelector", + type: "uint24" + }, + { + internalType: "address", + name: "feedUpdater", + type: "address" + }, + { + internalType: "address", + name: "conceroVerifier", + type: "address" + }, + { + internalType: "uint64", + name: "conceroVerifierSubId", + type: "uint64" + }, + { + internalType: "address[4]", + name: "clfSigners", + type: "address[4]" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [ + { + internalType: "address", + name: "signer", + type: "address" + } + ], + name: "DuplicateSignatureDetected", + type: "error" + }, + { + inputs: [], + name: "FinalityNotYetSupported", + type: "error" + }, + { + inputs: [], + name: "IncorrectNumberOfSignatures", + type: "error" + }, + { + inputs: [ + { + internalType: "uint256", + name: "provided", + type: "uint256" + }, + { + internalType: "uint256", + name: "required", + type: "uint256" + } + ], + name: "InsufficientFee", + type: "error" + }, + { + inputs: [], + name: "InvalidAmount", + type: "error" + }, + { + inputs: [], + name: "InvalidClfReportClient", + type: "error" + }, + { + inputs: [], + name: "InvalidClfReportSubscriptionId", + type: "error" + }, + { + inputs: [ + { + internalType: "uint24", + name: "dstChainSelector", + type: "uint24" + } + ], + name: "InvalidDstChainSelector", + type: "error" + }, + { + inputs: [], + name: "InvalidGasLimit", + type: "error" + }, + { + inputs: [], + name: "InvalidMessageHashSum", + type: "error" + }, + { + inputs: [], + name: "InvalidNamespace", + type: "error" + }, + { + inputs: [], + name: "InvalidReceiver", + type: "error" + }, + { + inputs: [], + name: "LengthMismatch", + type: "error" + }, + { + inputs: [ + { + internalType: "bytes32", + name: "messageId", + type: "bytes32" + } + ], + name: "MessageAlreadyProcessed", + type: "error" + }, + { + inputs: [ + { + internalType: "bytes32", + name: "messageId", + type: "bytes32" + } + ], + name: "MessageDeliveryFailed", + type: "error" + }, + { + inputs: [], + name: "MessageTooLarge", + type: "error" + }, + { + inputs: [ + { + internalType: "enum CommonErrors.RequiredVariableUnsetType", + name: "variableType", + type: "uint8" + } + ], + name: "RequiredVariableUnset", + type: "error" + }, + { + inputs: [ + { + internalType: "address", + name: "token", + type: "address" + } + ], + name: "SafeERC20FailedOperation", + type: "error" + }, + { + inputs: [], + name: "TransferFailed", + type: "error" + }, + { + inputs: [], + name: "Unauthorized", + type: "error" + }, + { + inputs: [], + name: "UnauthorizedOperator", + type: "error" + }, + { + inputs: [ + { + internalType: "address", + name: "signer", + type: "address" + } + ], + name: "UnauthorizedSigner", + type: "error" + }, + { + inputs: [ + { + internalType: "uint24", + name: "chainSelector", + type: "uint24" + } + ], + name: "UnsupportedChainSelector", + type: "error" + }, + { + inputs: [], + name: "UnsupportedFeeTokenType", + type: "error" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "id", + type: "bytes32" + } + ], + name: "ConceroMessageDelivered", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "id", + type: "bytes32" + } + ], + name: "ConceroMessageReceived", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "messageId", + type: "bytes32" + }, + { + indexed: false, + internalType: "uint8", + name: "version", + type: "uint8" + }, + { + indexed: false, + internalType: "bool", + name: "shouldFinaliseSrc", + type: "bool" + }, + { + indexed: false, + internalType: "uint24", + name: "dstChainSelector", + type: "uint24" + }, + { + indexed: false, + internalType: "bytes", + name: "dstChainData", + type: "bytes" + }, + { + indexed: false, + internalType: "address", + name: "sender", + type: "address" + }, + { + indexed: false, + internalType: "bytes", + name: "message", + type: "bytes" + } + ], + name: "ConceroMessageSent", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "operator", + type: "address" + }, + { + indexed: false, + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "OperatorFeeWithdrawn", + type: "event" + }, + { + stateMutability: "payable", + type: "fallback" + }, + { + inputs: [ + { + internalType: "uint24", + name: "dstChainSelector", + type: "uint24" + }, + { + internalType: "bool", + name: "shouldFinaliseSrc", + type: "bool" + }, + { + internalType: "address", + name: "feeToken", + type: "address" + }, + { + components: [ + { + internalType: "address", + name: "receiver", + type: "address" + }, + { + internalType: "uint256", + name: "gasLimit", + type: "uint256" + } + ], + internalType: "struct ConceroTypes.EvmDstChainData", + name: "dstChainData", + type: "tuple" + }, + { + internalType: "bytes", + name: "message", + type: "bytes" + } + ], + name: "conceroSend", + outputs: [ + { + internalType: "bytes32", + name: "", + type: "bytes32" + } + ], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "operator", + type: "address" + } + ], + name: "getCohort", + outputs: [ + { + internalType: "uint8", + name: "", + type: "uint8" + } + ], + stateMutability: "pure", + type: "function" + }, + { + inputs: [ + { + internalType: "uint24", + name: "dstChainSelector", + type: "uint24" + }, + { + internalType: "bool", + name: "shouldFinaliseSrc", + type: "bool" + }, + { + internalType: "address", + name: "feeToken", + type: "address" + }, + { + components: [ + { + internalType: "address", + name: "receiver", + type: "address" + }, + { + internalType: "uint256", + name: "gasLimit", + type: "uint256" + } + ], + internalType: "struct ConceroTypes.EvmDstChainData", + name: "dstChainData", + type: "tuple" + } + ], + name: "getMessageFee", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getMessageVersion", + outputs: [ + { + internalType: "uint8", + name: "", + type: "uint8" + } + ], + stateMutability: "pure", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32", + name: "namespace", + type: "bytes32" + }, + { + internalType: "uint256", + name: "offset", + type: "uint256" + }, + { + internalType: "bytes32", + name: "mappingKey", + type: "bytes32" + } + ], + name: "getStorage", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getWithdrawableConceroFee", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "i_owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint24", + name: "chainSelector", + type: "uint24" + } + ], + name: "isChainSupported", + outputs: [ + { + internalType: "bool", + name: "", + type: "bool" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint24[]", + name: "dstChainSelectors", + type: "uint24[]" + }, + { + internalType: "uint256[]", + name: "gasPrices", + type: "uint256[]" + } + ], + name: "setLastGasPrices", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint24[]", + name: "dstChainSelectors", + type: "uint24[]" + }, + { + internalType: "uint256[]", + name: "rates", + type: "uint256[]" + } + ], + name: "setNativeNativeRates", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "setNativeUsdRate", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32", + name: "namespace", + type: "bytes32" + }, + { + internalType: "uint256", + name: "offset", + type: "uint256" + }, + { + internalType: "bytes32", + name: "mappingKey", + type: "bytes32" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "setStorage", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32[]", + name: "namespaces", + type: "bytes32[]" + }, + { + internalType: "uint256[]", + name: "offsets", + type: "uint256[]" + }, + { + internalType: "bytes32[]", + name: "mappingKeys", + type: "bytes32[]" + }, + { + internalType: "uint256[]", + name: "values", + type: "uint256[]" + } + ], + name: "setStorageBulk", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint24[]", + name: "chainSelectors", + type: "uint24[]" + }, + { + internalType: "bool[]", + name: "isSupported", + type: "bool[]" + } + ], + name: "setSupportedChains", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + components: [ + { + internalType: "bytes32[3]", + name: "context", + type: "bytes32[3]" + }, + { + internalType: "bytes", + name: "report", + type: "bytes" + }, + { + internalType: "bytes32[]", + name: "rs", + type: "bytes32[]" + }, + { + internalType: "bytes32[]", + name: "ss", + type: "bytes32[]" + }, + { + internalType: "bytes32", + name: "rawVs", + type: "bytes32" + } + ], + internalType: "struct Types.ClfDonReportSubmission", + name: "reportSubmission", + type: "tuple" + }, + { + internalType: "bytes[]", + name: "messageBodies", + type: "bytes[]" + }, + { + internalType: "uint256[]", + name: "indexes", + type: "uint256[]" + } + ], + name: "submitMessageReport", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address[]", + name: "tokens", + type: "address[]" + }, + { + internalType: "uint256[]", + name: "amounts", + type: "uint256[]" + } + ], + name: "withdrawConceroFees", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "withdrawOperatorFee", + outputs: [ + { + internalType: "bool", + name: "success", + type: "bool" + } + ], + stateMutability: "nonpayable", + type: "function" + }, + { + stateMutability: "payable", + type: "receive" + } +]; + +// src/abi/ConceroVerifier.json +var abi2 = [ + { + inputs: [ + { + internalType: "uint24", + name: "chainSelector", + type: "uint24" + }, + { + internalType: "address", + name: "USDC", + type: "address" + }, + { + components: [ + { + internalType: "address", + name: "router", + type: "address" + }, + { + internalType: "bytes32", + name: "donId", + type: "bytes32" + }, + { + internalType: "uint64", + name: "subscriptionId", + type: "uint64" + }, + { + internalType: "uint64", + name: "donHostedSecretsVersion", + type: "uint64" + }, + { + internalType: "uint8", + name: "donHostedSecretsSlotId", + type: "uint8" + }, + { + internalType: "uint16", + name: "premiumFeeUsdBps", + type: "uint16" + }, + { + internalType: "uint32", + name: "callbackGasLimit", + type: "uint32" + }, + { + internalType: "bytes32", + name: "requestCLFMessageReportJsCodeHash", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "requestOperatorRegistrationJsCodeHash", + type: "bytes32" + } + ], + internalType: "struct CLFParams", + name: "clfParams", + type: "tuple" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [], + name: "EmptyArgs", + type: "error" + }, + { + inputs: [], + name: "EmptySource", + type: "error" + }, + { + inputs: [ + { + internalType: "uint256", + name: "requiredAmount", + type: "uint256" + }, + { + internalType: "uint256", + name: "availableAmount", + type: "uint256" + } + ], + name: "InsufficientFee", + type: "error" + }, + { + inputs: [ + { + internalType: "uint256", + name: "provided", + type: "uint256" + }, + { + internalType: "uint256", + name: "required", + type: "uint256" + } + ], + name: "InsufficientFee", + type: "error" + }, + { + inputs: [ + { + internalType: "uint256", + name: "provided", + type: "uint256" + }, + { + internalType: "uint256", + name: "required", + type: "uint256" + } + ], + name: "InsufficientOperatorDeposit", + type: "error" + }, + { + inputs: [], + name: "InvalidAddress", + type: "error" + }, + { + inputs: [], + name: "InvalidAmount", + type: "error" + }, + { + inputs: [], + name: "InvalidMessageVersion", + type: "error" + }, + { + inputs: [], + name: "InvalidNamespace", + type: "error" + }, + { + inputs: [], + name: "LengthMismatch", + type: "error" + }, + { + inputs: [], + name: "MessageAlreadyProcessed", + type: "error" + }, + { + inputs: [], + name: "NoInlineSecrets", + type: "error" + }, + { + inputs: [], + name: "OnlyRouterCanFulfill", + type: "error" + }, + { + inputs: [], + name: "OperatorAddressMismatch", + type: "error" + }, + { + inputs: [], + name: "OperatorAlreadyRegistered", + type: "error" + }, + { + inputs: [], + name: "OperatorNotRegistered", + type: "error" + }, + { + inputs: [ + { + internalType: "enum CommonErrors.RequiredVariableUnsetType", + name: "variableType", + type: "uint8" + } + ], + name: "RequiredVariableUnset", + type: "error" + }, + { + inputs: [ + { + internalType: "address", + name: "token", + type: "address" + } + ], + name: "SafeERC20FailedOperation", + type: "error" + }, + { + inputs: [], + name: "TransferFailed", + type: "error" + }, + { + inputs: [], + name: "TransferFailed", + type: "error" + }, + { + inputs: [], + name: "Unauthorized", + type: "error" + }, + { + inputs: [], + name: "UnauthorizedOperator", + type: "error" + }, + { + inputs: [], + name: "WrongClfResultType", + type: "error" + }, + { + anonymous: false, + inputs: [ + { + indexed: false, + internalType: "bytes", + name: "err", + type: "bytes" + } + ], + name: "CLFRequestError", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "messageId", + type: "bytes32" + } + ], + name: "MessageReport", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "messageId", + type: "bytes32" + } + ], + name: "MessageReportRequested", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "operator", + type: "address" + }, + { + indexed: false, + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "OperatorDepositWithdrawn", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "operator", + type: "address" + }, + { + indexed: false, + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "OperatorDeposited", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "operator", + type: "address" + }, + { + indexed: false, + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "OperatorFeeWithdrawn", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "operator", + type: "address" + }, + { + indexed: false, + internalType: "enum CommonTypes.ChainType[]", + name: "chainTypes", + type: "uint8[]" + }, + { + indexed: false, + internalType: "enum Types.OperatorRegistrationAction[]", + name: "operatorActions", + type: "uint8[]" + } + ], + name: "OperatorRegistered", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "address", + name: "requester", + type: "address" + }, + { + indexed: false, + internalType: "enum CommonTypes.ChainType[]", + name: "chainTypes", + type: "uint8[]" + }, + { + indexed: false, + internalType: "enum Types.OperatorRegistrationAction[]", + name: "operatorActions", + type: "uint8[]" + }, + { + indexed: false, + internalType: "bytes[]", + name: "operatorAddresses", + type: "bytes[]" + } + ], + name: "OperatorRegistrationRequested", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "id", + type: "bytes32" + } + ], + name: "RequestFulfilled", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: "bytes32", + name: "id", + type: "bytes32" + } + ], + name: "RequestSent", + type: "event" + }, + { + stateMutability: "payable", + type: "fallback" + }, + { + inputs: [], + name: "getCLFCost", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCohortsCount", + outputs: [ + { + internalType: "uint8", + name: "", + type: "uint8" + } + ], + stateMutability: "pure", + type: "function" + }, + { + inputs: [], + name: "getMinimumOperatorDeposit", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "operator", + type: "address" + } + ], + name: "getOperatorDeposit", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "operator", + type: "address" + } + ], + name: "getOperatorFeesEarned", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "enum CommonTypes.ChainType", + name: "chainType", + type: "uint8" + } + ], + name: "getRegisteredOperators", + outputs: [ + { + internalType: "bytes[]", + name: "", + type: "bytes[]" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32", + name: "namespace", + type: "bytes32" + }, + { + internalType: "uint256", + name: "offset", + type: "uint256" + }, + { + internalType: "bytes32", + name: "mappingKey", + type: "bytes32" + } + ], + name: "getStorage", + outputs: [ + { + internalType: "uint256", + name: "", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getWithdrawableConceroFee", + outputs: [ + { + internalType: "uint256", + name: "availableFees", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32", + name: "requestId", + type: "bytes32" + }, + { + internalType: "bytes", + name: "response", + type: "bytes" + }, + { + internalType: "bytes", + name: "err", + type: "bytes" + } + ], + name: "handleOracleFulfillment", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [], + name: "i_owner", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "uint24", + name: "chainSelector", + type: "uint24" + } + ], + name: "isChainSupported", + outputs: [ + { + internalType: "bool", + name: "", + type: "bool" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "operator", + type: "address" + } + ], + name: "isOperatorRegistered", + outputs: [ + { + internalType: "bool", + name: "", + type: "bool" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "operator", + type: "address" + } + ], + name: "operatorDeposit", + outputs: [], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32", + name: "messageId", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "messageHashSum", + type: "bytes32" + }, + { + internalType: "uint24", + name: "srcChainSelector", + type: "uint24" + }, + { + internalType: "bytes", + name: "srcChainData", + type: "bytes" + } + ], + name: "requestMessageReport", + outputs: [ + { + internalType: "bytes32", + name: "", + type: "bytes32" + } + ], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "enum CommonTypes.ChainType[]", + name: "chainTypes", + type: "uint8[]" + }, + { + internalType: "enum Types.OperatorRegistrationAction[]", + name: "operatorActions", + type: "uint8[]" + }, + { + internalType: "bytes[]", + name: "operatorAddresses", + type: "bytes[]" + } + ], + name: "requestOperatorRegistration", + outputs: [ + { + internalType: "bytes32", + name: "clfRequestId", + type: "bytes32" + } + ], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "setNativeUsdRate", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32", + name: "namespace", + type: "bytes32" + }, + { + internalType: "uint256", + name: "offset", + type: "uint256" + }, + { + internalType: "bytes32", + name: "mappingKey", + type: "bytes32" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "setStorage", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32[]", + name: "namespaces", + type: "bytes32[]" + }, + { + internalType: "uint256[]", + name: "offsets", + type: "uint256[]" + }, + { + internalType: "bytes32[]", + name: "mappingKeys", + type: "bytes32[]" + }, + { + internalType: "uint256[]", + name: "values", + type: "uint256[]" + } + ], + name: "setStorageBulk", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint24[]", + name: "chainSelectors", + type: "uint24[]" + }, + { + internalType: "bool[]", + name: "isSupported", + type: "bool[]" + } + ], + name: "setSupportedChains", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address[]", + name: "tokens", + type: "address[]" + }, + { + internalType: "uint256[]", + name: "amounts", + type: "uint256[]" + } + ], + name: "withdrawConceroFees", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "withdrawOperatorDeposit", + outputs: [ + { + internalType: "bool", + name: "success", + type: "bool" + } + ], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "withdrawOperatorFee", + outputs: [ + { + internalType: "bool", + name: "success", + type: "bool" + } + ], + stateMutability: "nonpayable", + type: "function" + }, + { + stateMutability: "payable", + type: "receive" + } +]; + +// src/common/utils/AppError.ts +var AppError = class extends Error { + isOperational; + constructor(errorType, originalError) { + const { message, isOperational } = appErrors[errorType]; + super(originalError ? `${message}: ${originalError.message}` : message); + Object.setPrototypeOf(this, new.target.prototype); + this.name = this.constructor.name; + this.isOperational = isOperational; + this.stack = originalError?.stack; + this.logError(); + } + logError() { + console.error({ + name: this.name, + message: this.message, + stack: this.stack, + isOperational: this.isOperational + }); + if (!this.isOperational) { + process.exit(1); + } + } +}; + +// src/common/utils/logger.ts +var import_winston = __toESM(require_winston(), 1); +var import_winston_daily_rotate_file = __toESM(require_winston_daily_rotate_file(), 1); + +// src/common/managers/ManagerBase.ts +var ManagerBase = class { + initialized = false; + async initialize() { + if (this.initialized) { + return; + } + try { + this.initialized = true; + } catch (error) { + throw error; + } + } + dispose() { + this.initialized = false; + } +}; + +// src/common/utils/logger.ts +var Logger = class _Logger extends ManagerBase { + static instance; + baseLogger; + consumerLoggers = /* @__PURE__ */ new Map(); + constructor() { + super(); + this.baseLogger = this.createBaseLogger(); + } + static createInstance() { + if (!_Logger.instance) { + _Logger.instance = new _Logger(); + } + return _Logger.instance; + } + static getInstance() { + if (!_Logger.instance) { + throw new Error("Logger is not initialized. Call createInstance() first."); + } + return _Logger.instance; + } + createBaseLogger() { + const logFormat = import_winston.default.format.combine( + import_winston.default.format.colorize({ level: true }), + import_winston.default.format.timestamp({ + format: "MM-DD HH:mm:ss" + }), + import_winston.default.format.printf(({ level, message, timestamp, consumer, ...meta }) => { + const prefix = consumer ? `${consumer}` : ""; + const formattedMessage = typeof message === "object" ? JSON.stringify(message, null, 2) : message; + const formattedMeta = meta && Object.keys(meta).length ? JSON.stringify(meta, null, 2) : ""; + return `${timestamp} ${level} ${prefix}: ${formattedMessage} ${formattedMeta}`.trim(); + }) + ); + const logger = import_winston.default.createLogger({ + level: "debug", + // Allow all logs through at base logger level + format: import_winston.default.format.json(), + transports: [ + new import_winston_daily_rotate_file.default({ + level: "debug", + dirname: globalConfig.LOGGER.LOG_DIR, + filename: "log-%DATE%.log", + datePattern: "YYYY-MM-DD", + maxSize: globalConfig.LOGGER.LOG_MAX_SIZE, + maxFiles: globalConfig.LOGGER.LOG_MAX_FILES + }), + new import_winston_daily_rotate_file.default({ + level: "error", + dirname: globalConfig.LOGGER.LOG_DIR, + filename: "error-%DATE%.log", + datePattern: "YYYY-MM-DD", + maxSize: globalConfig.LOGGER.LOG_MAX_SIZE, + maxFiles: globalConfig.LOGGER.LOG_MAX_FILES + }) + ] + }); + if (process.env.NODE_ENV !== "production") { + logger.add( + new import_winston.default.transports.Console({ + level: "debug", + format: logFormat + }) + ); + } + return logger; + } + async initialize() { + if (this.initialized) return; + super.initialize(); + this.getLogger("Logger").info("Initialized"); + } + getLogger(consumerName) { + const cacheKey2 = consumerName || "__default__"; + if (this.consumerLoggers.has(cacheKey2)) { + return this.consumerLoggers.get(cacheKey2); + } + const logger = this.createConsumerLogger(consumerName); + this.consumerLoggers.set(cacheKey2, logger); + return logger; + } + createConsumerLogger(consumerName) { + const getLogLevel = () => { + if (!consumerName) { + return globalConfig.LOGGER.LOG_LEVEL_DEFAULT; + } + return globalConfig.LOGGER.LOG_LEVELS_GRANULAR[consumerName] || globalConfig.LOGGER.LOG_LEVEL_DEFAULT; + }; + const logLevelValue = { + error: 0, + warn: 1, + info: 2, + debug: 3 + }; + const shouldLog = (messageLevel) => { + const configuredLevel = getLogLevel(); + const configLevelValue = logLevelValue[configuredLevel] || 2; + const messageLevelValue = logLevelValue[messageLevel] || 0; + return messageLevelValue <= configLevelValue; + }; + const logLevel = getLogLevel(); + return { + error: (message, ...meta) => { + this.baseLogger.error( + message, + consumerName ? { consumer: consumerName, ...meta } : meta + ); + }, + warn: (message, ...meta) => { + if (shouldLog("warn")) { + this.baseLogger.warn( + message, + consumerName ? { consumer: consumerName, ...meta } : meta + ); + } + }, + info: (message, ...meta) => { + if (shouldLog("info")) { + this.baseLogger.info( + message, + consumerName ? { consumer: consumerName, ...meta } : meta + ); + } + }, + debug: (message, ...meta) => { + if (shouldLog("debug")) { + this.baseLogger.debug( + message, + consumerName ? { consumer: consumerName, ...meta } : meta + ); + } + } + }; + } + dispose() { + this.consumerLoggers.clear(); + super.dispose(); + } +}; + +// src/common/utils/sleep.ts +async function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// src/common/utils/asyncRetry.ts +async function asyncRetry(fn2, options = {}) { + const { maxRetries = 3, delayMs = 2e3, isRetryableError = () => false } = options; + const logger = Logger.getInstance().getLogger("AsyncRetry"); + let attempt = 0; + let lastError; + while (attempt <= maxRetries) { + try { + return await fn2(); + } catch (error) { + lastError = error; + if (await isRetryableError(error) && attempt < maxRetries) { + ++attempt; + logger.debug(`Retry attempt ${attempt} failed. Retrying in ${delayMs}ms...`); + await sleep(delayMs); + } else { + throw error; + } + } + } + throw lastError; +} + +// node_modules/viem/_esm/index.js +init_exports(); + +// node_modules/viem/_esm/utils/getAction.js +function getAction(client, actionFn, name) { + const action_implicit = client[actionFn.name]; + if (typeof action_implicit === "function") + return action_implicit; + const action_explicit = client[name]; + if (typeof action_explicit === "function") + return action_explicit; + return (params) => actionFn(client, params); +} + +// node_modules/viem/_esm/utils/abi/encodeEventTopics.js +init_abi(); + +// node_modules/viem/_esm/errors/log.js +init_base(); +var FilterTypeNotSupportedError = class extends BaseError2 { + constructor(type) { + super(`Filter type "${type}" is not supported.`, { + name: "FilterTypeNotSupportedError" + }); + } +}; + +// node_modules/viem/_esm/utils/abi/encodeEventTopics.js +init_toBytes(); +init_keccak256(); +init_toEventSelector(); +init_encodeAbiParameters(); +init_formatAbiItem2(); +init_getAbiItem(); +var docsPath = "/docs/contract/encodeEventTopics"; +function encodeEventTopics(parameters) { + const { abi: abi4, eventName, args } = parameters; + let abiItem = abi4[0]; + if (eventName) { + const item = getAbiItem({ abi: abi4, name: eventName }); + if (!item) + throw new AbiEventNotFoundError(eventName, { docsPath }); + abiItem = item; + } + if (abiItem.type !== "event") + throw new AbiEventNotFoundError(void 0, { docsPath }); + const definition = formatAbiItem2(abiItem); + const signature = toEventSelector(definition); + let topics = []; + if (args && "inputs" in abiItem) { + const indexedInputs = abiItem.inputs?.filter((param) => "indexed" in param && param.indexed); + const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? indexedInputs?.map((x2) => args[x2.name]) ?? [] : []; + if (args_.length > 0) { + topics = indexedInputs?.map((param, i) => { + if (Array.isArray(args_[i])) + return args_[i].map((_, j2) => encodeArg({ param, value: args_[i][j2] })); + return typeof args_[i] !== "undefined" && args_[i] !== null ? encodeArg({ param, value: args_[i] }) : null; + }) ?? []; + } + } + return [signature, ...topics]; +} +function encodeArg({ param, value }) { + if (param.type === "string" || param.type === "bytes") + return keccak256(toBytes(value)); + if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) + throw new FilterTypeNotSupportedError(param.type); + return encodeAbiParameters([param], [value]); +} + +// node_modules/viem/_esm/actions/public/createContractEventFilter.js +init_toHex(); + +// node_modules/viem/_esm/utils/filters/createFilterRequestScope.js +function createFilterRequestScope(client, { method }) { + const requestMap = {}; + if (client.transport.type === "fallback") + client.transport.onResponse?.(({ method: method_, response: id2, status, transport }) => { + if (status === "success" && method === method_) + requestMap[id2] = transport.request; + }); + return (id2) => requestMap[id2] || client.request; +} + +// node_modules/viem/_esm/actions/public/createContractEventFilter.js +async function createContractEventFilter(client, parameters) { + const { address, abi: abi4, args, eventName, fromBlock, strict, toBlock } = parameters; + const getRequest = createFilterRequestScope(client, { + method: "eth_newFilter" + }); + const topics = eventName ? encodeEventTopics({ + abi: abi4, + args, + eventName + }) : void 0; + const id2 = await client.request({ + method: "eth_newFilter", + params: [ + { + address, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, + topics + } + ] + }); + return { + abi: abi4, + args, + eventName, + id: id2, + request: getRequest(id2), + strict: Boolean(strict), + type: "event" + }; +} + +// node_modules/viem/_esm/actions/public/estimateContractGas.js +init_parseAccount(); +init_encodeFunctionData(); + +// node_modules/viem/_esm/utils/errors/getContractError.js +init_abi(); +init_base(); +init_contract(); +init_request(); +init_rpc(); +var EXECUTION_REVERTED_ERROR_CODE = 3; +function getContractError(err, { abi: abi4, address, args, docsPath: docsPath6, functionName, sender }) { + const error = err instanceof RawContractError ? err : err instanceof BaseError2 ? err.walk((err2) => "data" in err2) || err.walk() : {}; + const { code, data, details, message, shortMessage } = error; + const cause = (() => { + if (err instanceof AbiDecodingZeroDataError) + return new ContractFunctionZeroDataError({ functionName }); + if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) && (data || details || message || shortMessage)) { + return new ContractFunctionRevertedError({ + abi: abi4, + data: typeof data === "object" ? data.data : data, + functionName, + message: error instanceof RpcRequestError ? details : shortMessage ?? message + }); + } + return err; + })(); + return new ContractFunctionExecutionError(cause, { + abi: abi4, + args, + contractAddress: address, + docsPath: docsPath6, + functionName, + sender + }); +} + +// node_modules/viem/_esm/actions/public/estimateGas.js +init_parseAccount(); +init_base(); + +// node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js +init_getAddress(); +init_keccak256(); +function publicKeyToAddress(publicKey) { + const address = keccak256(`0x${publicKey.substring(4)}`).substring(26); + return checksumAddress(`0x${address}`); +} + +// node_modules/viem/_esm/utils/signature/recoverPublicKey.js +init_isHex(); +init_fromHex(); +init_toHex(); +async function recoverPublicKey({ hash: hash2, signature }) { + const hashHex = isHex(hash2) ? hash2 : toHex(hash2); + const { secp256k1: secp256k12 } = await Promise.resolve().then(() => (init_secp256k1(), secp256k1_exports)); + const signature_ = (() => { + if (typeof signature === "object" && "r" in signature && "s" in signature) { + const { r, s, v, yParity } = signature; + const yParityOrV2 = Number(yParity ?? v); + const recoveryBit2 = toRecoveryBit(yParityOrV2); + return new secp256k12.Signature(hexToBigInt(r), hexToBigInt(s)).addRecoveryBit(recoveryBit2); + } + const signatureHex = isHex(signature) ? signature : toHex(signature); + const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`); + const recoveryBit = toRecoveryBit(yParityOrV); + return secp256k12.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit); + })(); + const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false); + return `0x${publicKey}`; +} +function toRecoveryBit(yParityOrV) { + if (yParityOrV === 0 || yParityOrV === 1) + return yParityOrV; + if (yParityOrV === 27) + return 0; + if (yParityOrV === 28) + return 1; + throw new Error("Invalid yParityOrV value"); +} + +// node_modules/viem/_esm/utils/signature/recoverAddress.js +async function recoverAddress({ hash: hash2, signature }) { + return publicKeyToAddress(await recoverPublicKey({ hash: hash2, signature })); +} + +// node_modules/viem/_esm/utils/authorization/hashAuthorization.js +init_concat(); +init_toBytes(); +init_toHex(); + +// node_modules/viem/_esm/utils/encoding/toRlp.js +init_base(); +init_cursor2(); +init_toBytes(); +init_toHex(); +function toRlp(bytes, to2 = "hex") { + const encodable = getEncodable(bytes); + const cursor = createCursor(new Uint8Array(encodable.length)); + encodable.encode(cursor); + if (to2 === "hex") + return bytesToHex(cursor.bytes); + return cursor.bytes; +} +function getEncodable(bytes) { + if (Array.isArray(bytes)) + return getEncodableList(bytes.map((x2) => getEncodable(x2))); + return getEncodableBytes(bytes); +} +function getEncodableList(list) { + const bodyLength = list.reduce((acc, x2) => acc + x2.length, 0); + const sizeOfBodyLength = getSizeOfLength(bodyLength); + const length = (() => { + if (bodyLength <= 55) + return 1 + bodyLength; + return 1 + sizeOfBodyLength + bodyLength; + })(); + return { + length, + encode(cursor) { + if (bodyLength <= 55) { + cursor.pushByte(192 + bodyLength); + } else { + cursor.pushByte(192 + 55 + sizeOfBodyLength); + if (sizeOfBodyLength === 1) + cursor.pushUint8(bodyLength); + else if (sizeOfBodyLength === 2) + cursor.pushUint16(bodyLength); + else if (sizeOfBodyLength === 3) + cursor.pushUint24(bodyLength); + else + cursor.pushUint32(bodyLength); + } + for (const { encode: encode6 } of list) { + encode6(cursor); + } + } + }; +} +function getEncodableBytes(bytesOrHex) { + const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex; + const sizeOfBytesLength = getSizeOfLength(bytes.length); + const length = (() => { + if (bytes.length === 1 && bytes[0] < 128) + return 1; + if (bytes.length <= 55) + return 1 + bytes.length; + return 1 + sizeOfBytesLength + bytes.length; + })(); + return { + length, + encode(cursor) { + if (bytes.length === 1 && bytes[0] < 128) { + cursor.pushBytes(bytes); + } else if (bytes.length <= 55) { + cursor.pushByte(128 + bytes.length); + cursor.pushBytes(bytes); + } else { + cursor.pushByte(128 + 55 + sizeOfBytesLength); + if (sizeOfBytesLength === 1) + cursor.pushUint8(bytes.length); + else if (sizeOfBytesLength === 2) + cursor.pushUint16(bytes.length); + else if (sizeOfBytesLength === 3) + cursor.pushUint24(bytes.length); + else + cursor.pushUint32(bytes.length); + cursor.pushBytes(bytes); + } + } + }; +} +function getSizeOfLength(length) { + if (length < 2 ** 8) + return 1; + if (length < 2 ** 16) + return 2; + if (length < 2 ** 24) + return 3; + if (length < 2 ** 32) + return 4; + throw new BaseError2("Length is too large."); +} + +// node_modules/viem/_esm/utils/authorization/hashAuthorization.js +init_keccak256(); +function hashAuthorization(parameters) { + const { chainId, nonce, to: to2 } = parameters; + const address = parameters.contractAddress ?? parameters.address; + const hash2 = keccak256(concatHex([ + "0x05", + toRlp([ + chainId ? numberToHex(chainId) : "0x", + address, + nonce ? numberToHex(nonce) : "0x" + ]) + ])); + if (to2 === "bytes") + return hexToBytes(hash2); + return hash2; +} + +// node_modules/viem/_esm/utils/authorization/recoverAuthorizationAddress.js +async function recoverAuthorizationAddress(parameters) { + const { authorization, signature } = parameters; + return recoverAddress({ + hash: hashAuthorization(authorization), + signature: signature ?? authorization + }); +} + +// node_modules/viem/_esm/actions/public/estimateGas.js +init_toHex(); + +// node_modules/viem/_esm/errors/estimateGas.js +init_formatEther(); +init_formatGwei(); +init_base(); +init_transaction(); +var EstimateGasExecutionError = class extends BaseError2 { + constructor(cause, { account, docsPath: docsPath6, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value }) { + const prettyArgs = prettyPrint({ + from: account?.address, + to: to2, + value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, + data, + gas, + gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, + maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, + maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, + nonce + }); + super(cause.shortMessage, { + cause, + docsPath: docsPath6, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Estimate Gas Arguments:", + prettyArgs + ].filter(Boolean), + name: "EstimateGasExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cause = cause; + } +}; + +// node_modules/viem/_esm/utils/errors/getEstimateGasError.js +init_node(); +init_getNodeError(); +function getEstimateGasError(err, { docsPath: docsPath6, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new EstimateGasExecutionError(cause, { + docsPath: docsPath6, + ...args + }); +} + +// node_modules/viem/_esm/actions/public/estimateGas.js +init_extract(); +init_transactionRequest(); +init_stateOverride2(); +init_assertRequest(); + +// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js +init_parseAccount(); + +// node_modules/viem/_esm/errors/fee.js +init_formatGwei(); +init_base(); +var BaseFeeScalarError = class extends BaseError2 { + constructor() { + super("`baseFeeMultiplier` must be greater than 1.", { + name: "BaseFeeScalarError" + }); + } +}; +var Eip1559FeesNotSupportedError = class extends BaseError2 { + constructor() { + super("Chain does not support EIP-1559 fees.", { + name: "Eip1559FeesNotSupportedError" + }); + } +}; +var MaxFeePerGasTooLowError = class extends BaseError2 { + constructor({ maxPriorityFeePerGas }) { + super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" }); + } +}; + +// node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js +init_fromHex(); + +// node_modules/viem/_esm/errors/block.js +init_base(); +var BlockNotFoundError = class extends BaseError2 { + constructor({ blockHash, blockNumber }) { + let identifier = "Block"; + if (blockHash) + identifier = `Block at hash "${blockHash}"`; + if (blockNumber) + identifier = `Block at number "${blockNumber}"`; + super(`${identifier} could not be found.`, { name: "BlockNotFoundError" }); + } +}; + +// node_modules/viem/_esm/actions/public/getBlock.js +init_toHex(); + +// node_modules/viem/_esm/utils/formatters/transaction.js +init_fromHex(); +var transactionType = { + "0x0": "legacy", + "0x1": "eip2930", + "0x2": "eip1559", + "0x3": "eip4844", + "0x4": "eip7702" +}; +function formatTransaction(transaction) { + const transaction_ = { + ...transaction, + blockHash: transaction.blockHash ? transaction.blockHash : null, + blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null, + chainId: transaction.chainId ? hexToNumber(transaction.chainId) : void 0, + gas: transaction.gas ? BigInt(transaction.gas) : void 0, + gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0, + maxFeePerBlobGas: transaction.maxFeePerBlobGas ? BigInt(transaction.maxFeePerBlobGas) : void 0, + maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0, + nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0, + to: transaction.to ? transaction.to : null, + transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null, + type: transaction.type ? transactionType[transaction.type] : void 0, + typeHex: transaction.type ? transaction.type : void 0, + value: transaction.value ? BigInt(transaction.value) : void 0, + v: transaction.v ? BigInt(transaction.v) : void 0 + }; + if (transaction.authorizationList) + transaction_.authorizationList = formatAuthorizationList2(transaction.authorizationList); + transaction_.yParity = (() => { + if (transaction.yParity) + return Number(transaction.yParity); + if (typeof transaction_.v === "bigint") { + if (transaction_.v === 0n || transaction_.v === 27n) + return 0; + if (transaction_.v === 1n || transaction_.v === 28n) + return 1; + if (transaction_.v >= 35n) + return transaction_.v % 2n === 0n ? 1 : 0; + } + return void 0; + })(); + if (transaction_.type === "legacy") { + delete transaction_.accessList; + delete transaction_.maxFeePerBlobGas; + delete transaction_.maxFeePerGas; + delete transaction_.maxPriorityFeePerGas; + delete transaction_.yParity; + } + if (transaction_.type === "eip2930") { + delete transaction_.maxFeePerBlobGas; + delete transaction_.maxFeePerGas; + delete transaction_.maxPriorityFeePerGas; + } + if (transaction_.type === "eip1559") { + delete transaction_.maxFeePerBlobGas; + } + return transaction_; +} +function formatAuthorizationList2(authorizationList) { + return authorizationList.map((authorization) => ({ + address: authorization.address, + chainId: Number(authorization.chainId), + nonce: Number(authorization.nonce), + r: authorization.r, + s: authorization.s, + yParity: Number(authorization.yParity) + })); +} + +// node_modules/viem/_esm/utils/formatters/block.js +function formatBlock(block) { + const transactions = (block.transactions ?? []).map((transaction) => { + if (typeof transaction === "string") + return transaction; + return formatTransaction(transaction); + }); + return { + ...block, + baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null, + blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : void 0, + difficulty: block.difficulty ? BigInt(block.difficulty) : void 0, + excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : void 0, + gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0, + gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0, + hash: block.hash ? block.hash : null, + logsBloom: block.logsBloom ? block.logsBloom : null, + nonce: block.nonce ? block.nonce : null, + number: block.number ? BigInt(block.number) : null, + size: block.size ? BigInt(block.size) : void 0, + timestamp: block.timestamp ? BigInt(block.timestamp) : void 0, + transactions, + totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null + }; +} + +// node_modules/viem/_esm/actions/public/getBlock.js +async function getBlock(client, { blockHash, blockNumber, blockTag: blockTag_, includeTransactions: includeTransactions_ } = {}) { + const blockTag = blockTag_ ?? "latest"; + const includeTransactions = includeTransactions_ ?? false; + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + let block = null; + if (blockHash) { + block = await client.request({ + method: "eth_getBlockByHash", + params: [blockHash, includeTransactions] + }, { dedupe: true }); + } else { + block = await client.request({ + method: "eth_getBlockByNumber", + params: [blockNumberHex || blockTag, includeTransactions] + }, { dedupe: Boolean(blockNumberHex) }); + } + if (!block) + throw new BlockNotFoundError({ blockHash, blockNumber }); + const format = client.chain?.formatters?.block?.format || formatBlock; + return format(block); +} + +// node_modules/viem/_esm/actions/public/getGasPrice.js +async function getGasPrice(client) { + const gasPrice = await client.request({ + method: "eth_gasPrice" + }); + return BigInt(gasPrice); +} + +// node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js +async function estimateMaxPriorityFeePerGas(client, args) { + return internal_estimateMaxPriorityFeePerGas(client, args); +} +async function internal_estimateMaxPriorityFeePerGas(client, args) { + const { block: block_, chain = client.chain, request } = args || {}; + try { + const maxPriorityFeePerGas = chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee; + if (typeof maxPriorityFeePerGas === "function") { + const block = block_ || await getAction(client, getBlock, "getBlock")({}); + const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({ + block, + client, + request + }); + if (maxPriorityFeePerGas_ === null) + throw new Error(); + return maxPriorityFeePerGas_; + } + if (typeof maxPriorityFeePerGas !== "undefined") + return maxPriorityFeePerGas; + const maxPriorityFeePerGasHex = await client.request({ + method: "eth_maxPriorityFeePerGas" + }); + return hexToBigInt(maxPriorityFeePerGasHex); + } catch { + const [block, gasPrice] = await Promise.all([ + block_ ? Promise.resolve(block_) : getAction(client, getBlock, "getBlock")({}), + getAction(client, getGasPrice, "getGasPrice")({}) + ]); + if (typeof block.baseFeePerGas !== "bigint") + throw new Eip1559FeesNotSupportedError(); + const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas; + if (maxPriorityFeePerGas < 0n) + return 0n; + return maxPriorityFeePerGas; + } +} + +// node_modules/viem/_esm/actions/public/estimateFeesPerGas.js +async function estimateFeesPerGas(client, args) { + return internal_estimateFeesPerGas(client, args); +} +async function internal_estimateFeesPerGas(client, args) { + const { block: block_, chain = client.chain, request, type = "eip1559" } = args || {}; + const baseFeeMultiplier = await (async () => { + if (typeof chain?.fees?.baseFeeMultiplier === "function") + return chain.fees.baseFeeMultiplier({ + block: block_, + client, + request + }); + return chain?.fees?.baseFeeMultiplier ?? 1.2; + })(); + if (baseFeeMultiplier < 1) + throw new BaseFeeScalarError(); + const decimals = baseFeeMultiplier.toString().split(".")[1]?.length ?? 0; + const denominator = 10 ** decimals; + const multiply = (base) => base * BigInt(Math.ceil(baseFeeMultiplier * denominator)) / BigInt(denominator); + const block = block_ ? block_ : await getAction(client, getBlock, "getBlock")({}); + if (typeof chain?.fees?.estimateFeesPerGas === "function") { + const fees = await chain.fees.estimateFeesPerGas({ + block: block_, + client, + multiply, + request, + type + }); + if (fees !== null) + return fees; + } + if (type === "eip1559") { + if (typeof block.baseFeePerGas !== "bigint") + throw new Eip1559FeesNotSupportedError(); + const maxPriorityFeePerGas = typeof request?.maxPriorityFeePerGas === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, { + block, + chain, + request + }); + const baseFeePerGas = multiply(block.baseFeePerGas); + const maxFeePerGas = request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas; + return { + maxFeePerGas, + maxPriorityFeePerGas + }; + } + const gasPrice = request?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({})); + return { + gasPrice + }; +} + +// node_modules/viem/_esm/actions/public/getTransactionCount.js +init_fromHex(); +init_toHex(); +async function getTransactionCount(client, { address, blockTag = "latest", blockNumber }) { + const count = await client.request({ + method: "eth_getTransactionCount", + params: [address, blockNumber ? numberToHex(blockNumber) : blockTag] + }, { dedupe: Boolean(blockNumber) }); + return hexToNumber(count); +} + +// node_modules/viem/_esm/utils/blob/blobsToCommitments.js +init_toBytes(); +init_toHex(); +function blobsToCommitments(parameters) { + const { kzg } = parameters; + const to2 = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); + const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x2) => hexToBytes(x2)) : parameters.blobs; + const commitments = []; + for (const blob of blobs) + commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob))); + return to2 === "bytes" ? commitments : commitments.map((x2) => bytesToHex(x2)); +} + +// node_modules/viem/_esm/utils/blob/blobsToProofs.js +init_toBytes(); +init_toHex(); +function blobsToProofs(parameters) { + const { kzg } = parameters; + const to2 = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); + const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x2) => hexToBytes(x2)) : parameters.blobs; + const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x2) => hexToBytes(x2)) : parameters.commitments; + const proofs = []; + for (let i = 0; i < blobs.length; i++) { + const blob = blobs[i]; + const commitment = commitments[i]; + proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment))); + } + return to2 === "bytes" ? proofs : proofs.map((x2) => bytesToHex(x2)); +} + +// node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js +init_toHex(); + +// node_modules/viem/_esm/utils/hash/sha256.js +init_sha256(); +init_isHex(); +init_toBytes(); +init_toHex(); +function sha2562(value, to_) { + const to2 = to_ || "hex"; + const bytes = sha256(isHex(value, { strict: false }) ? toBytes(value) : value); + if (to2 === "bytes") + return bytes; + return toHex(bytes); +} + +// node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js +function commitmentToVersionedHash(parameters) { + const { commitment, version: version4 = 1 } = parameters; + const to2 = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes"); + const versionedHash = sha2562(commitment, "bytes"); + versionedHash.set([version4], 0); + return to2 === "bytes" ? versionedHash : bytesToHex(versionedHash); +} + +// node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js +function commitmentsToVersionedHashes(parameters) { + const { commitments, version: version4 } = parameters; + const to2 = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes"); + const hashes = []; + for (const commitment of commitments) { + hashes.push(commitmentToVersionedHash({ + commitment, + to: to2, + version: version4 + })); + } + return hashes; +} + +// node_modules/viem/_esm/constants/blob.js +var blobsPerTransaction = 6; +var bytesPerFieldElement = 32; +var fieldElementsPerBlob = 4096; +var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob; +var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80). +1 - // zero byte (0x00) appended to each field element. +1 * fieldElementsPerBlob * blobsPerTransaction; + +// node_modules/viem/_esm/constants/kzg.js +var versionedHashVersionKzg = 1; + +// node_modules/viem/_esm/errors/blob.js +init_base(); +var BlobSizeTooLargeError = class extends BaseError2 { + constructor({ maxSize, size: size5 }) { + super("Blob size is too large.", { + metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size5} bytes`], + name: "BlobSizeTooLargeError" + }); + } +}; +var EmptyBlobError = class extends BaseError2 { + constructor() { + super("Blob data must not be empty.", { name: "EmptyBlobError" }); + } +}; +var InvalidVersionedHashSizeError = class extends BaseError2 { + constructor({ hash: hash2, size: size5 }) { + super(`Versioned hash "${hash2}" size is invalid.`, { + metaMessages: ["Expected: 32", `Received: ${size5}`], + name: "InvalidVersionedHashSizeError" + }); + } +}; +var InvalidVersionedHashVersionError = class extends BaseError2 { + constructor({ hash: hash2, version: version4 }) { + super(`Versioned hash "${hash2}" version is invalid.`, { + metaMessages: [ + `Expected: ${versionedHashVersionKzg}`, + `Received: ${version4}` + ], + name: "InvalidVersionedHashVersionError" + }); + } +}; + +// node_modules/viem/_esm/utils/blob/toBlobs.js +init_cursor2(); +init_size(); +init_toBytes(); +init_toHex(); +function toBlobs(parameters) { + const to2 = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes"); + const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data; + const size_ = size(data); + if (!size_) + throw new EmptyBlobError(); + if (size_ > maxBytesPerTransaction) + throw new BlobSizeTooLargeError({ + maxSize: maxBytesPerTransaction, + size: size_ + }); + const blobs = []; + let active = true; + let position = 0; + while (active) { + const blob = createCursor(new Uint8Array(bytesPerBlob)); + let size5 = 0; + while (size5 < fieldElementsPerBlob) { + const bytes = data.slice(position, position + (bytesPerFieldElement - 1)); + blob.pushByte(0); + blob.pushBytes(bytes); + if (bytes.length < 31) { + blob.pushByte(128); + active = false; + break; + } + size5++; + position += 31; + } + blobs.push(blob); + } + return to2 === "bytes" ? blobs.map((x2) => x2.bytes) : blobs.map((x2) => bytesToHex(x2.bytes)); +} + +// node_modules/viem/_esm/utils/blob/toBlobSidecars.js +function toBlobSidecars(parameters) { + const { data, kzg, to: to2 } = parameters; + const blobs = parameters.blobs ?? toBlobs({ data, to: to2 }); + const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to: to2 }); + const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to: to2 }); + const sidecars = []; + for (let i = 0; i < blobs.length; i++) + sidecars.push({ + blob: blobs[i], + commitment: commitments[i], + proof: proofs[i] + }); + return sidecars; +} + +// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js +init_assertRequest(); + +// node_modules/viem/_esm/utils/transaction/getTransactionType.js +init_transaction(); +function getTransactionType(transaction) { + if (transaction.type) + return transaction.type; + if (typeof transaction.authorizationList !== "undefined") + return "eip7702"; + if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined") + return "eip4844"; + if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") { + return "eip1559"; + } + if (typeof transaction.gasPrice !== "undefined") { + if (typeof transaction.accessList !== "undefined") + return "eip2930"; + return "legacy"; + } + throw new InvalidSerializableTransactionError({ transaction }); +} + +// node_modules/viem/_esm/actions/public/getChainId.js +init_fromHex(); +async function getChainId(client) { + const chainIdHex = await client.request({ + method: "eth_chainId" + }, { dedupe: true }); + return hexToNumber(chainIdHex); +} + +// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js +var defaultParameters = [ + "blobVersionedHashes", + "chainId", + "fees", + "gas", + "nonce", + "type" +]; +var eip1559NetworkCache = /* @__PURE__ */ new Map(); +async function prepareTransactionRequest(client, args) { + const { account: account_ = client.account, blobs, chain, gas, kzg, nonce, nonceManager, parameters = defaultParameters, type } = args; + const account = account_ ? parseAccount(account_) : account_; + const request = { ...args, ...account ? { from: account?.address } : {} }; + let block; + async function getBlock2() { + if (block) + return block; + block = await getAction(client, getBlock, "getBlock")({ blockTag: "latest" }); + return block; + } + let chainId; + async function getChainId2() { + if (chainId) + return chainId; + if (chain) + return chain.id; + if (typeof args.chainId !== "undefined") + return args.chainId; + const chainId_ = await getAction(client, getChainId, "getChainId")({}); + chainId = chainId_; + return chainId; + } + if (parameters.includes("nonce") && typeof nonce === "undefined" && account) { + if (nonceManager) { + const chainId2 = await getChainId2(); + request.nonce = await nonceManager.consume({ + address: account.address, + chainId: chainId2, + client + }); + } else { + request.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({ + address: account.address, + blockTag: "pending" + }); + } + } + if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) { + const commitments = blobsToCommitments({ blobs, kzg }); + if (parameters.includes("blobVersionedHashes")) { + const versionedHashes = commitmentsToVersionedHashes({ + commitments, + to: "hex" + }); + request.blobVersionedHashes = versionedHashes; + } + if (parameters.includes("sidecars")) { + const proofs = blobsToProofs({ blobs, commitments, kzg }); + const sidecars = toBlobSidecars({ + blobs, + commitments, + proofs, + to: "hex" + }); + request.sidecars = sidecars; + } + } + if (parameters.includes("chainId")) + request.chainId = await getChainId2(); + if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") { + try { + request.type = getTransactionType(request); + } catch { + let isEip1559Network = eip1559NetworkCache.get(client.uid); + if (typeof isEip1559Network === "undefined") { + const block2 = await getBlock2(); + isEip1559Network = typeof block2?.baseFeePerGas === "bigint"; + eip1559NetworkCache.set(client.uid, isEip1559Network); + } + request.type = isEip1559Network ? "eip1559" : "legacy"; + } + } + if (parameters.includes("fees")) { + if (request.type !== "legacy" && request.type !== "eip2930") { + if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") { + const block2 = await getBlock2(); + const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client, { + block: block2, + chain, + request + }); + if (typeof args.maxPriorityFeePerGas === "undefined" && args.maxFeePerGas && args.maxFeePerGas < maxPriorityFeePerGas) + throw new MaxFeePerGasTooLowError({ + maxPriorityFeePerGas + }); + request.maxPriorityFeePerGas = maxPriorityFeePerGas; + request.maxFeePerGas = maxFeePerGas; + } + } else { + if (typeof args.maxFeePerGas !== "undefined" || typeof args.maxPriorityFeePerGas !== "undefined") + throw new Eip1559FeesNotSupportedError(); + if (typeof args.gasPrice === "undefined") { + const block2 = await getBlock2(); + const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, { + block: block2, + chain, + request, + type: "legacy" + }); + request.gasPrice = gasPrice_; + } + } + } + if (parameters.includes("gas") && typeof gas === "undefined") + request.gas = await getAction(client, estimateGas, "estimateGas")({ + ...request, + account: account ? { address: account.address, type: "json-rpc" } : account + }); + assertRequest(request); + delete request.parameters; + return request; +} + +// node_modules/viem/_esm/actions/public/getBalance.js +init_toHex(); +async function getBalance(client, { address, blockNumber, blockTag = "latest" }) { + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const balance = await client.request({ + method: "eth_getBalance", + params: [address, blockNumberHex || blockTag] + }); + return BigInt(balance); +} + +// node_modules/viem/_esm/actions/public/estimateGas.js +async function estimateGas(client, args) { + const { account: account_ = client.account } = args; + const account = account_ ? parseAccount(account_) : void 0; + try { + let estimateGas_rpc = function(parameters) { + const { block: block2, request: request2, rpcStateOverride: rpcStateOverride2 } = parameters; + return client.request({ + method: "eth_estimateGas", + params: rpcStateOverride2 ? [request2, block2 ?? "latest", rpcStateOverride2] : block2 ? [request2, block2] : [request2] + }); + }; + const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = await prepareTransactionRequest(client, { + ...args, + parameters: ( + // Some RPC Providers do not compute versioned hashes from blobs. We will need + // to compute them. + account?.type === "local" ? void 0 : ["blobVersionedHashes"] + ) + }); + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const rpcStateOverride = serializeStateOverride(stateOverride); + const to2 = await (async () => { + if (rest.to) + return rest.to; + if (authorizationList && authorizationList.length > 0) + return await recoverAuthorizationAddress({ + authorization: authorizationList[0] + }).catch(() => { + throw new BaseError2("`to` is required. Could not infer from `authorizationList`"); + }); + return void 0; + })(); + assertRequest(args); + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format = chainFormat || formatTransactionRequest; + const request = format({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + from: account?.address, + accessList, + authorizationList, + blobs, + blobVersionedHashes, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to: to2, + value + }); + let estimate = BigInt(await estimateGas_rpc({ block, request, rpcStateOverride })); + if (authorizationList) { + const value2 = await getBalance(client, { address: request.from }); + const estimates = await Promise.all(authorizationList.map(async (authorization) => { + const { address } = authorization; + const estimate2 = await estimateGas_rpc({ + block, + request: { + authorizationList: void 0, + data, + from: account?.address, + to: address, + value: numberToHex(value2) + }, + rpcStateOverride + }).catch(() => 100000n); + return 2n * BigInt(estimate2); + })); + estimate += estimates.reduce((acc, curr) => acc + curr, 0n); + } + return estimate; + } catch (err) { + throw getEstimateGasError(err, { + ...args, + account, + chain: client.chain + }); + } +} + +// node_modules/viem/_esm/actions/public/estimateContractGas.js +async function estimateContractGas(client, parameters) { + const { abi: abi4, address, args, functionName, dataSuffix, ...request } = parameters; + const data = encodeFunctionData({ + abi: abi4, + args, + functionName + }); + try { + const gas = await getAction(client, estimateGas, "estimateGas")({ + data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, + to: address, + ...request + }); + return gas; + } catch (error) { + const account = request.account ? parseAccount(request.account) : void 0; + throw getContractError(error, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/estimateContractGas", + functionName, + sender: account?.address + }); + } +} + +// node_modules/viem/_esm/actions/public/getContractEvents.js +init_getAbiItem(); + +// node_modules/viem/_esm/utils/abi/parseEventLogs.js +init_abi(); +init_isAddressEqual(); +init_toBytes(); +init_keccak256(); +init_toEventSelector(); + +// node_modules/viem/_esm/utils/abi/decodeEventLog.js +init_abi(); +init_size(); +init_toEventSelector(); +init_cursor(); +init_decodeAbiParameters(); +init_formatAbiItem2(); +var docsPath3 = "/docs/contract/decodeEventLog"; +function decodeEventLog(parameters) { + const { abi: abi4, data, strict: strict_, topics } = parameters; + const strict = strict_ ?? true; + const [signature, ...argTopics] = topics; + if (!signature) + throw new AbiEventSignatureEmptyTopicsError({ docsPath: docsPath3 }); + const abiItem = (() => { + if (abi4.length === 1) + return abi4[0]; + return abi4.find((x2) => x2.type === "event" && signature === toEventSelector(formatAbiItem2(x2))); + })(); + if (!(abiItem && "name" in abiItem) || abiItem.type !== "event") + throw new AbiEventSignatureNotFoundError(signature, { docsPath: docsPath3 }); + const { name, inputs } = abiItem; + const isUnnamed = inputs?.some((x2) => !("name" in x2 && x2.name)); + let args = isUnnamed ? [] : {}; + const indexedInputs = inputs.filter((x2) => "indexed" in x2 && x2.indexed); + for (let i = 0; i < indexedInputs.length; i++) { + const param = indexedInputs[i]; + const topic = argTopics[i]; + if (!topic) + throw new DecodeLogTopicsMismatch({ + abiItem, + param + }); + args[isUnnamed ? i : param.name || i] = decodeTopic({ param, value: topic }); + } + const nonIndexedInputs = inputs.filter((x2) => !("indexed" in x2 && x2.indexed)); + if (nonIndexedInputs.length > 0) { + if (data && data !== "0x") { + try { + const decodedData = decodeAbiParameters(nonIndexedInputs, data); + if (decodedData) { + if (isUnnamed) + args = [...args, ...decodedData]; + else { + for (let i = 0; i < nonIndexedInputs.length; i++) { + args[nonIndexedInputs[i].name] = decodedData[i]; + } + } + } + } catch (err) { + if (strict) { + if (err instanceof AbiDecodingDataSizeTooSmallError || err instanceof PositionOutOfBoundsError) + throw new DecodeLogDataMismatch({ + abiItem, + data, + params: nonIndexedInputs, + size: size(data) + }); + throw err; + } + } + } else if (strict) { + throw new DecodeLogDataMismatch({ + abiItem, + data: "0x", + params: nonIndexedInputs, + size: 0 + }); + } + } + return { + eventName: name, + args: Object.values(args).length > 0 ? args : void 0 + }; +} +function decodeTopic({ param, value }) { + if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) + return value; + const decodedArg = decodeAbiParameters([param], value) || []; + return decodedArg[0]; +} + +// node_modules/viem/_esm/utils/abi/parseEventLogs.js +function parseEventLogs(parameters) { + const { abi: abi4, args, logs, strict = true } = parameters; + const eventName = (() => { + if (!parameters.eventName) + return void 0; + if (Array.isArray(parameters.eventName)) + return parameters.eventName; + return [parameters.eventName]; + })(); + return logs.map((log) => { + try { + const abiItem = abi4.find((abiItem2) => abiItem2.type === "event" && log.topics[0] === toEventSelector(abiItem2)); + if (!abiItem) + return null; + const event = decodeEventLog({ + ...log, + abi: [abiItem], + strict + }); + if (eventName && !eventName.includes(event.eventName)) + return null; + if (!includesArgs({ + args: event.args, + inputs: abiItem.inputs, + matchArgs: args + })) + return null; + return { ...event, ...log }; + } catch (err) { + let eventName2; + let isUnnamed; + if (err instanceof AbiEventSignatureNotFoundError) + return null; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict) + return null; + eventName2 = err.abiItem.name; + isUnnamed = err.abiItem.inputs?.some((x2) => !("name" in x2 && x2.name)); + } + return { ...log, args: isUnnamed ? [] : {}, eventName: eventName2 }; + } + }).filter(Boolean); +} +function includesArgs(parameters) { + const { args, inputs, matchArgs } = parameters; + if (!matchArgs) + return true; + if (!args) + return false; + function isEqual(input, value, arg) { + try { + if (input.type === "address") + return isAddressEqual(value, arg); + if (input.type === "string" || input.type === "bytes") + return keccak256(toBytes(value)) === arg; + return value === arg; + } catch { + return false; + } + } + if (Array.isArray(args) && Array.isArray(matchArgs)) { + return matchArgs.every((value, index2) => { + if (value === null || value === void 0) + return true; + const input = inputs[index2]; + if (!input) + return false; + const value_ = Array.isArray(value) ? value : [value]; + return value_.some((value2) => isEqual(input, value2, args[index2])); + }); + } + if (typeof args === "object" && !Array.isArray(args) && typeof matchArgs === "object" && !Array.isArray(matchArgs)) + return Object.entries(matchArgs).every(([key, value]) => { + if (value === null || value === void 0) + return true; + const input = inputs.find((input2) => input2.name === key); + if (!input) + return false; + const value_ = Array.isArray(value) ? value : [value]; + return value_.some((value2) => isEqual(input, value2, args[key])); + }); + return false; +} + +// node_modules/viem/_esm/actions/public/getLogs.js +init_toHex(); + +// node_modules/viem/_esm/utils/formatters/log.js +function formatLog(log, { args, eventName } = {}) { + return { + ...log, + blockHash: log.blockHash ? log.blockHash : null, + blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null, + logIndex: log.logIndex ? Number(log.logIndex) : null, + transactionHash: log.transactionHash ? log.transactionHash : null, + transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null, + ...eventName ? { args, eventName } : {} + }; +} + +// node_modules/viem/_esm/actions/public/getLogs.js +async function getLogs(client, { address, blockHash, fromBlock, toBlock, event, events: events_, args, strict: strict_ } = {}) { + const strict = strict_ ?? false; + const events = events_ ?? (event ? [event] : void 0); + let topics = []; + if (events) { + const encoded = events.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args: events_ ? void 0 : args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + let logs; + if (blockHash) { + logs = await client.request({ + method: "eth_getLogs", + params: [{ address, topics, blockHash }] + }); + } else { + logs = await client.request({ + method: "eth_getLogs", + params: [ + { + address, + topics, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock + } + ] + }); + } + const formattedLogs = logs.map((log) => formatLog(log)); + if (!events) + return formattedLogs; + return parseEventLogs({ + abi: events, + args, + logs: formattedLogs, + strict + }); +} + +// node_modules/viem/_esm/actions/public/getContractEvents.js +async function getContractEvents(client, parameters) { + const { abi: abi4, address, args, blockHash, eventName, fromBlock, toBlock, strict } = parameters; + const event = eventName ? getAbiItem({ abi: abi4, name: eventName }) : void 0; + const events = !event ? abi4.filter((x2) => x2.type === "event") : void 0; + return getAction(client, getLogs, "getLogs")({ + address, + args, + blockHash, + event, + events, + fromBlock, + toBlock, + strict + }); +} + +// node_modules/viem/_esm/actions/public/readContract.js +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_call(); +async function readContract(client, parameters) { + const { abi: abi4, address, args, functionName, ...rest } = parameters; + const calldata = encodeFunctionData({ + abi: abi4, + args, + functionName + }); + try { + const { data } = await getAction(client, call, "call")({ + ...rest, + data: calldata, + to: address + }); + return decodeFunctionResult({ + abi: abi4, + args, + functionName, + data: data || "0x" + }); + } catch (error) { + throw getContractError(error, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/readContract", + functionName + }); + } +} + +// node_modules/viem/_esm/actions/public/simulateContract.js +init_parseAccount(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_call(); +async function simulateContract(client, parameters) { + const { abi: abi4, address, args, dataSuffix, functionName, ...callRequest } = parameters; + const account = callRequest.account ? parseAccount(callRequest.account) : client.account; + const calldata = encodeFunctionData({ abi: abi4, args, functionName }); + try { + const { data } = await getAction(client, call, "call")({ + batch: false, + data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, + to: address, + ...callRequest, + account + }); + const result = decodeFunctionResult({ + abi: abi4, + args, + functionName, + data: data || "0x" + }); + const minimizedAbi = abi4.filter((abiItem) => "name" in abiItem && abiItem.name === parameters.functionName); + return { + result, + request: { + abi: minimizedAbi, + address, + args, + dataSuffix, + functionName, + ...callRequest, + account + } + }; + } catch (error) { + throw getContractError(error, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/simulateContract", + functionName, + sender: account?.address + }); + } +} + +// node_modules/viem/_esm/actions/public/watchContractEvent.js +init_abi(); +init_rpc(); + +// node_modules/viem/_esm/utils/observe.js +var listenersCache = /* @__PURE__ */ new Map(); +var cleanupCache = /* @__PURE__ */ new Map(); +var callbackCount = 0; +function observe(observerId, callbacks, fn2) { + const callbackId = ++callbackCount; + const getListeners = () => listenersCache.get(observerId) || []; + const unsubscribe = () => { + const listeners2 = getListeners(); + listenersCache.set(observerId, listeners2.filter((cb) => cb.id !== callbackId)); + }; + const unwatch = () => { + const listeners2 = getListeners(); + if (!listeners2.some((cb) => cb.id === callbackId)) + return; + const cleanup2 = cleanupCache.get(observerId); + if (listeners2.length === 1 && cleanup2) + cleanup2(); + unsubscribe(); + }; + const listeners = getListeners(); + listenersCache.set(observerId, [ + ...listeners, + { id: callbackId, fns: callbacks } + ]); + if (listeners && listeners.length > 0) + return unwatch; + const emit = {}; + for (const key in callbacks) { + emit[key] = (...args) => { + const listeners2 = getListeners(); + if (listeners2.length === 0) + return; + for (const listener of listeners2) + listener.fns[key]?.(...args); + }; + } + const cleanup = fn2(emit); + if (typeof cleanup === "function") + cleanupCache.set(observerId, cleanup); + return unwatch; +} + +// node_modules/viem/_esm/utils/wait.js +async function wait(time) { + return new Promise((res) => setTimeout(res, time)); +} + +// node_modules/viem/_esm/utils/poll.js +function poll(fn2, { emitOnBegin, initialWaitTime, interval }) { + let active = true; + const unwatch = () => active = false; + const watch = async () => { + let data = void 0; + if (emitOnBegin) + data = await fn2({ unpoll: unwatch }); + const initialWait = await initialWaitTime?.(data) ?? interval; + await wait(initialWait); + const poll2 = async () => { + if (!active) + return; + await fn2({ unpoll: unwatch }); + await wait(interval); + poll2(); + }; + poll2(); + }; + watch(); + return unwatch; +} + +// node_modules/viem/_esm/actions/public/watchContractEvent.js +init_stringify(); + +// node_modules/viem/_esm/utils/promise/withCache.js +var promiseCache = /* @__PURE__ */ new Map(); +var responseCache = /* @__PURE__ */ new Map(); +function getCache(cacheKey2) { + const buildCache = (cacheKey3, cache) => ({ + clear: () => cache.delete(cacheKey3), + get: () => cache.get(cacheKey3), + set: (data) => cache.set(cacheKey3, data) + }); + const promise = buildCache(cacheKey2, promiseCache); + const response = buildCache(cacheKey2, responseCache); + return { + clear: () => { + promise.clear(); + response.clear(); + }, + promise, + response + }; +} +async function withCache(fn2, { cacheKey: cacheKey2, cacheTime = Number.POSITIVE_INFINITY }) { + const cache = getCache(cacheKey2); + const response = cache.response.get(); + if (response && cacheTime > 0) { + const age = (/* @__PURE__ */ new Date()).getTime() - response.created.getTime(); + if (age < cacheTime) + return response.data; + } + let promise = cache.promise.get(); + if (!promise) { + promise = fn2(); + cache.promise.set(promise); + } + try { + const data = await promise; + cache.response.set({ created: /* @__PURE__ */ new Date(), data }); + return data; + } finally { + cache.promise.clear(); + } +} + +// node_modules/viem/_esm/actions/public/getBlockNumber.js +var cacheKey = (id2) => `blockNumber.${id2}`; +async function getBlockNumber(client, { cacheTime = client.cacheTime } = {}) { + const blockNumberHex = await withCache(() => client.request({ + method: "eth_blockNumber" + }), { cacheKey: cacheKey(client.uid), cacheTime }); + return BigInt(blockNumberHex); +} + +// node_modules/viem/_esm/actions/public/getFilterChanges.js +async function getFilterChanges(_client, { filter: filter2 }) { + const strict = "strict" in filter2 && filter2.strict; + const logs = await filter2.request({ + method: "eth_getFilterChanges", + params: [filter2.id] + }); + if (typeof logs[0] === "string") + return logs; + const formattedLogs = logs.map((log) => formatLog(log)); + if (!("abi" in filter2) || !filter2.abi) + return formattedLogs; + return parseEventLogs({ + abi: filter2.abi, + logs: formattedLogs, + strict + }); +} + +// node_modules/viem/_esm/actions/public/uninstallFilter.js +async function uninstallFilter(_client, { filter: filter2 }) { + return filter2.request({ + method: "eth_uninstallFilter", + params: [filter2.id] + }); +} + +// node_modules/viem/_esm/actions/public/watchContractEvent.js +function watchContractEvent(client, parameters) { + const { abi: abi4, address, args, batch = true, eventName, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ } = parameters; + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (typeof fromBlock === "bigint") + return true; + if (client.transport.type === "webSocket") + return false; + if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + const pollContractEvent = () => { + const strict = strict_ ?? false; + const observerId = stringify([ + "watchContractEvent", + address, + args, + batch, + client.uid, + eventName, + pollingInterval, + strict, + fromBlock + ]); + return observe(observerId, { onLogs, onError }, (emit) => { + let previousBlockNumber; + if (fromBlock !== void 0) + previousBlockNumber = fromBlock - 1n; + let filter2; + let initialized = false; + const unwatch = poll(async () => { + if (!initialized) { + try { + filter2 = await getAction(client, createContractEventFilter, "createContractEventFilter")({ + abi: abi4, + address, + args, + eventName, + strict, + fromBlock + }); + } catch { + } + initialized = true; + return; + } + try { + let logs; + if (filter2) { + logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter: filter2 }); + } else { + const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({}); + if (previousBlockNumber && previousBlockNumber < blockNumber) { + logs = await getAction(client, getContractEvents, "getContractEvents")({ + abi: abi4, + address, + args, + eventName, + fromBlock: previousBlockNumber + 1n, + toBlock: blockNumber, + strict + }); + } else { + logs = []; + } + previousBlockNumber = blockNumber; + } + if (logs.length === 0) + return; + if (batch) + emit.onLogs(logs); + else + for (const log of logs) + emit.onLogs([log]); + } catch (err) { + if (filter2 && err instanceof InvalidInputRpcError) + initialized = false; + emit.onError?.(err); + } + }, { + emitOnBegin: true, + interval: pollingInterval + }); + return async () => { + if (filter2) + await getAction(client, uninstallFilter, "uninstallFilter")({ filter: filter2 }); + unwatch(); + }; + }); + }; + const subscribeContractEvent = () => { + const strict = strict_ ?? false; + const observerId = stringify([ + "watchContractEvent", + address, + args, + batch, + client.uid, + eventName, + pollingInterval, + strict + ]); + let active = true; + let unsubscribe = () => active = false; + return observe(observerId, { onLogs, onError }, (emit) => { + ; + (async () => { + try { + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const topics = eventName ? encodeEventTopics({ + abi: abi4, + eventName, + args + }) : []; + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["logs", { address, topics }], + onData(data) { + if (!active) + return; + const log = data.result; + try { + const { eventName: eventName2, args: args2 } = decodeEventLog({ + abi: abi4, + data: log.data, + topics: log.topics, + strict: strict_ + }); + const formatted = formatLog(log, { + args: args2, + eventName: eventName2 + }); + emit.onLogs([formatted]); + } catch (err) { + let eventName2; + let isUnnamed; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict_) + return; + eventName2 = err.abiItem.name; + isUnnamed = err.abiItem.inputs?.some((x2) => !("name" in x2 && x2.name)); + } + const formatted = formatLog(log, { + args: isUnnamed ? [] : {}, + eventName: eventName2 + }); + emit.onLogs([formatted]); + } + }, + onError(error) { + emit.onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }); + }; + return enablePolling ? pollContractEvent() : subscribeContractEvent(); +} + +// node_modules/viem/_esm/actions/wallet/writeContract.js +init_parseAccount(); + +// node_modules/viem/_esm/errors/account.js +init_base(); +var AccountNotFoundError = class extends BaseError2 { + constructor({ docsPath: docsPath6 } = {}) { + super([ + "Could not find an Account to execute with this Action.", + "Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client." + ].join("\n"), { + docsPath: docsPath6, + docsSlug: "account", + name: "AccountNotFoundError" + }); + } +}; +var AccountTypeNotSupportedError = class extends BaseError2 { + constructor({ docsPath: docsPath6, metaMessages, type }) { + super(`Account type "${type}" is not supported.`, { + docsPath: docsPath6, + metaMessages, + name: "AccountTypeNotSupportedError" + }); + } +}; + +// node_modules/viem/_esm/actions/wallet/writeContract.js +init_encodeFunctionData(); + +// node_modules/viem/_esm/actions/wallet/sendTransaction.js +init_parseAccount(); +init_base(); + +// node_modules/viem/_esm/utils/chain/assertCurrentChain.js +init_chain(); +function assertCurrentChain({ chain, currentChainId }) { + if (!chain) + throw new ChainNotFoundError(); + if (currentChainId !== chain.id) + throw new ChainMismatchError({ chain, currentChainId }); +} + +// node_modules/viem/_esm/utils/errors/getTransactionError.js +init_node(); +init_transaction(); +init_getNodeError(); +function getTransactionError(err, { docsPath: docsPath6, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new TransactionExecutionError(cause, { + docsPath: docsPath6, + ...args + }); +} + +// node_modules/viem/_esm/actions/wallet/sendTransaction.js +init_extract(); +init_transactionRequest(); +init_lru(); +init_assertRequest(); + +// node_modules/viem/_esm/actions/wallet/sendRawTransaction.js +async function sendRawTransaction(client, { serializedTransaction }) { + return client.request({ + method: "eth_sendRawTransaction", + params: [serializedTransaction] + }, { retryCount: 0 }); +} + +// node_modules/viem/_esm/actions/wallet/sendTransaction.js +var supportsWalletNamespace = new LruMap(128); +async function sendTransaction(client, parameters) { + const { account: account_ = client.account, chain = client.chain, accessList, authorizationList, blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, ...rest } = parameters; + if (typeof account_ === "undefined") + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/sendTransaction" + }); + const account = account_ ? parseAccount(account_) : null; + try { + assertRequest(parameters); + const to2 = await (async () => { + if (parameters.to) + return parameters.to; + if (parameters.to === null) + return void 0; + if (authorizationList && authorizationList.length > 0) + return await recoverAuthorizationAddress({ + authorization: authorizationList[0] + }).catch(() => { + throw new BaseError2("`to` is required. Could not infer from `authorizationList`."); + }); + return void 0; + })(); + if (account?.type === "json-rpc" || account === null) { + let chainId; + if (chain !== null) { + chainId = await getAction(client, getChainId, "getChainId")({}); + assertCurrentChain({ + currentChainId: chainId, + chain + }); + } + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format = chainFormat || formatTransactionRequest; + const request = format({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + accessList, + authorizationList, + blobs, + chainId, + data, + from: account?.address, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to: to2, + value + }); + const isWalletNamespaceSupported = supportsWalletNamespace.get(client.uid); + const method = isWalletNamespaceSupported ? "wallet_sendTransaction" : "eth_sendTransaction"; + try { + return await client.request({ + method, + params: [request] + }, { retryCount: 0 }); + } catch (e) { + if (isWalletNamespaceSupported === false) + throw e; + const error = e; + if (error.name === "InvalidInputRpcError" || error.name === "InvalidParamsRpcError" || error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError") { + return await client.request({ + method: "wallet_sendTransaction", + params: [request] + }, { retryCount: 0 }).then((hash2) => { + supportsWalletNamespace.set(client.uid, true); + return hash2; + }).catch((e2) => { + const walletNamespaceError = e2; + if (walletNamespaceError.name === "MethodNotFoundRpcError" || walletNamespaceError.name === "MethodNotSupportedRpcError") { + supportsWalletNamespace.set(client.uid, false); + throw error; + } + throw walletNamespaceError; + }); + } + throw error; + } + } + if (account?.type === "local") { + const request = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({ + account, + accessList, + authorizationList, + blobs, + chain, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + nonceManager: account.nonceManager, + parameters: [...defaultParameters, "sidecars"], + value, + ...rest, + to: to2 + }); + const serializer = chain?.serializers?.transaction; + const serializedTransaction = await account.signTransaction(request, { + serializer + }); + return await getAction(client, sendRawTransaction, "sendRawTransaction")({ + serializedTransaction + }); + } + if (account?.type === "smart") + throw new AccountTypeNotSupportedError({ + metaMessages: [ + "Consider using the `sendUserOperation` Action instead." + ], + docsPath: "/docs/actions/bundler/sendUserOperation", + type: "smart" + }); + throw new AccountTypeNotSupportedError({ + docsPath: "/docs/actions/wallet/sendTransaction", + type: account?.type + }); + } catch (err) { + if (err instanceof AccountTypeNotSupportedError) + throw err; + throw getTransactionError(err, { + ...parameters, + account, + chain: parameters.chain || void 0 + }); + } +} + +// node_modules/viem/_esm/actions/wallet/writeContract.js +async function writeContract(client, parameters) { + const { abi: abi4, account: account_ = client.account, address, args, dataSuffix, functionName, ...request } = parameters; + if (typeof account_ === "undefined") + throw new AccountNotFoundError({ + docsPath: "/docs/contract/writeContract" + }); + const account = account_ ? parseAccount(account_) : null; + const data = encodeFunctionData({ + abi: abi4, + args, + functionName + }); + try { + return await getAction(client, sendTransaction, "sendTransaction")({ + data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, + to: address, + account, + ...request + }); + } catch (error) { + throw getContractError(error, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/writeContract", + functionName, + sender: account?.address + }); + } +} + +// node_modules/viem/_esm/errors/eip712.js +init_base(); +var Eip712DomainNotFoundError = class extends BaseError2 { + constructor({ address }) { + super(`No EIP-712 domain found on contract "${address}".`, { + metaMessages: [ + "Ensure that:", + `- The contract is deployed at the address "${address}".`, + "- `eip712Domain()` function exists on the contract.", + "- `eip712Domain()` function matches signature to ERC-5267 specification." + ], + name: "Eip712DomainNotFoundError" + }); + } +}; + +// node_modules/viem/_esm/actions/public/getEip712Domain.js +async function getEip712Domain(client, parameters) { + const { address, factory, factoryData } = parameters; + try { + const [fields, name, version4, chainId, verifyingContract, salt, extensions] = await getAction(client, readContract, "readContract")({ + abi: abi3, + address, + functionName: "eip712Domain", + factory, + factoryData + }); + return { + domain: { + name, + version: version4, + chainId: Number(chainId), + verifyingContract, + salt + }, + extensions, + fields + }; + } catch (e) { + const error = e; + if (error.name === "ContractFunctionExecutionError" && error.cause.name === "ContractFunctionZeroDataError") { + throw new Eip712DomainNotFoundError({ address }); + } + throw error; + } +} +var abi3 = [ + { + inputs: [], + name: "eip712Domain", + outputs: [ + { name: "fields", type: "bytes1" }, + { name: "name", type: "string" }, + { name: "version", type: "string" }, + { name: "chainId", type: "uint256" }, + { name: "verifyingContract", type: "address" }, + { name: "salt", type: "bytes32" }, + { name: "extensions", type: "uint256[]" } + ], + stateMutability: "view", + type: "function" + } +]; + +// node_modules/viem/_esm/actions/wallet/addChain.js +init_toHex(); +async function addChain(client, { chain }) { + const { id: id2, name, nativeCurrency, rpcUrls, blockExplorers } = chain; + await client.request({ + method: "wallet_addEthereumChain", + params: [ + { + chainId: numberToHex(id2), + chainName: name, + nativeCurrency, + rpcUrls: rpcUrls.default.http, + blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url: url2 }) => url2) : void 0 + } + ] + }, { dedupe: true, retryCount: 0 }); +} + +// node_modules/viem/_esm/clients/createClient.js +init_parseAccount(); + +// node_modules/viem/_esm/utils/uid.js +var size2 = 256; +var index = size2; +var buffer; +function uid(length = 11) { + if (!buffer || index + length > size2 * 2) { + buffer = ""; + index = 0; + for (let i = 0; i < size2; i++) { + buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1); + } + } + return buffer.substring(index, index++ + length); +} + +// node_modules/viem/_esm/clients/createClient.js +function createClient(parameters) { + const { batch, cacheTime = parameters.pollingInterval ?? 4e3, ccipRead, key = "base", name = "Base Client", pollingInterval = 4e3, type = "base" } = parameters; + const chain = parameters.chain; + const account = parameters.account ? parseAccount(parameters.account) : void 0; + const { config: config3, request, value } = parameters.transport({ + chain, + pollingInterval + }); + const transport = { ...config3, ...value }; + const client = { + account, + batch, + cacheTime, + ccipRead, + chain, + key, + name, + pollingInterval, + request, + transport, + type, + uid: uid() + }; + function extend2(base) { + return (extendFn) => { + const extended = extendFn(base); + for (const key2 in client) + delete extended[key2]; + const combined = { ...base, ...extended }; + return Object.assign(combined, { extend: extend2(combined) }); + }; + } + return Object.assign(client, { extend: extend2(client) }); +} + +// node_modules/viem/_esm/utils/buildRequest.js +init_base(); +init_request(); +init_rpc(); +init_toHex(); + +// node_modules/viem/_esm/utils/promise/withDedupe.js +init_lru(); +var promiseCache2 = /* @__PURE__ */ new LruMap(8192); +function withDedupe(fn2, { enabled = true, id: id2 }) { + if (!enabled || !id2) + return fn2(); + if (promiseCache2.get(id2)) + return promiseCache2.get(id2); + const promise = fn2().finally(() => promiseCache2.delete(id2)); + promiseCache2.set(id2, promise); + return promise; +} + +// node_modules/viem/_esm/utils/promise/withRetry.js +function withRetry(fn2, { delay: delay_ = 100, retryCount = 2, shouldRetry: shouldRetry2 = () => true } = {}) { + return new Promise((resolve, reject) => { + const attemptRetry = async ({ count = 0 } = {}) => { + const retry = async ({ error }) => { + const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_; + if (delay) + await wait(delay); + attemptRetry({ count: count + 1 }); + }; + try { + const data = await fn2(); + resolve(data); + } catch (err) { + if (count < retryCount && await shouldRetry2({ count, error: err })) + return retry({ error: err }); + reject(err); + } + }; + attemptRetry(); + }); +} + +// node_modules/viem/_esm/utils/buildRequest.js +init_stringify(); +function buildRequest(request, options = {}) { + return async (args, overrideOptions = {}) => { + const { dedupe = false, methods, retryDelay = 150, retryCount = 3, uid: uid2 } = { + ...options, + ...overrideOptions + }; + const { method } = args; + if (methods?.exclude?.includes(method)) + throw new MethodNotSupportedRpcError(new Error("method not supported"), { + method + }); + if (methods?.include && !methods.include.includes(method)) + throw new MethodNotSupportedRpcError(new Error("method not supported"), { + method + }); + const requestId = dedupe ? stringToHex(`${uid2}.${stringify(args)}`) : void 0; + return withDedupe(() => withRetry(async () => { + try { + return await request(args); + } catch (err_) { + const err = err_; + switch (err.code) { + // -32700 + case ParseRpcError.code: + throw new ParseRpcError(err); + // -32600 + case InvalidRequestRpcError.code: + throw new InvalidRequestRpcError(err); + // -32601 + case MethodNotFoundRpcError.code: + throw new MethodNotFoundRpcError(err, { method: args.method }); + // -32602 + case InvalidParamsRpcError.code: + throw new InvalidParamsRpcError(err); + // -32603 + case InternalRpcError.code: + throw new InternalRpcError(err); + // -32000 + case InvalidInputRpcError.code: + throw new InvalidInputRpcError(err); + // -32001 + case ResourceNotFoundRpcError.code: + throw new ResourceNotFoundRpcError(err); + // -32002 + case ResourceUnavailableRpcError.code: + throw new ResourceUnavailableRpcError(err); + // -32003 + case TransactionRejectedRpcError.code: + throw new TransactionRejectedRpcError(err); + // -32004 + case MethodNotSupportedRpcError.code: + throw new MethodNotSupportedRpcError(err, { + method: args.method + }); + // -32005 + case LimitExceededRpcError.code: + throw new LimitExceededRpcError(err); + // -32006 + case JsonRpcVersionUnsupportedError.code: + throw new JsonRpcVersionUnsupportedError(err); + // 4001 + case UserRejectedRequestError.code: + throw new UserRejectedRequestError(err); + // 4100 + case UnauthorizedProviderError.code: + throw new UnauthorizedProviderError(err); + // 4200 + case UnsupportedProviderMethodError.code: + throw new UnsupportedProviderMethodError(err); + // 4900 + case ProviderDisconnectedError.code: + throw new ProviderDisconnectedError(err); + // 4901 + case ChainDisconnectedError.code: + throw new ChainDisconnectedError(err); + // 4902 + case SwitchChainError.code: + throw new SwitchChainError(err); + // CAIP-25: User Rejected Error + // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25 + case 5e3: + throw new UserRejectedRequestError(err); + default: + if (err_ instanceof BaseError2) + throw err_; + throw new UnknownRpcError(err); + } + } + }, { + delay: ({ count, error }) => { + if (error && error instanceof HttpRequestError) { + const retryAfter = error?.headers?.get("Retry-After"); + if (retryAfter?.match(/\d/)) + return Number.parseInt(retryAfter) * 1e3; + } + return ~~(1 << count) * retryDelay; + }, + retryCount, + shouldRetry: ({ error }) => shouldRetry(error) + }), { enabled: dedupe, id: requestId }); + }; +} +function shouldRetry(error) { + if ("code" in error && typeof error.code === "number") { + if (error.code === -1) + return true; + if (error.code === LimitExceededRpcError.code) + return true; + if (error.code === InternalRpcError.code) + return true; + return false; + } + if (error instanceof HttpRequestError && error.status) { + if (error.status === 403) + return true; + if (error.status === 408) + return true; + if (error.status === 413) + return true; + if (error.status === 429) + return true; + if (error.status === 500) + return true; + if (error.status === 502) + return true; + if (error.status === 503) + return true; + if (error.status === 504) + return true; + return false; + } + return true; +} + +// node_modules/viem/_esm/clients/transports/createTransport.js +function createTransport({ key, methods, name, request, retryCount = 3, retryDelay = 150, timeout, type }, value) { + const uid2 = uid(); + return { + config: { + key, + methods, + name, + request, + retryCount, + retryDelay, + timeout, + type + }, + request: buildRequest(request, { methods, retryCount, retryDelay, uid: uid2 }), + value + }; +} + +// node_modules/viem/_esm/clients/transports/fallback.js +init_node(); +init_rpc(); +function fallback(transports_, config3 = {}) { + const { key = "fallback", name = "Fallback", rank = false, shouldThrow: shouldThrow_ = shouldThrow, retryCount, retryDelay } = config3; + return ({ chain, pollingInterval = 4e3, timeout, ...rest }) => { + let transports = transports_; + let onResponse = () => { + }; + const transport = createTransport({ + key, + name, + async request({ method, params }) { + let includes; + const fetch2 = async (i = 0) => { + const transport2 = transports[i]({ + ...rest, + chain, + retryCount: 0, + timeout + }); + try { + const response = await transport2.request({ + method, + params + }); + onResponse({ + method, + params, + response, + transport: transport2, + status: "success" + }); + return response; + } catch (err) { + onResponse({ + error: err, + method, + params, + transport: transport2, + status: "error" + }); + if (shouldThrow_(err)) + throw err; + if (i === transports.length - 1) + throw err; + includes ??= transports.slice(i + 1).some((transport3) => { + const { include, exclude } = transport3({ chain }).config.methods || {}; + if (include) + return include.includes(method); + if (exclude) + return !exclude.includes(method); + return true; + }); + if (!includes) + throw err; + return fetch2(i + 1); + } + }; + return fetch2(); + }, + retryCount, + retryDelay, + type: "fallback" + }, { + onResponse: (fn2) => onResponse = fn2, + transports: transports.map((fn2) => fn2({ chain, retryCount: 0 })) + }); + if (rank) { + const rankOptions = typeof rank === "object" ? rank : {}; + rankTransports({ + chain, + interval: rankOptions.interval ?? pollingInterval, + onTransports: (transports_2) => transports = transports_2, + ping: rankOptions.ping, + sampleCount: rankOptions.sampleCount, + timeout: rankOptions.timeout, + transports, + weights: rankOptions.weights + }); + } + return transport; + }; +} +function shouldThrow(error) { + if ("code" in error && typeof error.code === "number") { + if (error.code === TransactionRejectedRpcError.code || error.code === UserRejectedRequestError.code || ExecutionRevertedError.nodeMessage.test(error.message) || error.code === 5e3) + return true; + } + return false; +} +function rankTransports({ chain, interval = 4e3, onTransports, ping, sampleCount = 10, timeout = 1e3, transports, weights = {} }) { + const { stability: stabilityWeight = 0.7, latency: latencyWeight = 0.3 } = weights; + const samples = []; + const rankTransports_ = async () => { + const sample = await Promise.all(transports.map(async (transport) => { + const transport_ = transport({ chain, retryCount: 0, timeout }); + const start = Date.now(); + let end; + let success; + try { + await (ping ? ping({ transport: transport_ }) : transport_.request({ method: "net_listening" })); + success = 1; + } catch { + success = 0; + } finally { + end = Date.now(); + } + const latency = end - start; + return { latency, success }; + })); + samples.push(sample); + if (samples.length > sampleCount) + samples.shift(); + const maxLatency = Math.max(...samples.map((sample2) => Math.max(...sample2.map(({ latency }) => latency)))); + const scores = transports.map((_, i) => { + const latencies = samples.map((sample2) => sample2[i].latency); + const meanLatency = latencies.reduce((acc, latency) => acc + latency, 0) / latencies.length; + const latencyScore = 1 - meanLatency / maxLatency; + const successes = samples.map((sample2) => sample2[i].success); + const stabilityScore = successes.reduce((acc, success) => acc + success, 0) / successes.length; + if (stabilityScore === 0) + return [0, i]; + return [ + latencyWeight * latencyScore + stabilityWeight * stabilityScore, + i + ]; + }).sort((a, b2) => b2[0] - a[0]); + onTransports(scores.map(([, i]) => transports[i])); + await wait(interval); + rankTransports_(); + }; + rankTransports_(); +} + +// node_modules/viem/_esm/clients/transports/http.js +init_request(); + +// node_modules/viem/_esm/errors/transport.js +init_base(); +var UrlRequiredError = class extends BaseError2 { + constructor() { + super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.", { + docsPath: "/docs/clients/intro", + name: "UrlRequiredError" + }); + } +}; + +// node_modules/viem/_esm/clients/transports/http.js +init_createBatchScheduler(); + +// node_modules/viem/_esm/utils/rpc/http.js +init_request(); + +// node_modules/viem/_esm/utils/promise/withTimeout.js +function withTimeout(fn2, { errorInstance = new Error("timed out"), timeout, signal }) { + return new Promise((resolve, reject) => { + ; + (async () => { + let timeoutId; + try { + const controller = new AbortController(); + if (timeout > 0) { + timeoutId = setTimeout(() => { + if (signal) { + controller.abort(); + } else { + reject(errorInstance); + } + }, timeout); + } + resolve(await fn2({ signal: controller?.signal || null })); + } catch (err) { + if (err?.name === "AbortError") + reject(errorInstance); + reject(err); + } finally { + clearTimeout(timeoutId); + } + })(); + }); +} + +// node_modules/viem/_esm/utils/rpc/http.js +init_stringify(); + +// node_modules/viem/_esm/utils/rpc/id.js +function createIdStore() { + return { + current: 0, + take() { + return this.current++; + }, + reset() { + this.current = 0; + } + }; +} +var idCache = /* @__PURE__ */ createIdStore(); + +// node_modules/viem/_esm/utils/rpc/http.js +function getHttpRpcClient(url2, options = {}) { + return { + async request(params) { + const { body, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 1e4 } = params; + const fetchOptions = { + ...options.fetchOptions ?? {}, + ...params.fetchOptions ?? {} + }; + const { headers, method, signal: signal_ } = fetchOptions; + try { + const response = await withTimeout(async ({ signal }) => { + const init = { + ...fetchOptions, + body: Array.isArray(body) ? stringify(body.map((body2) => ({ + jsonrpc: "2.0", + id: body2.id ?? idCache.take(), + ...body2 + }))) : stringify({ + jsonrpc: "2.0", + id: body.id ?? idCache.take(), + ...body + }), + headers: { + "Content-Type": "application/json", + ...headers + }, + method: method || "POST", + signal: signal_ || (timeout > 0 ? signal : null) + }; + const request = new Request(url2, init); + const args = await onRequest?.(request, init) ?? { ...init, url: url2 }; + const response2 = await fetch(args.url ?? url2, args); + return response2; + }, { + errorInstance: new TimeoutError({ body, url: url2 }), + timeout, + signal: true + }); + if (onResponse) + await onResponse(response); + let data; + if (response.headers.get("Content-Type")?.startsWith("application/json")) + data = await response.json(); + else { + data = await response.text(); + try { + data = JSON.parse(data || "{}"); + } catch (err) { + if (response.ok) + throw err; + data = { error: data }; + } + } + if (!response.ok) { + throw new HttpRequestError({ + body, + details: stringify(data.error) || response.statusText, + headers: response.headers, + status: response.status, + url: url2 + }); + } + return data; + } catch (err) { + if (err instanceof HttpRequestError) + throw err; + if (err instanceof TimeoutError) + throw err; + throw new HttpRequestError({ + body, + cause: err, + url: url2 + }); + } + } + }; +} + +// node_modules/viem/_esm/clients/transports/http.js +function http2(url2, config3 = {}) { + const { batch, fetchOptions, key = "http", methods, name = "HTTP JSON-RPC", onFetchRequest, onFetchResponse, retryDelay, raw: raw2 } = config3; + return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => { + const { batchSize = 1e3, wait: wait2 = 0 } = typeof batch === "object" ? batch : {}; + const retryCount = config3.retryCount ?? retryCount_; + const timeout = timeout_ ?? config3.timeout ?? 1e4; + const url_ = url2 || chain?.rpcUrls.default.http[0]; + if (!url_) + throw new UrlRequiredError(); + const rpcClient = getHttpRpcClient(url_, { + fetchOptions, + onRequest: onFetchRequest, + onResponse: onFetchResponse, + timeout + }); + return createTransport({ + key, + methods, + name, + async request({ method, params }) { + const body = { method, params }; + const { schedule } = createBatchScheduler({ + id: url_, + wait: wait2, + shouldSplitBatch(requests) { + return requests.length > batchSize; + }, + fn: (body2) => rpcClient.request({ + body: body2 + }), + sort: (a, b2) => a.id - b2.id + }); + const fn2 = async (body2) => batch ? schedule(body2) : [ + await rpcClient.request({ + body: body2 + }) + ]; + const [{ error, result }] = await fn2(body); + if (raw2) + return { error, result }; + if (error) + throw new RpcRequestError({ + body, + error, + url: url_ + }); + return result; + }, + retryCount, + retryDelay, + timeout, + type: "http" + }, { + fetchOptions, + url: url_ + }); + }; +} + +// node_modules/viem/_esm/actions/ens/getEnsAddress.js +init_abis(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_getChainContractAddress(); +init_trim(); +init_toHex(); + +// node_modules/viem/_esm/utils/ens/errors.js +init_solidity(); +init_base(); +init_contract(); +function isNullUniversalResolverError(err, callType) { + if (!(err instanceof BaseError2)) + return false; + const cause = err.walk((e) => e instanceof ContractFunctionRevertedError); + if (!(cause instanceof ContractFunctionRevertedError)) + return false; + if (cause.data?.errorName === "ResolverNotFound") + return true; + if (cause.data?.errorName === "ResolverWildcardNotSupported") + return true; + if (cause.data?.errorName === "ResolverNotContract") + return true; + if (cause.data?.errorName === "ResolverError") + return true; + if (cause.data?.errorName === "HttpError") + return true; + if (cause.reason?.includes("Wildcard on non-extended resolvers is not supported")) + return true; + if (callType === "reverse" && cause.reason === panicReasons[50]) + return true; + return false; +} + +// node_modules/viem/_esm/utils/ens/namehash.js +init_concat(); +init_toBytes(); +init_toHex(); +init_keccak256(); + +// node_modules/viem/_esm/utils/ens/encodedLabelToLabelhash.js +init_isHex(); +function encodedLabelToLabelhash(label) { + if (label.length !== 66) + return null; + if (label.indexOf("[") !== 0) + return null; + if (label.indexOf("]") !== 65) + return null; + const hash2 = `0x${label.slice(1, 65)}`; + if (!isHex(hash2)) + return null; + return hash2; +} + +// node_modules/viem/_esm/utils/ens/namehash.js +function namehash(name) { + let result = new Uint8Array(32).fill(0); + if (!name) + return bytesToHex(result); + const labels = name.split("."); + for (let i = labels.length - 1; i >= 0; i -= 1) { + const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]); + const hashed = hashFromEncodedLabel ? toBytes(hashFromEncodedLabel) : keccak256(stringToBytes(labels[i]), "bytes"); + result = keccak256(concat([result, hashed]), "bytes"); + } + return bytesToHex(result); +} + +// node_modules/viem/_esm/utils/ens/packetToBytes.js +init_toBytes(); + +// node_modules/viem/_esm/utils/ens/encodeLabelhash.js +function encodeLabelhash(hash2) { + return `[${hash2.slice(2)}]`; +} + +// node_modules/viem/_esm/utils/ens/labelhash.js +init_toBytes(); +init_toHex(); +init_keccak256(); +function labelhash(label) { + const result = new Uint8Array(32).fill(0); + if (!label) + return bytesToHex(result); + return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label)); +} + +// node_modules/viem/_esm/utils/ens/packetToBytes.js +function packetToBytes(packet) { + const value = packet.replace(/^\.|\.$/gm, ""); + if (value.length === 0) + return new Uint8Array(1); + const bytes = new Uint8Array(stringToBytes(value).byteLength + 2); + let offset = 0; + const list = value.split("."); + for (let i = 0; i < list.length; i++) { + let encoded = stringToBytes(list[i]); + if (encoded.byteLength > 255) + encoded = stringToBytes(encodeLabelhash(labelhash(list[i]))); + bytes[offset] = encoded.length; + bytes.set(encoded, offset + 1); + offset += encoded.length + 1; + } + if (bytes.byteLength !== offset + 1) + return bytes.slice(0, offset + 1); + return bytes; +} + +// node_modules/viem/_esm/actions/ens/getEnsAddress.js +async function getEnsAddress(client, { blockNumber, blockTag, coinType, name, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "ensUniversalResolver" + }); + } + try { + const functionData = encodeFunctionData({ + abi: addressResolverAbi, + functionName: "addr", + ...coinType != null ? { args: [namehash(name), BigInt(coinType)] } : { args: [namehash(name)] } + }); + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverResolveAbi, + functionName: "resolve", + args: [toHex(packetToBytes(name)), functionData], + blockNumber, + blockTag + }; + const readContractAction = getAction(client, readContract, "readContract"); + const res = gatewayUrls ? await readContractAction({ + ...readContractParameters, + args: [...readContractParameters.args, gatewayUrls] + }) : await readContractAction(readContractParameters); + if (res[0] === "0x") + return null; + const address = decodeFunctionResult({ + abi: addressResolverAbi, + args: coinType != null ? [namehash(name), BigInt(coinType)] : void 0, + functionName: "addr", + data: res[0] + }); + if (address === "0x") + return null; + if (trim2(address) === "0x00") + return null; + return address; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err, "resolve")) + return null; + throw err; + } +} + +// node_modules/viem/_esm/errors/ens.js +init_base(); +var EnsAvatarInvalidMetadataError = class extends BaseError2 { + constructor({ data }) { + super("Unable to extract image from metadata. The metadata may be malformed or invalid.", { + metaMessages: [ + "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.", + "", + `Provided data: ${JSON.stringify(data)}` + ], + name: "EnsAvatarInvalidMetadataError" + }); + } +}; +var EnsAvatarInvalidNftUriError = class extends BaseError2 { + constructor({ reason }) { + super(`ENS NFT avatar URI is invalid. ${reason}`, { + name: "EnsAvatarInvalidNftUriError" + }); + } +}; +var EnsAvatarUriResolutionError = class extends BaseError2 { + constructor({ uri }) { + super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`, { name: "EnsAvatarUriResolutionError" }); + } +}; +var EnsAvatarUnsupportedNamespaceError = class extends BaseError2 { + constructor({ namespace }) { + super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`, { name: "EnsAvatarUnsupportedNamespaceError" }); + } +}; + +// node_modules/viem/_esm/utils/ens/avatar/utils.js +var networkRegex = /(?https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/; +var ipfsHashRegex = /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/; +var base64Regex = /^data:([a-zA-Z\-/+]*);base64,([^"].*)/; +var dataURIRegex = /^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/; +async function isImageUri(uri) { + try { + const res = await fetch(uri, { method: "HEAD" }); + if (res.status === 200) { + const contentType = res.headers.get("content-type"); + return contentType?.startsWith("image/"); + } + return false; + } catch (error) { + if (typeof error === "object" && typeof error.response !== "undefined") { + return false; + } + if (!globalThis.hasOwnProperty("Image")) + return false; + return new Promise((resolve) => { + const img = new Image(); + img.onload = () => { + resolve(true); + }; + img.onerror = () => { + resolve(false); + }; + img.src = uri; + }); + } +} +function getGateway(custom, defaultGateway) { + if (!custom) + return defaultGateway; + if (custom.endsWith("/")) + return custom.slice(0, -1); + return custom; +} +function resolveAvatarUri({ uri, gatewayUrls }) { + const isEncoded = base64Regex.test(uri); + if (isEncoded) + return { uri, isOnChain: true, isEncoded }; + const ipfsGateway = getGateway(gatewayUrls?.ipfs, "https://ipfs.io"); + const arweaveGateway = getGateway(gatewayUrls?.arweave, "https://arweave.net"); + const networkRegexMatch = uri.match(networkRegex); + const { protocol, subpath, target, subtarget = "" } = networkRegexMatch?.groups || {}; + const isIPNS = protocol === "ipns:/" || subpath === "ipns/"; + const isIPFS = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri); + if (uri.startsWith("http") && !isIPNS && !isIPFS) { + let replacedUri = uri; + if (gatewayUrls?.arweave) + replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls?.arweave); + return { uri: replacedUri, isOnChain: false, isEncoded: false }; + } + if ((isIPNS || isIPFS) && target) { + return { + uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`, + isOnChain: false, + isEncoded: false + }; + } + if (protocol === "ar:/" && target) { + return { + uri: `${arweaveGateway}/${target}${subtarget || ""}`, + isOnChain: false, + isEncoded: false + }; + } + let parsedUri = uri.replace(dataURIRegex, ""); + if (parsedUri.startsWith(" res2.json()); + const image = await parseAvatarUri({ + gatewayUrls, + uri: getJsonImage(res) + }); + return image; + } catch { + throw new EnsAvatarUriResolutionError({ uri }); + } +} +async function parseAvatarUri({ gatewayUrls, uri }) { + const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls }); + if (isOnChain) + return resolvedURI; + const isImage = await isImageUri(resolvedURI); + if (isImage) + return resolvedURI; + throw new EnsAvatarUriResolutionError({ uri }); +} +function parseNftUri(uri_) { + let uri = uri_; + if (uri.startsWith("did:nft:")) { + uri = uri.replace("did:nft:", "").replace(/_/g, "/"); + } + const [reference, asset_namespace, tokenID] = uri.split("/"); + const [eip_namespace, chainID] = reference.split(":"); + const [erc_namespace, contractAddress] = asset_namespace.split(":"); + if (!eip_namespace || eip_namespace.toLowerCase() !== "eip155") + throw new EnsAvatarInvalidNftUriError({ reason: "Only EIP-155 supported" }); + if (!chainID) + throw new EnsAvatarInvalidNftUriError({ reason: "Chain ID not found" }); + if (!contractAddress) + throw new EnsAvatarInvalidNftUriError({ + reason: "Contract address not found" + }); + if (!tokenID) + throw new EnsAvatarInvalidNftUriError({ reason: "Token ID not found" }); + if (!erc_namespace) + throw new EnsAvatarInvalidNftUriError({ reason: "ERC namespace not found" }); + return { + chainID: Number.parseInt(chainID), + namespace: erc_namespace.toLowerCase(), + contractAddress, + tokenID + }; +} +async function getNftTokenUri(client, { nft }) { + if (nft.namespace === "erc721") { + return readContract(client, { + address: nft.contractAddress, + abi: [ + { + name: "tokenURI", + type: "function", + stateMutability: "view", + inputs: [{ name: "tokenId", type: "uint256" }], + outputs: [{ name: "", type: "string" }] + } + ], + functionName: "tokenURI", + args: [BigInt(nft.tokenID)] + }); + } + if (nft.namespace === "erc1155") { + return readContract(client, { + address: nft.contractAddress, + abi: [ + { + name: "uri", + type: "function", + stateMutability: "view", + inputs: [{ name: "_id", type: "uint256" }], + outputs: [{ name: "", type: "string" }] + } + ], + functionName: "uri", + args: [BigInt(nft.tokenID)] + }); + } + throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace }); +} + +// node_modules/viem/_esm/utils/ens/avatar/parseAvatarRecord.js +async function parseAvatarRecord(client, { gatewayUrls, record }) { + if (/eip155:/i.test(record)) + return parseNftAvatarUri(client, { gatewayUrls, record }); + return parseAvatarUri({ uri: record, gatewayUrls }); +} +async function parseNftAvatarUri(client, { gatewayUrls, record }) { + const nft = parseNftUri(record); + const nftUri = await getNftTokenUri(client, { nft }); + const { uri: resolvedNftUri, isOnChain, isEncoded } = resolveAvatarUri({ uri: nftUri, gatewayUrls }); + if (isOnChain && (resolvedNftUri.includes("data:application/json;base64,") || resolvedNftUri.startsWith("{"))) { + const encodedJson = isEncoded ? ( + // if it is encoded, decode it + atob(resolvedNftUri.replace("data:application/json;base64,", "")) + ) : ( + // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is) + resolvedNftUri + ); + const decoded = JSON.parse(encodedJson); + return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls }); + } + let uriTokenId = nft.tokenID; + if (nft.namespace === "erc1155") + uriTokenId = uriTokenId.replace("0x", "").padStart(64, "0"); + return getMetadataAvatarUri({ + gatewayUrls, + uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId) + }); +} + +// node_modules/viem/_esm/actions/ens/getEnsText.js +init_abis(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_getChainContractAddress(); +init_toHex(); +async function getEnsText(client, { blockNumber, blockTag, name, key, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "ensUniversalResolver" + }); + } + try { + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverResolveAbi, + functionName: "resolve", + args: [ + toHex(packetToBytes(name)), + encodeFunctionData({ + abi: textResolverAbi, + functionName: "text", + args: [namehash(name), key] + }) + ], + blockNumber, + blockTag + }; + const readContractAction = getAction(client, readContract, "readContract"); + const res = gatewayUrls ? await readContractAction({ + ...readContractParameters, + args: [...readContractParameters.args, gatewayUrls] + }) : await readContractAction(readContractParameters); + if (res[0] === "0x") + return null; + const record = decodeFunctionResult({ + abi: textResolverAbi, + functionName: "text", + data: res[0] + }); + return record === "" ? null : record; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err, "resolve")) + return null; + throw err; + } +} + +// node_modules/viem/_esm/actions/ens/getEnsAvatar.js +async function getEnsAvatar(client, { blockNumber, blockTag, assetGatewayUrls, name, gatewayUrls, strict, universalResolverAddress }) { + const record = await getAction(client, getEnsText, "getEnsText")({ + blockNumber, + blockTag, + key: "avatar", + name, + universalResolverAddress, + gatewayUrls, + strict + }); + if (!record) + return null; + try { + return await parseAvatarRecord(client, { + record, + gatewayUrls: assetGatewayUrls + }); + } catch { + return null; + } +} + +// node_modules/viem/_esm/actions/ens/getEnsName.js +init_abis(); +init_getChainContractAddress(); +init_toHex(); +async function getEnsName(client, { address, blockNumber, blockTag, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "ensUniversalResolver" + }); + } + const reverseNode = `${address.toLowerCase().substring(2)}.addr.reverse`; + try { + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverReverseAbi, + functionName: "reverse", + args: [toHex(packetToBytes(reverseNode))], + blockNumber, + blockTag + }; + const readContractAction = getAction(client, readContract, "readContract"); + const [name, resolvedAddress] = gatewayUrls ? await readContractAction({ + ...readContractParameters, + args: [...readContractParameters.args, gatewayUrls] + }) : await readContractAction(readContractParameters); + if (address.toLowerCase() !== resolvedAddress.toLowerCase()) + return null; + return name; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err, "reverse")) + return null; + throw err; + } +} + +// node_modules/viem/_esm/actions/ens/getEnsResolver.js +init_getChainContractAddress(); +init_toHex(); +async function getEnsResolver(client, { blockNumber, blockTag, name, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "ensUniversalResolver" + }); + } + const [resolverAddress] = await getAction(client, readContract, "readContract")({ + address: universalResolverAddress, + abi: [ + { + inputs: [{ type: "bytes" }], + name: "findResolver", + outputs: [{ type: "address" }, { type: "bytes32" }], + stateMutability: "view", + type: "function" + } + ], + functionName: "findResolver", + args: [toHex(packetToBytes(name))], + blockNumber, + blockTag + }); + return resolverAddress; +} + +// node_modules/viem/_esm/clients/decorators/public.js +init_call(); + +// node_modules/viem/_esm/actions/public/createAccessList.js +init_parseAccount(); +init_toHex(); +init_getCallError(); +init_extract(); +init_transactionRequest(); +init_assertRequest(); +async function createAccessList(client, args) { + const { account: account_ = client.account, blockNumber, blockTag = "latest", blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, to: to2, value, ...rest } = args; + const account = account_ ? parseAccount(account_) : void 0; + try { + assertRequest(args); + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format = chainFormat || formatTransactionRequest; + const request = format({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + from: account?.address, + blobs, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + to: to2, + value + }); + const response = await client.request({ + method: "eth_createAccessList", + params: [request, block] + }); + return { + accessList: response.accessList, + gasUsed: BigInt(response.gasUsed) + }; + } catch (err) { + throw getCallError(err, { + ...args, + account, + chain: client.chain + }); + } +} + +// node_modules/viem/_esm/actions/public/createBlockFilter.js +async function createBlockFilter(client) { + const getRequest = createFilterRequestScope(client, { + method: "eth_newBlockFilter" + }); + const id2 = await client.request({ + method: "eth_newBlockFilter" + }); + return { id: id2, request: getRequest(id2), type: "block" }; +} + +// node_modules/viem/_esm/actions/public/createEventFilter.js +init_toHex(); +async function createEventFilter(client, { address, args, event, events: events_, fromBlock, strict, toBlock } = {}) { + const events = events_ ?? (event ? [event] : void 0); + const getRequest = createFilterRequestScope(client, { + method: "eth_newFilter" + }); + let topics = []; + if (events) { + const encoded = events.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + const id2 = await client.request({ + method: "eth_newFilter", + params: [ + { + address, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, + ...topics.length ? { topics } : {} + } + ] + }); + return { + abi: events, + args, + eventName: event ? event.name : void 0, + fromBlock, + id: id2, + request: getRequest(id2), + strict: Boolean(strict), + toBlock, + type: "event" + }; +} + +// node_modules/viem/_esm/actions/public/createPendingTransactionFilter.js +async function createPendingTransactionFilter(client) { + const getRequest = createFilterRequestScope(client, { + method: "eth_newPendingTransactionFilter" + }); + const id2 = await client.request({ + method: "eth_newPendingTransactionFilter" + }); + return { id: id2, request: getRequest(id2), type: "transaction" }; +} + +// node_modules/viem/_esm/actions/public/getBlobBaseFee.js +async function getBlobBaseFee(client) { + const baseFee = await client.request({ + method: "eth_blobBaseFee" + }); + return BigInt(baseFee); +} + +// node_modules/viem/_esm/actions/public/getBlockTransactionCount.js +init_fromHex(); +init_toHex(); +async function getBlockTransactionCount(client, { blockHash, blockNumber, blockTag = "latest" } = {}) { + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + let count; + if (blockHash) { + count = await client.request({ + method: "eth_getBlockTransactionCountByHash", + params: [blockHash] + }, { dedupe: true }); + } else { + count = await client.request({ + method: "eth_getBlockTransactionCountByNumber", + params: [blockNumberHex || blockTag] + }, { dedupe: Boolean(blockNumberHex) }); + } + return hexToNumber(count); +} + +// node_modules/viem/_esm/actions/public/getCode.js +init_toHex(); +async function getCode(client, { address, blockNumber, blockTag = "latest" }) { + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + const hex = await client.request({ + method: "eth_getCode", + params: [address, blockNumberHex || blockTag] + }, { dedupe: Boolean(blockNumberHex) }); + if (hex === "0x") + return void 0; + return hex; +} + +// node_modules/viem/_esm/actions/public/getFeeHistory.js +init_toHex(); + +// node_modules/viem/_esm/utils/formatters/feeHistory.js +function formatFeeHistory(feeHistory) { + return { + baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)), + gasUsedRatio: feeHistory.gasUsedRatio, + oldestBlock: BigInt(feeHistory.oldestBlock), + reward: feeHistory.reward?.map((reward) => reward.map((value) => BigInt(value))) + }; +} + +// node_modules/viem/_esm/actions/public/getFeeHistory.js +async function getFeeHistory(client, { blockCount, blockNumber, blockTag = "latest", rewardPercentiles }) { + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const feeHistory = await client.request({ + method: "eth_feeHistory", + params: [ + numberToHex(blockCount), + blockNumberHex || blockTag, + rewardPercentiles + ] + }, { dedupe: Boolean(blockNumberHex) }); + return formatFeeHistory(feeHistory); +} + +// node_modules/viem/_esm/actions/public/getFilterLogs.js +async function getFilterLogs(_client, { filter: filter2 }) { + const strict = filter2.strict ?? false; + const logs = await filter2.request({ + method: "eth_getFilterLogs", + params: [filter2.id] + }); + const formattedLogs = logs.map((log) => formatLog(log)); + if (!filter2.abi) + return formattedLogs; + return parseEventLogs({ + abi: filter2.abi, + logs: formattedLogs, + strict + }); +} + +// node_modules/viem/_esm/actions/public/getProof.js +init_toHex(); + +// node_modules/viem/_esm/utils/chain/defineChain.js +function defineChain(chain) { + return { + formatters: void 0, + fees: void 0, + serializers: void 0, + ...chain + }; +} + +// node_modules/viem/_esm/utils/typedData.js +init_abi(); +init_address(); + +// node_modules/viem/_esm/errors/typedData.js +init_stringify(); +init_base(); +var InvalidDomainError = class extends BaseError2 { + constructor({ domain }) { + super(`Invalid domain "${stringify(domain)}".`, { + metaMessages: ["Must be a valid EIP-712 domain."] + }); + } +}; +var InvalidPrimaryTypeError = class extends BaseError2 { + constructor({ primaryType, types }) { + super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, { + docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror", + metaMessages: ["Check that the primary type is a key in `types`."] + }); + } +}; +var InvalidStructTypeError = class extends BaseError2 { + constructor({ type }) { + super(`Struct type "${type}" is invalid.`, { + metaMessages: ["Struct type must not be a Solidity type."], + name: "InvalidStructTypeError" + }); + } +}; + +// node_modules/viem/_esm/utils/typedData.js +init_isAddress(); +init_size(); +init_toHex(); +init_regex2(); + +// node_modules/viem/_esm/utils/signature/hashTypedData.js +init_encodeAbiParameters(); +init_concat(); +init_toHex(); +init_keccak256(); +function hashTypedData(parameters) { + const { domain = {}, message, primaryType } = parameters; + const types = { + EIP712Domain: getTypesForEIP712Domain({ domain }), + ...parameters.types + }; + validateTypedData({ + domain, + message, + primaryType, + types + }); + const parts = ["0x1901"]; + if (domain) + parts.push(hashDomain({ + domain, + types + })); + if (primaryType !== "EIP712Domain") + parts.push(hashStruct({ + data: message, + primaryType, + types + })); + return keccak256(concat(parts)); +} +function hashDomain({ domain, types }) { + return hashStruct({ + data: domain, + primaryType: "EIP712Domain", + types + }); +} +function hashStruct({ data, primaryType, types }) { + const encoded = encodeData({ + data, + primaryType, + types + }); + return keccak256(encoded); +} +function encodeData({ data, primaryType, types }) { + const encodedTypes = [{ type: "bytes32" }]; + const encodedValues = [hashType({ primaryType, types })]; + for (const field of types[primaryType]) { + const [type, value] = encodeField({ + types, + name: field.name, + type: field.type, + value: data[field.name] + }); + encodedTypes.push(type); + encodedValues.push(value); + } + return encodeAbiParameters(encodedTypes, encodedValues); +} +function hashType({ primaryType, types }) { + const encodedHashType = toHex(encodeType({ primaryType, types })); + return keccak256(encodedHashType); +} +function encodeType({ primaryType, types }) { + let result = ""; + const unsortedDeps = findTypeDependencies({ primaryType, types }); + unsortedDeps.delete(primaryType); + const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; + for (const type of deps) { + result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`; + } + return result; +} +function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) { + const match = primaryType_.match(/^\w*/u); + const primaryType = match?.[0]; + if (results.has(primaryType) || types[primaryType] === void 0) { + return results; + } + results.add(primaryType); + for (const field of types[primaryType]) { + findTypeDependencies({ primaryType: field.type, types }, results); + } + return results; +} +function encodeField({ types, name, type, value }) { + if (types[type] !== void 0) { + return [ + { type: "bytes32" }, + keccak256(encodeData({ data: value, primaryType: type, types })) + ]; + } + if (type === "bytes") { + const prepend = value.length % 2 ? "0" : ""; + value = `0x${prepend + value.slice(2)}`; + return [{ type: "bytes32" }, keccak256(value)]; + } + if (type === "string") + return [{ type: "bytes32" }, keccak256(toHex(value))]; + if (type.lastIndexOf("]") === type.length - 1) { + const parsedType = type.slice(0, type.lastIndexOf("[")); + const typeValuePairs = value.map((item) => encodeField({ + name, + type: parsedType, + types, + value: item + })); + return [ + { type: "bytes32" }, + keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v))) + ]; + } + return [{ type }, value]; +} + +// node_modules/viem/_esm/utils/typedData.js +init_stringify(); +function serializeTypedData(parameters) { + const { domain: domain_, message: message_, primaryType, types } = parameters; + const normalizeData = (struct, data_) => { + const data = { ...data_ }; + for (const param of struct) { + const { name, type } = param; + if (type === "address") + data[name] = data[name].toLowerCase(); + } + return data; + }; + const domain = (() => { + if (!types.EIP712Domain) + return {}; + if (!domain_) + return {}; + return normalizeData(types.EIP712Domain, domain_); + })(); + const message = (() => { + if (primaryType === "EIP712Domain") + return void 0; + return normalizeData(types[primaryType], message_); + })(); + return stringify({ domain, message, primaryType, types }); +} +function validateTypedData(parameters) { + const { domain, message, primaryType, types } = parameters; + const validateData = (struct, data) => { + for (const param of struct) { + const { name, type } = param; + const value = data[name]; + const integerMatch = type.match(integerRegex2); + if (integerMatch && (typeof value === "number" || typeof value === "bigint")) { + const [_type, base, size_] = integerMatch; + numberToHex(value, { + signed: base === "int", + size: Number.parseInt(size_) / 8 + }); + } + if (type === "address" && typeof value === "string" && !isAddress(value)) + throw new InvalidAddressError({ address: value }); + const bytesMatch = type.match(bytesRegex2); + if (bytesMatch) { + const [_type, size_] = bytesMatch; + if (size_ && size(value) !== Number.parseInt(size_)) + throw new BytesSizeMismatchError({ + expectedSize: Number.parseInt(size_), + givenSize: size(value) + }); + } + const struct2 = types[type]; + if (struct2) { + validateReference(type); + validateData(struct2, value); + } + } + }; + if (types.EIP712Domain && domain) { + if (typeof domain !== "object") + throw new InvalidDomainError({ domain }); + validateData(types.EIP712Domain, domain); + } + if (primaryType !== "EIP712Domain") { + if (types[primaryType]) + validateData(types[primaryType], message); + else + throw new InvalidPrimaryTypeError({ primaryType, types }); + } +} +function getTypesForEIP712Domain({ domain }) { + return [ + typeof domain?.name === "string" && { name: "name", type: "string" }, + domain?.version && { name: "version", type: "string" }, + (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && { + name: "chainId", + type: "uint256" + }, + domain?.verifyingContract && { + name: "verifyingContract", + type: "address" + }, + domain?.salt && { name: "salt", type: "bytes32" } + ].filter(Boolean); +} +function validateReference(type) { + if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int")) + throw new InvalidStructTypeError({ type }); +} + +// node_modules/viem/_esm/utils/index.js +init_encodeFunctionData(); + +// node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js +init_toHex(); + +// node_modules/viem/_esm/utils/transaction/serializeTransaction.js +init_transaction(); +init_concat(); +init_trim(); +init_toHex(); + +// node_modules/viem/_esm/utils/transaction/assertTransaction.js +init_number(); +init_address(); +init_base(); +init_chain(); +init_node(); +init_isAddress(); +init_size(); +init_slice(); +init_fromHex(); +function assertTransactionEIP7702(transaction) { + const { authorizationList } = transaction; + if (authorizationList) { + for (const authorization of authorizationList) { + const { chainId } = authorization; + const address = authorization.address; + if (!isAddress(address)) + throw new InvalidAddressError({ address }); + if (chainId < 0) + throw new InvalidChainIdError({ chainId }); + } + } + assertTransactionEIP1559(transaction); +} +function assertTransactionEIP4844(transaction) { + const { blobVersionedHashes } = transaction; + if (blobVersionedHashes) { + if (blobVersionedHashes.length === 0) + throw new EmptyBlobError(); + for (const hash2 of blobVersionedHashes) { + const size_ = size(hash2); + const version4 = hexToNumber(slice(hash2, 0, 1)); + if (size_ !== 32) + throw new InvalidVersionedHashSizeError({ hash: hash2, size: size_ }); + if (version4 !== versionedHashVersionKzg) + throw new InvalidVersionedHashVersionError({ + hash: hash2, + version: version4 + }); + } + } + assertTransactionEIP1559(transaction); +} +function assertTransactionEIP1559(transaction) { + const { chainId, maxPriorityFeePerGas, maxFeePerGas, to: to2 } = transaction; + if (chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (to2 && !isAddress(to2)) + throw new InvalidAddressError({ address: to2 }); + if (maxFeePerGas && maxFeePerGas > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas }); + if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) + throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); +} +function assertTransactionEIP2930(transaction) { + const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to: to2 } = transaction; + if (chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (to2 && !isAddress(to2)) + throw new InvalidAddressError({ address: to2 }); + if (maxPriorityFeePerGas || maxFeePerGas) + throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute."); + if (gasPrice && gasPrice > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); +} +function assertTransactionLegacy(transaction) { + const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to: to2 } = transaction; + if (to2 && !isAddress(to2)) + throw new InvalidAddressError({ address: to2 }); + if (typeof chainId !== "undefined" && chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (maxPriorityFeePerGas || maxFeePerGas) + throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute."); + if (gasPrice && gasPrice > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); +} + +// node_modules/viem/_esm/utils/transaction/serializeAccessList.js +init_address(); +init_transaction(); +init_isAddress(); +function serializeAccessList(accessList) { + if (!accessList || accessList.length === 0) + return []; + const serializedAccessList = []; + for (let i = 0; i < accessList.length; i++) { + const { address, storageKeys } = accessList[i]; + for (let j2 = 0; j2 < storageKeys.length; j2++) { + if (storageKeys[j2].length - 2 !== 64) { + throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j2] }); + } + } + if (!isAddress(address, { strict: false })) { + throw new InvalidAddressError({ address }); + } + serializedAccessList.push([address, storageKeys]); + } + return serializedAccessList; +} + +// node_modules/viem/_esm/utils/transaction/serializeTransaction.js +function serializeTransaction(transaction, signature) { + const type = getTransactionType(transaction); + if (type === "eip1559") + return serializeTransactionEIP1559(transaction, signature); + if (type === "eip2930") + return serializeTransactionEIP2930(transaction, signature); + if (type === "eip4844") + return serializeTransactionEIP4844(transaction, signature); + if (type === "eip7702") + return serializeTransactionEIP7702(transaction, signature); + return serializeTransactionLegacy(transaction, signature); +} +function serializeTransactionEIP7702(transaction, signature) { + const { authorizationList, chainId, gas, nonce, to: to2, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP7702(transaction); + const serializedAccessList = serializeAccessList(accessList); + const serializedAuthorizationList = serializeAuthorizationList(authorizationList); + return concatHex([ + "0x04", + toRlp([ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? toHex(maxFeePerGas) : "0x", + gas ? toHex(gas) : "0x", + to2 ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + serializedAuthorizationList, + ...toYParitySignatureArray(transaction, signature) + ]) + ]); +} +function serializeTransactionEIP4844(transaction, signature) { + const { chainId, gas, nonce, to: to2, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP4844(transaction); + let blobVersionedHashes = transaction.blobVersionedHashes; + let sidecars = transaction.sidecars; + if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) { + const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x2) => bytesToHex(x2)); + const kzg = transaction.kzg; + const commitments2 = blobsToCommitments({ + blobs: blobs2, + kzg + }); + if (typeof blobVersionedHashes === "undefined") + blobVersionedHashes = commitmentsToVersionedHashes({ + commitments: commitments2 + }); + if (typeof sidecars === "undefined") { + const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg }); + sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 }); + } + } + const serializedAccessList = serializeAccessList(accessList); + const serializedTransaction = [ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? toHex(maxFeePerGas) : "0x", + gas ? toHex(gas) : "0x", + to2 ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : "0x", + blobVersionedHashes ?? [], + ...toYParitySignatureArray(transaction, signature) + ]; + const blobs = []; + const commitments = []; + const proofs = []; + if (sidecars) + for (let i = 0; i < sidecars.length; i++) { + const { blob, commitment, proof } = sidecars[i]; + blobs.push(blob); + commitments.push(commitment); + proofs.push(proof); + } + return concatHex([ + "0x03", + sidecars ? ( + // If sidecars are enabled, envelope turns into a "wrapper": + toRlp([serializedTransaction, blobs, commitments, proofs]) + ) : ( + // If sidecars are disabled, standard envelope is used: + toRlp(serializedTransaction) + ) + ]); +} +function serializeTransactionEIP1559(transaction, signature) { + const { chainId, gas, nonce, to: to2, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP1559(transaction); + const serializedAccessList = serializeAccessList(accessList); + const serializedTransaction = [ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? toHex(maxFeePerGas) : "0x", + gas ? toHex(gas) : "0x", + to2 ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + ...toYParitySignatureArray(transaction, signature) + ]; + return concatHex([ + "0x02", + toRlp(serializedTransaction) + ]); +} +function serializeTransactionEIP2930(transaction, signature) { + const { chainId, gas, data, nonce, to: to2, value, accessList, gasPrice } = transaction; + assertTransactionEIP2930(transaction); + const serializedAccessList = serializeAccessList(accessList); + const serializedTransaction = [ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + gasPrice ? toHex(gasPrice) : "0x", + gas ? toHex(gas) : "0x", + to2 ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + ...toYParitySignatureArray(transaction, signature) + ]; + return concatHex([ + "0x01", + toRlp(serializedTransaction) + ]); +} +function serializeTransactionLegacy(transaction, signature) { + const { chainId = 0, gas, data, nonce, to: to2, value, gasPrice } = transaction; + assertTransactionLegacy(transaction); + let serializedTransaction = [ + nonce ? toHex(nonce) : "0x", + gasPrice ? toHex(gasPrice) : "0x", + gas ? toHex(gas) : "0x", + to2 ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x" + ]; + if (signature) { + const v = (() => { + if (signature.v >= 35n) { + const inferredChainId = (signature.v - 35n) / 2n; + if (inferredChainId > 0) + return signature.v; + return 27n + (signature.v === 35n ? 0n : 1n); + } + if (chainId > 0) + return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n); + const v2 = 27n + (signature.v === 27n ? 0n : 1n); + if (signature.v !== v2) + throw new InvalidLegacyVError({ v: signature.v }); + return v2; + })(); + const r = trim2(signature.r); + const s = trim2(signature.s); + serializedTransaction = [ + ...serializedTransaction, + toHex(v), + r === "0x00" ? "0x" : r, + s === "0x00" ? "0x" : s + ]; + } else if (chainId > 0) { + serializedTransaction = [ + ...serializedTransaction, + toHex(chainId), + "0x", + "0x" + ]; + } + return toRlp(serializedTransaction); +} +function toYParitySignatureArray(transaction, signature_) { + const signature = signature_ ?? transaction; + const { v, yParity } = signature; + if (typeof signature.r === "undefined") + return []; + if (typeof signature.s === "undefined") + return []; + if (typeof v === "undefined" && typeof yParity === "undefined") + return []; + const r = trim2(signature.r); + const s = trim2(signature.s); + const yParity_ = (() => { + if (typeof yParity === "number") + return yParity ? toHex(1) : "0x"; + if (v === 0n) + return "0x"; + if (v === 1n) + return toHex(1); + return v === 27n ? "0x" : toHex(1); + })(); + return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s]; +} + +// node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js +function serializeAuthorizationList(authorizationList) { + if (!authorizationList || authorizationList.length === 0) + return []; + const serializedAuthorizationList = []; + for (const authorization of authorizationList) { + const { chainId, nonce, ...signature } = authorization; + const contractAddress = authorization.address; + serializedAuthorizationList.push([ + chainId ? toHex(chainId) : "0x", + contractAddress, + nonce ? toHex(nonce) : "0x", + ...toYParitySignatureArray({}, signature) + ]); + } + return serializedAuthorizationList; +} + +// node_modules/viem/_esm/utils/formatters/transactionReceipt.js +init_fromHex(); +var receiptStatuses = { + "0x0": "reverted", + "0x1": "success" +}; +function formatTransactionReceipt(transactionReceipt) { + const receipt = { + ...transactionReceipt, + blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null, + contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null, + cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null, + effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null, + gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null, + logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null, + to: transactionReceipt.to ? transactionReceipt.to : null, + transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null, + status: transactionReceipt.status ? receiptStatuses[transactionReceipt.status] : null, + type: transactionReceipt.type ? transactionType[transactionReceipt.type] || transactionReceipt.type : null + }; + if (transactionReceipt.blobGasPrice) + receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice); + if (transactionReceipt.blobGasUsed) + receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed); + return receipt; +} + +// node_modules/viem/_esm/utils/index.js +init_fromHex(); + +// node_modules/viem/_esm/utils/signature/hashMessage.js +init_keccak256(); + +// node_modules/viem/_esm/constants/strings.js +var presignMessagePrefix = "Ethereum Signed Message:\n"; + +// node_modules/viem/_esm/utils/signature/toPrefixedMessage.js +init_concat(); +init_size(); +init_toHex(); +function toPrefixedMessage(message_) { + const message = (() => { + if (typeof message_ === "string") + return stringToHex(message_); + if (typeof message_.raw === "string") + return message_.raw; + return bytesToHex(message_.raw); + })(); + const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`); + return concat([prefix, message]); +} + +// node_modules/viem/_esm/utils/signature/hashMessage.js +function hashMessage(message, to_) { + return keccak256(toPrefixedMessage(message), to_); +} + +// node_modules/viem/_esm/constants/bytes.js +var erc6492MagicBytes = "0x6492649264926492649264926492649264926492649264926492649264926492"; + +// node_modules/viem/_esm/utils/signature/isErc6492Signature.js +init_slice(); +function isErc6492Signature(signature) { + return sliceHex(signature, -32) === erc6492MagicBytes; +} + +// node_modules/viem/_esm/utils/signature/serializeErc6492Signature.js +init_encodeAbiParameters(); +init_concat(); +init_toBytes(); +function serializeErc6492Signature(parameters) { + const { address, data, signature, to: to2 = "hex" } = parameters; + const signature_ = concatHex([ + encodeAbiParameters([{ type: "address" }, { type: "bytes" }, { type: "bytes" }], [address, data, signature]), + erc6492MagicBytes + ]); + if (to2 === "hex") + return signature_; + return hexToBytes(signature_); +} + +// node_modules/viem/_esm/utils/formatters/proof.js +function formatStorageProof(storageProof) { + return storageProof.map((proof) => ({ + ...proof, + value: BigInt(proof.value) + })); +} +function formatProof(proof) { + return { + ...proof, + balance: proof.balance ? BigInt(proof.balance) : void 0, + nonce: proof.nonce ? hexToNumber(proof.nonce) : void 0, + storageProof: proof.storageProof ? formatStorageProof(proof.storageProof) : void 0 + }; +} + +// node_modules/viem/_esm/actions/public/getProof.js +async function getProof(client, { address, blockNumber, blockTag: blockTag_, storageKeys }) { + const blockTag = blockTag_ ?? "latest"; + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + const proof = await client.request({ + method: "eth_getProof", + params: [address, storageKeys, blockNumberHex || blockTag] + }); + return formatProof(proof); +} + +// node_modules/viem/_esm/actions/public/getStorageAt.js +init_toHex(); +async function getStorageAt(client, { address, blockNumber, blockTag = "latest", slot }) { + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + const data = await client.request({ + method: "eth_getStorageAt", + params: [address, slot, blockNumberHex || blockTag] + }); + return data; +} + +// node_modules/viem/_esm/actions/public/getTransaction.js +init_transaction(); +init_toHex(); +async function getTransaction(client, { blockHash, blockNumber, blockTag: blockTag_, hash: hash2, index: index2 }) { + const blockTag = blockTag_ || "latest"; + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + let transaction = null; + if (hash2) { + transaction = await client.request({ + method: "eth_getTransactionByHash", + params: [hash2] + }, { dedupe: true }); + } else if (blockHash) { + transaction = await client.request({ + method: "eth_getTransactionByBlockHashAndIndex", + params: [blockHash, numberToHex(index2)] + }, { dedupe: true }); + } else if (blockNumberHex || blockTag) { + transaction = await client.request({ + method: "eth_getTransactionByBlockNumberAndIndex", + params: [blockNumberHex || blockTag, numberToHex(index2)] + }, { dedupe: Boolean(blockNumberHex) }); + } + if (!transaction) + throw new TransactionNotFoundError({ + blockHash, + blockNumber, + blockTag, + hash: hash2, + index: index2 + }); + const format = client.chain?.formatters?.transaction?.format || formatTransaction; + return format(transaction); +} + +// node_modules/viem/_esm/actions/public/getTransactionConfirmations.js +async function getTransactionConfirmations(client, { hash: hash2, transactionReceipt }) { + const [blockNumber, transaction] = await Promise.all([ + getAction(client, getBlockNumber, "getBlockNumber")({}), + hash2 ? getAction(client, getTransaction, "getTransaction")({ hash: hash2 }) : void 0 + ]); + const transactionBlockNumber = transactionReceipt?.blockNumber || transaction?.blockNumber; + if (!transactionBlockNumber) + return 0n; + return blockNumber - transactionBlockNumber + 1n; +} + +// node_modules/viem/_esm/actions/public/getTransactionReceipt.js +init_transaction(); +async function getTransactionReceipt(client, { hash: hash2 }) { + const receipt = await client.request({ + method: "eth_getTransactionReceipt", + params: [hash2] + }, { dedupe: true }); + if (!receipt) + throw new TransactionReceiptNotFoundError({ hash: hash2 }); + const format = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt; + return format(receipt); +} + +// node_modules/viem/_esm/actions/public/multicall.js +init_abis(); +init_abi(); +init_base(); +init_contract(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_getChainContractAddress(); +async function multicall(client, parameters) { + const { allowFailure = true, batchSize: batchSize_, blockNumber, blockTag, multicallAddress: multicallAddress_, stateOverride } = parameters; + const contracts = parameters.contracts; + const batchSize = batchSize_ ?? (typeof client.batch?.multicall === "object" && client.batch.multicall.batchSize || 1024); + let multicallAddress = multicallAddress_; + if (!multicallAddress) { + if (!client.chain) + throw new Error("client chain not configured. multicallAddress is required."); + multicallAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "multicall3" + }); + } + const chunkedCalls = [[]]; + let currentChunk = 0; + let currentChunkSize = 0; + for (let i = 0; i < contracts.length; i++) { + const { abi: abi4, address, args, functionName } = contracts[i]; + try { + const callData = encodeFunctionData({ abi: abi4, args, functionName }); + currentChunkSize += (callData.length - 2) / 2; + if ( + // Check if batching is enabled. + batchSize > 0 && // Check if the current size of the batch exceeds the size limit. + currentChunkSize > batchSize && // Check if the current chunk is not already empty. + chunkedCalls[currentChunk].length > 0 + ) { + currentChunk++; + currentChunkSize = (callData.length - 2) / 2; + chunkedCalls[currentChunk] = []; + } + chunkedCalls[currentChunk] = [ + ...chunkedCalls[currentChunk], + { + allowFailure: true, + callData, + target: address + } + ]; + } catch (err) { + const error = getContractError(err, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/multicall", + functionName + }); + if (!allowFailure) + throw error; + chunkedCalls[currentChunk] = [ + ...chunkedCalls[currentChunk], + { + allowFailure: true, + callData: "0x", + target: address + } + ]; + } + } + const aggregate3Results = await Promise.allSettled(chunkedCalls.map((calls) => getAction(client, readContract, "readContract")({ + abi: multicall3Abi, + address: multicallAddress, + args: [calls], + blockNumber, + blockTag, + functionName: "aggregate3", + stateOverride + }))); + const results = []; + for (let i = 0; i < aggregate3Results.length; i++) { + const result = aggregate3Results[i]; + if (result.status === "rejected") { + if (!allowFailure) + throw result.reason; + for (let j2 = 0; j2 < chunkedCalls[i].length; j2++) { + results.push({ + status: "failure", + error: result.reason, + result: void 0 + }); + } + continue; + } + const aggregate3Result = result.value; + for (let j2 = 0; j2 < aggregate3Result.length; j2++) { + const { returnData, success } = aggregate3Result[j2]; + const { callData } = chunkedCalls[i][j2]; + const { abi: abi4, address, functionName, args } = contracts[results.length]; + try { + if (callData === "0x") + throw new AbiDecodingZeroDataError(); + if (!success) + throw new RawContractError({ data: returnData }); + const result2 = decodeFunctionResult({ + abi: abi4, + args, + data: returnData, + functionName + }); + results.push(allowFailure ? { result: result2, status: "success" } : result2); + } catch (err) { + const error = getContractError(err, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/multicall", + functionName + }); + if (!allowFailure) + throw error; + results.push({ error, result: void 0, status: "failure" }); + } + } + } + if (results.length !== contracts.length) + throw new BaseError2("multicall results mismatch"); + return results; +} + +// node_modules/ox/_esm/core/version.js +var version3 = "0.1.1"; + +// node_modules/ox/_esm/core/internal/errors.js +function getVersion() { + return version3; +} + +// node_modules/ox/_esm/core/Errors.js +var BaseError3 = class _BaseError extends Error { + constructor(shortMessage, options = {}) { + const details = (() => { + if (options.cause instanceof _BaseError) { + if (options.cause.details) + return options.cause.details; + if (options.cause.shortMessage) + return options.cause.shortMessage; + } + if (options.cause?.message) + return options.cause.message; + return options.details; + })(); + const docsPath6 = (() => { + if (options.cause instanceof _BaseError) + return options.cause.docsPath || options.docsPath; + return options.docsPath; + })(); + const docsBaseUrl = "https://oxlib.sh"; + const docs = `${docsBaseUrl}${docsPath6 ?? ""}`; + const message = [ + shortMessage || "An error occurred.", + ...options.metaMessages ? ["", ...options.metaMessages] : [], + ...details || docsPath6 ? [ + "", + details ? `Details: ${details}` : void 0, + docsPath6 ? `See: ${docs}` : void 0 + ] : [] + ].filter((x2) => typeof x2 === "string").join("\n"); + super(message, options.cause ? { cause: options.cause } : void 0); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "docs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "docsPath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "shortMessage", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "BaseError" + }); + Object.defineProperty(this, "version", { + enumerable: true, + configurable: true, + writable: true, + value: `ox@${getVersion()}` + }); + this.cause = options.cause; + this.details = details; + this.docs = docs; + this.docsPath = docsPath6; + this.shortMessage = shortMessage; + } + walk(fn2) { + return walk2(this, fn2); + } +}; +function walk2(err, fn2) { + if (fn2?.(err)) + return err; + if (err && typeof err === "object" && "cause" in err && err.cause) + return walk2(err.cause, fn2); + return fn2 ? null : err; +} + +// node_modules/ox/_esm/core/Json.js +var bigIntSuffix = "#__bigint"; +function stringify2(value, replacer, space) { + return JSON.stringify(value, (key, value2) => { + if (typeof replacer === "function") + return replacer(key, value2); + if (typeof value2 === "bigint") + return value2.toString() + bigIntSuffix; + return value2; + }, space); +} + +// node_modules/ox/_esm/core/internal/bytes.js +function assertSize2(bytes, size_) { + if (size3(bytes) > size_) + throw new SizeOverflowError2({ + givenSize: size3(bytes), + maxSize: size_ + }); +} +var charCodeMap2 = { + zero: 48, + nine: 57, + A: 65, + F: 70, + a: 97, + f: 102 +}; +function charCodeToBase162(char) { + if (char >= charCodeMap2.zero && char <= charCodeMap2.nine) + return char - charCodeMap2.zero; + if (char >= charCodeMap2.A && char <= charCodeMap2.F) + return char - (charCodeMap2.A - 10); + if (char >= charCodeMap2.a && char <= charCodeMap2.f) + return char - (charCodeMap2.a - 10); + return void 0; +} +function pad2(bytes, options = {}) { + const { dir, size: size5 = 32 } = options; + if (size5 === 0) + return bytes; + if (bytes.length > size5) + throw new SizeExceedsPaddingSizeError2({ + size: bytes.length, + targetSize: size5, + type: "Bytes" + }); + const paddedBytes = new Uint8Array(size5); + for (let i = 0; i < size5; i++) { + const padEnd = dir === "right"; + paddedBytes[padEnd ? i : size5 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; + } + return paddedBytes; +} + +// node_modules/ox/_esm/core/internal/hex.js +function assertSize3(hex, size_) { + if (size4(hex) > size_) + throw new SizeOverflowError3({ + givenSize: size4(hex), + maxSize: size_ + }); +} +function assertStartOffset2(value, start) { + if (typeof start === "number" && start > 0 && start > size4(value) - 1) + throw new SliceOffsetOutOfBoundsError3({ + offset: start, + position: "start", + size: size4(value) + }); +} +function assertEndOffset2(value, start, end) { + if (typeof start === "number" && typeof end === "number" && size4(value) !== end - start) { + throw new SliceOffsetOutOfBoundsError3({ + offset: end, + position: "end", + size: size4(value) + }); + } +} +function pad3(hex_, options = {}) { + const { dir, size: size5 = 32 } = options; + if (size5 === 0) + return hex_; + const hex = hex_.replace("0x", ""); + if (hex.length > size5 * 2) + throw new SizeExceedsPaddingSizeError3({ + size: Math.ceil(hex.length / 2), + targetSize: size5, + type: "Hex" + }); + return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`; +} + +// node_modules/ox/_esm/core/Bytes.js +var encoder3 = /* @__PURE__ */ new TextEncoder(); +function from(value) { + if (value instanceof Uint8Array) + return value; + if (typeof value === "string") + return fromHex2(value); + return fromArray(value); +} +function fromArray(value) { + return value instanceof Uint8Array ? value : new Uint8Array(value); +} +function fromHex2(value, options = {}) { + const { size: size5 } = options; + let hex = value; + if (size5) { + assertSize3(value, size5); + hex = padRight(value, size5); + } + let hexString = hex.slice(2); + if (hexString.length % 2) + hexString = `0${hexString}`; + const length = hexString.length / 2; + const bytes = new Uint8Array(length); + for (let index2 = 0, j2 = 0; index2 < length; index2++) { + const nibbleLeft = charCodeToBase162(hexString.charCodeAt(j2++)); + const nibbleRight = charCodeToBase162(hexString.charCodeAt(j2++)); + if (nibbleLeft === void 0 || nibbleRight === void 0) { + throw new BaseError3(`Invalid byte sequence ("${hexString[j2 - 2]}${hexString[j2 - 1]}" in "${hexString}").`); + } + bytes[index2] = nibbleLeft * 16 + nibbleRight; + } + return bytes; +} +function fromString(value, options = {}) { + const { size: size5 } = options; + const bytes = encoder3.encode(value); + if (typeof size5 === "number") { + assertSize2(bytes, size5); + return padRight2(bytes, size5); + } + return bytes; +} +function padRight2(value, size5) { + return pad2(value, { dir: "right", size: size5 }); +} +function size3(value) { + return value.length; +} +var SizeOverflowError2 = class extends BaseError3 { + constructor({ givenSize, maxSize }) { + super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Bytes.SizeOverflowError" + }); + } +}; +var SizeExceedsPaddingSizeError2 = class extends BaseError3 { + constructor({ size: size5, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Bytes.SizeExceedsPaddingSizeError" + }); + } +}; + +// node_modules/ox/_esm/core/Hex.js +var encoder4 = /* @__PURE__ */ new TextEncoder(); +var hexes3 = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); +function assert(value, options = {}) { + const { strict = false } = options; + if (!value) + throw new InvalidHexTypeError(value); + if (typeof value !== "string") + throw new InvalidHexTypeError(value); + if (strict) { + if (!/^0x[0-9a-fA-F]*$/.test(value)) + throw new InvalidHexValueError(value); + } + if (!value.startsWith("0x")) + throw new InvalidHexValueError(value); +} +function concat2(...values) { + return `0x${values.reduce((acc, x2) => acc + x2.replace("0x", ""), "")}`; +} +function fromBoolean(value, options = {}) { + const hex = `0x${Number(value)}`; + if (typeof options.size === "number") { + assertSize3(hex, options.size); + return padLeft(hex, options.size); + } + return hex; +} +function fromBytes(value, options = {}) { + let string = ""; + for (let i = 0; i < value.length; i++) + string += hexes3[value[i]]; + const hex = `0x${string}`; + if (typeof options.size === "number") { + assertSize3(hex, options.size); + return padRight(hex, options.size); + } + return hex; +} +function fromNumber(value, options = {}) { + const { signed, size: size5 } = options; + const value_ = BigInt(value); + let maxValue; + if (size5) { + if (signed) + maxValue = (1n << BigInt(size5) * 8n - 1n) - 1n; + else + maxValue = 2n ** (BigInt(size5) * 8n) - 1n; + } else if (typeof value === "number") { + maxValue = BigInt(Number.MAX_SAFE_INTEGER); + } + const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0; + if (maxValue && value_ > maxValue || value_ < minValue) { + const suffix = typeof value === "bigint" ? "n" : ""; + throw new IntegerOutOfRangeError2({ + max: maxValue ? `${maxValue}${suffix}` : void 0, + min: `${minValue}${suffix}`, + signed, + size: size5, + value: `${value}${suffix}` + }); + } + const stringValue = (signed && value_ < 0 ? (1n << BigInt(size5 * 8)) + BigInt(value_) : value_).toString(16); + const hex = `0x${stringValue}`; + if (size5) + return padLeft(hex, size5); + return hex; +} +function fromString2(value, options = {}) { + return fromBytes(encoder4.encode(value), options); +} +function padLeft(value, size5) { + return pad3(value, { dir: "left", size: size5 }); +} +function padRight(value, size5) { + return pad3(value, { dir: "right", size: size5 }); +} +function slice2(value, start, end, options = {}) { + const { strict } = options; + assertStartOffset2(value, start); + const value_ = `0x${value.replace("0x", "").slice((start ?? 0) * 2, (end ?? value.length) * 2)}`; + if (strict) + assertEndOffset2(value_, start, end); + return value_; +} +function size4(value) { + return Math.ceil((value.length - 2) / 2); +} +function validate(value, options = {}) { + const { strict = false } = options; + try { + assert(value, { strict }); + return true; + } catch { + return false; + } +} +var IntegerOutOfRangeError2 = class extends BaseError3 { + constructor({ max, min, signed, size: size5, value }) { + super(`Number \`${value}\` is not in safe${size5 ? ` ${size5 * 8}-bit` : ""}${signed ? " signed" : " unsigned"} integer range ${max ? `(\`${min}\` to \`${max}\`)` : `(above \`${min}\`)`}`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.IntegerOutOfRangeError" + }); + } +}; +var InvalidHexTypeError = class extends BaseError3 { + constructor(value) { + super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid hex type.`, { + metaMessages: ['Hex types must be represented as `"0x${string}"`.'] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.InvalidHexTypeError" + }); + } +}; +var InvalidHexValueError = class extends BaseError3 { + constructor(value) { + super(`Value \`${value}\` is an invalid hex value.`, { + metaMessages: [ + 'Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).' + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.InvalidHexValueError" + }); + } +}; +var SizeOverflowError3 = class extends BaseError3 { + constructor({ givenSize, maxSize }) { + super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.SizeOverflowError" + }); + } +}; +var SliceOffsetOutOfBoundsError3 = class extends BaseError3 { + constructor({ offset, position, size: size5 }) { + super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size5}\`).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.SliceOffsetOutOfBoundsError" + }); + } +}; +var SizeExceedsPaddingSizeError3 = class extends BaseError3 { + constructor({ size: size5, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.SizeExceedsPaddingSizeError" + }); + } +}; + +// node_modules/ox/_esm/core/Withdrawal.js +function toRpc(withdrawal) { + return { + address: withdrawal.address, + amount: fromNumber(withdrawal.amount), + index: fromNumber(withdrawal.index), + validatorIndex: fromNumber(withdrawal.validatorIndex) + }; +} + +// node_modules/ox/_esm/core/BlockOverrides.js +function toRpc2(blockOverrides) { + return { + ...typeof blockOverrides.baseFeePerGas === "bigint" && { + baseFeePerGas: fromNumber(blockOverrides.baseFeePerGas) + }, + ...typeof blockOverrides.blobBaseFee === "bigint" && { + blobBaseFee: fromNumber(blockOverrides.blobBaseFee) + }, + ...typeof blockOverrides.feeRecipient === "string" && { + feeRecipient: blockOverrides.feeRecipient + }, + ...typeof blockOverrides.gasLimit === "bigint" && { + gasLimit: fromNumber(blockOverrides.gasLimit) + }, + ...typeof blockOverrides.number === "bigint" && { + number: fromNumber(blockOverrides.number) + }, + ...typeof blockOverrides.prevRandao === "bigint" && { + prevRandao: fromNumber(blockOverrides.prevRandao) + }, + ...typeof blockOverrides.time === "bigint" && { + time: fromNumber(blockOverrides.time) + }, + ...blockOverrides.withdrawals && { + withdrawals: blockOverrides.withdrawals.map(toRpc) + } + }; +} + +// node_modules/viem/_esm/actions/public/simulateBlocks.js +init_parseAccount(); +init_abi(); +init_contract(); +init_node(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_toHex(); +init_getNodeError(); +init_transactionRequest(); +init_stateOverride2(); +init_assertRequest(); +async function simulateBlocks(client, parameters) { + const { blockNumber, blockTag = "latest", blocks, returnFullTransactions, traceTransfers, validation } = parameters; + try { + const blockStateCalls = []; + for (const block2 of blocks) { + const blockOverrides = block2.blockOverrides ? toRpc2(block2.blockOverrides) : void 0; + const calls = block2.calls.map((call_) => { + const call2 = call_; + const account = call2.account ? parseAccount(call2.account) : void 0; + const request = { + ...call2, + data: call2.abi ? encodeFunctionData(call2) : call2.data, + from: call2.from ?? account?.address + }; + assertRequest(request); + return formatTransactionRequest(request); + }); + const stateOverrides = block2.stateOverrides ? serializeStateOverride(block2.stateOverrides) : void 0; + blockStateCalls.push({ + blockOverrides, + calls, + stateOverrides + }); + } + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const result = await client.request({ + method: "eth_simulateV1", + params: [ + { blockStateCalls, returnFullTransactions, traceTransfers, validation }, + block + ] + }); + return result.map((block2, i) => ({ + ...formatBlock(block2), + calls: block2.calls.map((call2, j2) => { + const { abi: abi4, args, functionName, to: to2 } = blocks[i].calls[j2]; + const data = call2.error?.data ?? call2.returnData; + const gasUsed = BigInt(call2.gasUsed); + const logs = call2.logs?.map((log) => formatLog(log)); + const status = call2.status === "0x1" ? "success" : "failure"; + const result2 = abi4 && status === "success" && data !== "0x" ? decodeFunctionResult({ + abi: abi4, + data, + functionName + }) : null; + const error = (() => { + if (status === "success") + return void 0; + let error2 = void 0; + if (call2.error?.data === "0x") + error2 = new AbiDecodingZeroDataError(); + else if (call2.error) + error2 = new RawContractError(call2.error); + if (!error2) + return void 0; + return getContractError(error2, { + abi: abi4 ?? [], + address: to2, + args, + functionName: functionName ?? "" + }); + })(); + return { + data, + gasUsed, + logs, + status, + ...status === "success" ? { + result: result2 + } : { + error + } + }; + }) + })); + } catch (e) { + const cause = e; + const error = getNodeError(cause, {}); + if (error instanceof UnknownNodeError) + throw cause; + throw error; + } +} + +// node_modules/ox/_esm/core/AbiItem.js +init_exports(); + +// node_modules/ox/node_modules/@noble/hashes/esm/_assert.js +function anumber2(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error("positive integer expected, got " + n); +} +function isBytes3(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; +} +function abytes3(b2, ...lengths) { + if (!isBytes3(b2)) + throw new Error("Uint8Array expected"); + if (lengths.length > 0 && !lengths.includes(b2.length)) + throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b2.length); +} +function aexists2(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function aoutput2(out, instance) { + abytes3(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error("digestInto() expects output buffer of length at least " + min); + } +} + +// node_modules/ox/node_modules/@noble/hashes/esm/utils.js +function u322(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +var isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); +function byteSwap2(word) { + return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; +} +function byteSwap322(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap2(arr[i]); + } +} +function utf8ToBytes3(str) { + if (typeof str !== "string") + throw new Error("utf8ToBytes expected string, got " + typeof str); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes3(data) { + if (typeof data === "string") + data = utf8ToBytes3(data); + abytes3(data); + return data; +} +var Hash2 = class { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +}; +function wrapConstructor2(hashCons) { + const hashC = (msg) => hashCons().update(toBytes3(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function wrapXOFConstructorWithOpts2(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes3(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} + +// node_modules/ox/node_modules/@noble/hashes/esm/_u64.js +var U32_MASK642 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +var _32n2 = /* @__PURE__ */ BigInt(32); +function fromBig2(n, le2 = false) { + if (le2) + return { h: Number(n & U32_MASK642), l: Number(n >> _32n2 & U32_MASK642) }; + return { h: Number(n >> _32n2 & U32_MASK642) | 0, l: Number(n & U32_MASK642) | 0 }; +} +function split2(lst, le2 = false) { + let Ah = new Uint32Array(lst.length); + let Al2 = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig2(lst[i], le2); + [Ah[i], Al2[i]] = [h, l]; + } + return [Ah, Al2]; +} +var rotlSH2 = (h, l, s) => h << s | l >>> 32 - s; +var rotlSL2 = (h, l, s) => l << s | h >>> 32 - s; +var rotlBH2 = (h, l, s) => l << s - 32 | h >>> 64 - s; +var rotlBL2 = (h, l, s) => h << s - 32 | l >>> 64 - s; + +// node_modules/ox/node_modules/@noble/hashes/esm/sha3.js +var SHA3_PI2 = []; +var SHA3_ROTL2 = []; +var _SHA3_IOTA2 = []; +var _0n7 = /* @__PURE__ */ BigInt(0); +var _1n7 = /* @__PURE__ */ BigInt(1); +var _2n6 = /* @__PURE__ */ BigInt(2); +var _7n2 = /* @__PURE__ */ BigInt(7); +var _256n2 = /* @__PURE__ */ BigInt(256); +var _0x71n2 = /* @__PURE__ */ BigInt(113); +for (let round = 0, R2 = _1n7, x2 = 1, y2 = 0; round < 24; round++) { + [x2, y2] = [y2, (2 * x2 + 3 * y2) % 5]; + SHA3_PI2.push(2 * (5 * y2 + x2)); + SHA3_ROTL2.push((round + 1) * (round + 2) / 2 % 64); + let t = _0n7; + for (let j2 = 0; j2 < 7; j2++) { + R2 = (R2 << _1n7 ^ (R2 >> _7n2) * _0x71n2) % _256n2; + if (R2 & _2n6) + t ^= _1n7 << (_1n7 << /* @__PURE__ */ BigInt(j2)) - _1n7; + } + _SHA3_IOTA2.push(t); +} +var [SHA3_IOTA_H2, SHA3_IOTA_L2] = /* @__PURE__ */ split2(_SHA3_IOTA2, true); +var rotlH2 = (h, l, s) => s > 32 ? rotlBH2(h, l, s) : rotlSH2(h, l, s); +var rotlL2 = (h, l, s) => s > 32 ? rotlBL2(h, l, s) : rotlSL2(h, l, s); +function keccakP2(s, rounds = 24) { + const B2 = new Uint32Array(5 * 2); + for (let round = 24 - rounds; round < 24; round++) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s[x2] ^ s[x2 + 10] ^ s[x2 + 20] ^ s[x2 + 30] ^ s[x2 + 40]; + for (let x2 = 0; x2 < 10; x2 += 2) { + const idx1 = (x2 + 8) % 10; + const idx0 = (x2 + 2) % 10; + const B0 = B2[idx0]; + const B1 = B2[idx0 + 1]; + const Th = rotlH2(B0, B1, 1) ^ B2[idx1]; + const Tl2 = rotlL2(B0, B1, 1) ^ B2[idx1 + 1]; + for (let y2 = 0; y2 < 50; y2 += 10) { + s[x2 + y2] ^= Th; + s[x2 + y2 + 1] ^= Tl2; + } + } + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL2[t]; + const Th = rotlH2(curH, curL, shift); + const Tl2 = rotlL2(curH, curL, shift); + const PI = SHA3_PI2[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl2; + } + for (let y2 = 0; y2 < 50; y2 += 10) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s[y2 + x2]; + for (let x2 = 0; x2 < 10; x2++) + s[y2 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10]; + } + s[0] ^= SHA3_IOTA_H2[round]; + s[1] ^= SHA3_IOTA_L2[round]; + } + B2.fill(0); +} +var Keccak2 = class _Keccak extends Hash2 { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + anumber2(outputLen); + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error("Sha3 supports only keccak-f1600 function"); + this.state = new Uint8Array(200); + this.state32 = u322(this.state); + } + keccak() { + if (!isLE2) + byteSwap322(this.state32); + keccakP2(this.state32, this.rounds); + if (!isLE2) + byteSwap322(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + aexists2(this); + const { blockLen, state } = this; + data = toBytes3(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + state[pos] ^= suffix; + if ((suffix & 128) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 128; + this.keccak(); + } + writeInto(out) { + aexists2(this, false); + abytes3(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); + } + xof(bytes) { + anumber2(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + aoutput2(out, this); + if (this.finished) + throw new Error("digest() was already called"); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to2) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to2 || (to2 = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to2.state32.set(this.state32); + to2.pos = this.pos; + to2.posOut = this.posOut; + to2.finished = this.finished; + to2.rounds = rounds; + to2.suffix = suffix; + to2.outputLen = outputLen; + to2.enableXOF = enableXOF; + to2.destroyed = this.destroyed; + return to2; + } +}; +var gen2 = (suffix, blockLen, outputLen) => wrapConstructor2(() => new Keccak2(blockLen, suffix, outputLen)); +var sha3_2242 = /* @__PURE__ */ gen2(6, 144, 224 / 8); +var sha3_2562 = /* @__PURE__ */ gen2(6, 136, 256 / 8); +var sha3_3842 = /* @__PURE__ */ gen2(6, 104, 384 / 8); +var sha3_5122 = /* @__PURE__ */ gen2(6, 72, 512 / 8); +var keccak_2242 = /* @__PURE__ */ gen2(1, 144, 224 / 8); +var keccak_2562 = /* @__PURE__ */ gen2(1, 136, 256 / 8); +var keccak_3842 = /* @__PURE__ */ gen2(1, 104, 384 / 8); +var keccak_5122 = /* @__PURE__ */ gen2(1, 72, 512 / 8); +var genShake2 = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts2((opts = {}) => new Keccak2(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true)); +var shake1282 = /* @__PURE__ */ genShake2(31, 168, 128 / 8); +var shake2562 = /* @__PURE__ */ genShake2(31, 136, 256 / 8); + +// node_modules/ox/_esm/core/Hash.js +function keccak2562(value, options = {}) { + const { as: as2 = typeof value === "string" ? "Hex" : "Bytes" } = options; + const bytes = keccak_2562(from(value)); + if (as2 === "Bytes") + return bytes; + return fromBytes(bytes); +} + +// node_modules/ox/_esm/core/internal/lru.js +var LruMap2 = class extends Map { + constructor(size5) { + super(); + Object.defineProperty(this, "maxSize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxSize = size5; + } + get(key) { + const value = super.get(key); + if (super.has(key) && value !== void 0) { + this.delete(key); + super.set(key, value); + } + return value; + } + set(key, value) { + super.set(key, value); + if (this.maxSize && this.size > this.maxSize) { + const firstKey = this.keys().next().value; + if (firstKey) + this.delete(firstKey); + } + return this; + } +}; + +// node_modules/ox/_esm/core/Caches.js +var caches = { + checksum: /* @__PURE__ */ new LruMap2(8192) +}; +var checksum = caches.checksum; + +// node_modules/ox/_esm/core/Address.js +var addressRegex2 = /^0x[a-fA-F0-9]{40}$/; +function assert2(value, options = {}) { + const { strict = true } = options; + if (!addressRegex2.test(value)) + throw new InvalidAddressError2({ + address: value, + cause: new InvalidInputError() + }); + if (strict) { + if (value.toLowerCase() === value) + return; + if (checksum2(value) !== value) + throw new InvalidAddressError2({ + address: value, + cause: new InvalidChecksumError() + }); + } +} +function checksum2(address) { + if (checksum.has(address)) + return checksum.get(address); + assert2(address, { strict: false }); + const hexAddress = address.substring(2).toLowerCase(); + const hash2 = keccak2562(fromString(hexAddress), { as: "Bytes" }); + const characters = hexAddress.split(""); + for (let i = 0; i < 40; i += 2) { + if (hash2[i >> 1] >> 4 >= 8 && characters[i]) { + characters[i] = characters[i].toUpperCase(); + } + if ((hash2[i >> 1] & 15) >= 8 && characters[i + 1]) { + characters[i + 1] = characters[i + 1].toUpperCase(); + } + } + const result = `0x${characters.join("")}`; + checksum.set(address, result); + return result; +} +function validate2(address, options = {}) { + const { strict = true } = options ?? {}; + try { + assert2(address, { strict }); + return true; + } catch { + return false; + } +} +var InvalidAddressError2 = class extends BaseError3 { + constructor({ address, cause }) { + super(`Address "${address}" is invalid.`, { + cause + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Address.InvalidAddressError" + }); + } +}; +var InvalidInputError = class extends BaseError3 { + constructor() { + super("Address is not a 20 byte (40 hexadecimal character) value."); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Address.InvalidInputError" + }); + } +}; +var InvalidChecksumError = class extends BaseError3 { + constructor() { + super("Address does not match its checksum counterpart."); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Address.InvalidChecksumError" + }); + } +}; + +// node_modules/ox/_esm/core/internal/abiItem.js +function normalizeSignature2(signature) { + let active = true; + let current = ""; + let level = 0; + let result = ""; + let valid = false; + for (let i = 0; i < signature.length; i++) { + const char = signature[i]; + if (["(", ")", ","].includes(char)) + active = true; + if (char === "(") + level++; + if (char === ")") + level--; + if (!active) + continue; + if (level === 0) { + if (char === " " && ["event", "function", "error", ""].includes(result)) + result = ""; + else { + result += char; + if (char === ")") { + valid = true; + break; + } + } + continue; + } + if (char === " ") { + if (signature[i - 1] !== "," && current !== "," && current !== ",(") { + current = ""; + active = false; + } + continue; + } + result += char; + current += char; + } + if (!valid) + throw new BaseError3("Unable to normalize signature."); + return result; +} +function isArgOfType2(arg, abiParameter) { + const argType = typeof arg; + const abiParameterType = abiParameter.type; + switch (abiParameterType) { + case "address": + return validate2(arg, { strict: false }); + case "bool": + return argType === "boolean"; + case "function": + return argType === "string"; + case "string": + return argType === "string"; + default: { + if (abiParameterType === "tuple" && "components" in abiParameter) + return Object.values(abiParameter.components).every((component, index2) => { + return isArgOfType2(Object.values(arg)[index2], component); + }); + if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) + return argType === "number" || argType === "bigint"; + if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) + return argType === "string" || arg instanceof Uint8Array; + if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { + return Array.isArray(arg) && arg.every((x2) => isArgOfType2(x2, { + ...abiParameter, + // Pop off `[]` or `[M]` from end of type + type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") + })); + } + return false; + } + } +} +function getAmbiguousTypes2(sourceParameters, targetParameters, args) { + for (const parameterIndex in sourceParameters) { + const sourceParameter = sourceParameters[parameterIndex]; + const targetParameter = targetParameters[parameterIndex]; + if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) + return getAmbiguousTypes2(sourceParameter.components, targetParameter.components, args[parameterIndex]); + const types = [sourceParameter.type, targetParameter.type]; + const ambiguous = (() => { + if (types.includes("address") && types.includes("bytes20")) + return true; + if (types.includes("address") && types.includes("string")) + return validate2(args[parameterIndex], { + strict: false + }); + if (types.includes("address") && types.includes("bytes")) + return validate2(args[parameterIndex], { + strict: false + }); + return false; + })(); + if (ambiguous) + return types; + } + return; +} + +// node_modules/ox/_esm/core/AbiItem.js +function from2(abiItem, options = {}) { + const { prepare = true } = options; + const item = (() => { + if (Array.isArray(abiItem)) + return parseAbiItem(abiItem); + if (typeof abiItem === "string") + return parseAbiItem(abiItem); + return abiItem; + })(); + return { + ...item, + ...prepare ? { hash: getSignatureHash(item) } : {} + }; +} +function fromAbi(abi4, name, options) { + const { args = [], prepare = true } = options ?? {}; + const isSelector = validate(name, { strict: false }); + const abiItems = abi4.filter((abiItem2) => { + if (isSelector) { + if (abiItem2.type === "function" || abiItem2.type === "error") + return getSelector(abiItem2) === slice2(name, 0, 4); + if (abiItem2.type === "event") + return getSignatureHash(abiItem2) === name; + return false; + } + return "name" in abiItem2 && abiItem2.name === name; + }); + if (abiItems.length === 0) + throw new NotFoundError2({ name }); + if (abiItems.length === 1) + return { + ...abiItems[0], + ...prepare ? { hash: getSignatureHash(abiItems[0]) } : {} + }; + let matchedAbiItem = void 0; + for (const abiItem2 of abiItems) { + if (!("inputs" in abiItem2)) + continue; + if (!args || args.length === 0) { + if (!abiItem2.inputs || abiItem2.inputs.length === 0) + return { + ...abiItem2, + ...prepare ? { hash: getSignatureHash(abiItem2) } : {} + }; + continue; + } + if (!abiItem2.inputs) + continue; + if (abiItem2.inputs.length === 0) + continue; + if (abiItem2.inputs.length !== args.length) + continue; + const matched = args.every((arg, index2) => { + const abiParameter = "inputs" in abiItem2 && abiItem2.inputs[index2]; + if (!abiParameter) + return false; + return isArgOfType2(arg, abiParameter); + }); + if (matched) { + if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { + const ambiguousTypes = getAmbiguousTypes2(abiItem2.inputs, matchedAbiItem.inputs, args); + if (ambiguousTypes) + throw new AmbiguityError({ + abiItem: abiItem2, + type: ambiguousTypes[0] + }, { + abiItem: matchedAbiItem, + type: ambiguousTypes[1] + }); + } + matchedAbiItem = abiItem2; + } + } + const abiItem = (() => { + if (matchedAbiItem) + return matchedAbiItem; + const [abiItem2, ...overloads] = abiItems; + return { ...abiItem2, overloads }; + })(); + if (!abiItem) + throw new NotFoundError2({ name }); + return { + ...abiItem, + ...prepare ? { hash: getSignatureHash(abiItem) } : {} + }; +} +function getSelector(abiItem) { + return slice2(getSignatureHash(abiItem), 0, 4); +} +function getSignature(abiItem) { + const signature = (() => { + if (typeof abiItem === "string") + return abiItem; + return formatAbiItem(abiItem); + })(); + return normalizeSignature2(signature); +} +function getSignatureHash(abiItem) { + if (typeof abiItem !== "string" && "hash" in abiItem && abiItem.hash) + return abiItem.hash; + return keccak2562(fromString2(getSignature(abiItem))); +} +var AmbiguityError = class extends BaseError3 { + constructor(x2, y2) { + super("Found ambiguous types in overloaded ABI Items.", { + metaMessages: [ + // TODO: abitype to add support for signature-formatted ABI items. + `\`${x2.type}\` in \`${normalizeSignature2(formatAbiItem(x2.abiItem))}\`, and`, + `\`${y2.type}\` in \`${normalizeSignature2(formatAbiItem(y2.abiItem))}\``, + "", + "These types encode differently and cannot be distinguished at runtime.", + "Remove one of the ambiguous items in the ABI." + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiItem.AmbiguityError" + }); + } +}; +var NotFoundError2 = class extends BaseError3 { + constructor({ name, data, type = "item" }) { + const selector = (() => { + if (name) + return ` with name "${name}"`; + if (data) + return ` with data "${data}"`; + return ""; + })(); + super(`ABI ${type}${selector} not found.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiItem.NotFoundError" + }); + } +}; + +// node_modules/ox/_esm/core/Solidity.js +var arrayRegex = /^(.*)\[([0-9]*)\]$/; +var bytesRegex3 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; +var integerRegex3 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; +var maxInt82 = 2n ** (8n - 1n) - 1n; +var maxInt162 = 2n ** (16n - 1n) - 1n; +var maxInt242 = 2n ** (24n - 1n) - 1n; +var maxInt322 = 2n ** (32n - 1n) - 1n; +var maxInt402 = 2n ** (40n - 1n) - 1n; +var maxInt482 = 2n ** (48n - 1n) - 1n; +var maxInt562 = 2n ** (56n - 1n) - 1n; +var maxInt642 = 2n ** (64n - 1n) - 1n; +var maxInt722 = 2n ** (72n - 1n) - 1n; +var maxInt802 = 2n ** (80n - 1n) - 1n; +var maxInt882 = 2n ** (88n - 1n) - 1n; +var maxInt962 = 2n ** (96n - 1n) - 1n; +var maxInt1042 = 2n ** (104n - 1n) - 1n; +var maxInt1122 = 2n ** (112n - 1n) - 1n; +var maxInt1202 = 2n ** (120n - 1n) - 1n; +var maxInt1282 = 2n ** (128n - 1n) - 1n; +var maxInt1362 = 2n ** (136n - 1n) - 1n; +var maxInt1442 = 2n ** (144n - 1n) - 1n; +var maxInt1522 = 2n ** (152n - 1n) - 1n; +var maxInt1602 = 2n ** (160n - 1n) - 1n; +var maxInt1682 = 2n ** (168n - 1n) - 1n; +var maxInt1762 = 2n ** (176n - 1n) - 1n; +var maxInt1842 = 2n ** (184n - 1n) - 1n; +var maxInt1922 = 2n ** (192n - 1n) - 1n; +var maxInt2002 = 2n ** (200n - 1n) - 1n; +var maxInt2082 = 2n ** (208n - 1n) - 1n; +var maxInt2162 = 2n ** (216n - 1n) - 1n; +var maxInt2242 = 2n ** (224n - 1n) - 1n; +var maxInt2322 = 2n ** (232n - 1n) - 1n; +var maxInt2402 = 2n ** (240n - 1n) - 1n; +var maxInt2482 = 2n ** (248n - 1n) - 1n; +var maxInt2562 = 2n ** (256n - 1n) - 1n; +var minInt82 = -(2n ** (8n - 1n)); +var minInt162 = -(2n ** (16n - 1n)); +var minInt242 = -(2n ** (24n - 1n)); +var minInt322 = -(2n ** (32n - 1n)); +var minInt402 = -(2n ** (40n - 1n)); +var minInt482 = -(2n ** (48n - 1n)); +var minInt562 = -(2n ** (56n - 1n)); +var minInt642 = -(2n ** (64n - 1n)); +var minInt722 = -(2n ** (72n - 1n)); +var minInt802 = -(2n ** (80n - 1n)); +var minInt882 = -(2n ** (88n - 1n)); +var minInt962 = -(2n ** (96n - 1n)); +var minInt1042 = -(2n ** (104n - 1n)); +var minInt1122 = -(2n ** (112n - 1n)); +var minInt1202 = -(2n ** (120n - 1n)); +var minInt1282 = -(2n ** (128n - 1n)); +var minInt1362 = -(2n ** (136n - 1n)); +var minInt1442 = -(2n ** (144n - 1n)); +var minInt1522 = -(2n ** (152n - 1n)); +var minInt1602 = -(2n ** (160n - 1n)); +var minInt1682 = -(2n ** (168n - 1n)); +var minInt1762 = -(2n ** (176n - 1n)); +var minInt1842 = -(2n ** (184n - 1n)); +var minInt1922 = -(2n ** (192n - 1n)); +var minInt2002 = -(2n ** (200n - 1n)); +var minInt2082 = -(2n ** (208n - 1n)); +var minInt2162 = -(2n ** (216n - 1n)); +var minInt2242 = -(2n ** (224n - 1n)); +var minInt2322 = -(2n ** (232n - 1n)); +var minInt2402 = -(2n ** (240n - 1n)); +var minInt2482 = -(2n ** (248n - 1n)); +var minInt2562 = -(2n ** (256n - 1n)); +var maxUint82 = 2n ** 8n - 1n; +var maxUint162 = 2n ** 16n - 1n; +var maxUint242 = 2n ** 24n - 1n; +var maxUint322 = 2n ** 32n - 1n; +var maxUint402 = 2n ** 40n - 1n; +var maxUint482 = 2n ** 48n - 1n; +var maxUint562 = 2n ** 56n - 1n; +var maxUint642 = 2n ** 64n - 1n; +var maxUint722 = 2n ** 72n - 1n; +var maxUint802 = 2n ** 80n - 1n; +var maxUint882 = 2n ** 88n - 1n; +var maxUint962 = 2n ** 96n - 1n; +var maxUint1042 = 2n ** 104n - 1n; +var maxUint1122 = 2n ** 112n - 1n; +var maxUint1202 = 2n ** 120n - 1n; +var maxUint1282 = 2n ** 128n - 1n; +var maxUint1362 = 2n ** 136n - 1n; +var maxUint1442 = 2n ** 144n - 1n; +var maxUint1522 = 2n ** 152n - 1n; +var maxUint1602 = 2n ** 160n - 1n; +var maxUint1682 = 2n ** 168n - 1n; +var maxUint1762 = 2n ** 176n - 1n; +var maxUint1842 = 2n ** 184n - 1n; +var maxUint1922 = 2n ** 192n - 1n; +var maxUint2002 = 2n ** 200n - 1n; +var maxUint2082 = 2n ** 208n - 1n; +var maxUint2162 = 2n ** 216n - 1n; +var maxUint2242 = 2n ** 224n - 1n; +var maxUint2322 = 2n ** 232n - 1n; +var maxUint2402 = 2n ** 240n - 1n; +var maxUint2482 = 2n ** 248n - 1n; +var maxUint2562 = 2n ** 256n - 1n; + +// node_modules/ox/_esm/core/internal/abiParameters.js +function prepareParameters({ checksumAddress: checksumAddress2, parameters, values }) { + const preparedParameters = []; + for (let i = 0; i < parameters.length; i++) { + preparedParameters.push(prepareParameter({ + checksumAddress: checksumAddress2, + parameter: parameters[i], + value: values[i] + })); + } + return preparedParameters; +} +function prepareParameter({ checksumAddress: checksumAddress2 = false, parameter: parameter_, value }) { + const parameter = parameter_; + const arrayComponents = getArrayComponents2(parameter.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return encodeArray2(value, { + checksumAddress: checksumAddress2, + length, + parameter: { + ...parameter, + type + } + }); + } + if (parameter.type === "tuple") { + return encodeTuple2(value, { + checksumAddress: checksumAddress2, + parameter + }); + } + if (parameter.type === "address") { + return encodeAddress2(value, { + checksum: checksumAddress2 + }); + } + if (parameter.type === "bool") { + return encodeBoolean(value); + } + if (parameter.type.startsWith("uint") || parameter.type.startsWith("int")) { + const signed = parameter.type.startsWith("int"); + const [, , size5 = "256"] = integerRegex3.exec(parameter.type) ?? []; + return encodeNumber2(value, { + signed, + size: Number(size5) + }); + } + if (parameter.type.startsWith("bytes")) { + return encodeBytes2(value, { type: parameter.type }); + } + if (parameter.type === "string") { + return encodeString2(value); + } + throw new InvalidTypeError(parameter.type); +} +function encode3(preparedParameters) { + let staticSize = 0; + for (let i = 0; i < preparedParameters.length; i++) { + const { dynamic, encoded } = preparedParameters[i]; + if (dynamic) + staticSize += 32; + else + staticSize += size4(encoded); + } + const staticParameters = []; + const dynamicParameters = []; + let dynamicSize = 0; + for (let i = 0; i < preparedParameters.length; i++) { + const { dynamic, encoded } = preparedParameters[i]; + if (dynamic) { + staticParameters.push(fromNumber(staticSize + dynamicSize, { size: 32 })); + dynamicParameters.push(encoded); + dynamicSize += size4(encoded); + } else { + staticParameters.push(encoded); + } + } + return concat2(...staticParameters, ...dynamicParameters); +} +function encodeAddress2(value, options) { + const { checksum: checksum3 = false } = options; + assert2(value, { strict: checksum3 }); + return { + dynamic: false, + encoded: padLeft(value.toLowerCase()) + }; +} +function encodeArray2(value, options) { + const { checksumAddress: checksumAddress2, length, parameter } = options; + const dynamic = length === null; + if (!Array.isArray(value)) + throw new InvalidArrayError2(value); + if (!dynamic && value.length !== length) + throw new ArrayLengthMismatchError({ + expectedLength: length, + givenLength: value.length, + type: `${parameter.type}[${length}]` + }); + let dynamicChild = false; + const preparedParameters = []; + for (let i = 0; i < value.length; i++) { + const preparedParam = prepareParameter({ + checksumAddress: checksumAddress2, + parameter, + value: value[i] + }); + if (preparedParam.dynamic) + dynamicChild = true; + preparedParameters.push(preparedParam); + } + if (dynamic || dynamicChild) { + const data = encode3(preparedParameters); + if (dynamic) { + const length2 = fromNumber(preparedParameters.length, { size: 32 }); + return { + dynamic: true, + encoded: preparedParameters.length > 0 ? concat2(length2, data) : length2 + }; + } + if (dynamicChild) + return { dynamic: true, encoded: data }; + } + return { + dynamic: false, + encoded: concat2(...preparedParameters.map(({ encoded }) => encoded)) + }; +} +function encodeBytes2(value, { type }) { + const [, parametersize] = type.split("bytes"); + const bytesSize = size4(value); + if (!parametersize) { + let value_ = value; + if (bytesSize % 32 !== 0) + value_ = padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32); + return { + dynamic: true, + encoded: concat2(padLeft(fromNumber(bytesSize, { size: 32 })), value_) + }; + } + if (bytesSize !== Number.parseInt(parametersize)) + throw new BytesSizeMismatchError2({ + expectedSize: Number.parseInt(parametersize), + value + }); + return { dynamic: false, encoded: padRight(value) }; +} +function encodeBoolean(value) { + if (typeof value !== "boolean") + throw new BaseError3(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); + return { dynamic: false, encoded: padLeft(fromBoolean(value)) }; +} +function encodeNumber2(value, { signed, size: size5 }) { + if (typeof size5 === "number") { + const max = 2n ** (BigInt(size5) - (signed ? 1n : 0n)) - 1n; + const min = signed ? -max - 1n : 0n; + if (value > max || value < min) + throw new IntegerOutOfRangeError2({ + max: max.toString(), + min: min.toString(), + signed, + size: size5 / 8, + value: value.toString() + }); + } + return { + dynamic: false, + encoded: fromNumber(value, { + size: 32, + signed + }) + }; +} +function encodeString2(value) { + const hexValue = fromString2(value); + const partsLength = Math.ceil(size4(hexValue) / 32); + const parts = []; + for (let i = 0; i < partsLength; i++) { + parts.push(padRight(slice2(hexValue, i * 32, (i + 1) * 32))); + } + return { + dynamic: true, + encoded: concat2(padRight(fromNumber(size4(hexValue), { size: 32 })), ...parts) + }; +} +function encodeTuple2(value, options) { + const { checksumAddress: checksumAddress2, parameter } = options; + let dynamic = false; + const preparedParameters = []; + for (let i = 0; i < parameter.components.length; i++) { + const param_ = parameter.components[i]; + const index2 = Array.isArray(value) ? i : param_.name; + const preparedParam = prepareParameter({ + checksumAddress: checksumAddress2, + parameter: param_, + value: value[index2] + }); + preparedParameters.push(preparedParam); + if (preparedParam.dynamic) + dynamic = true; + } + return { + dynamic, + encoded: dynamic ? encode3(preparedParameters) : concat2(...preparedParameters.map(({ encoded }) => encoded)) + }; +} +function getArrayComponents2(type) { + const matches = type.match(/^(.*)\[(\d+)?\]$/); + return matches ? ( + // Return `null` if the array is dynamic. + [matches[2] ? Number(matches[2]) : null, matches[1]] + ) : void 0; +} + +// node_modules/ox/_esm/core/AbiParameters.js +function encode4(parameters, values, options) { + const { checksumAddress: checksumAddress2 = false } = options ?? {}; + if (parameters.length !== values.length) + throw new LengthMismatchError({ + expectedLength: parameters.length, + givenLength: values.length + }); + const preparedParameters = prepareParameters({ + checksumAddress: checksumAddress2, + parameters, + values + }); + const data = encode3(preparedParameters); + if (data.length === 0) + return "0x"; + return data; +} +function encodePacked(types, values) { + if (types.length !== values.length) + throw new LengthMismatchError({ + expectedLength: types.length, + givenLength: values.length + }); + const data = []; + for (let i = 0; i < types.length; i++) { + const type = types[i]; + const value = values[i]; + data.push(encodePacked.encode(type, value)); + } + return concat2(...data); +} +(function(encodePacked2) { + function encode6(type, value, isArray2 = false) { + if (type === "address") { + const address = value; + assert2(address); + return padLeft(address.toLowerCase(), isArray2 ? 32 : 0); + } + if (type === "string") + return fromString2(value); + if (type === "bytes") + return value; + if (type === "bool") + return padLeft(fromBoolean(value), isArray2 ? 32 : 1); + const intMatch = type.match(integerRegex3); + if (intMatch) { + const [_type, baseType, bits = "256"] = intMatch; + const size5 = Number.parseInt(bits) / 8; + return fromNumber(value, { + size: isArray2 ? 32 : size5, + signed: baseType === "int" + }); + } + const bytesMatch = type.match(bytesRegex3); + if (bytesMatch) { + const [_type, size5] = bytesMatch; + if (Number.parseInt(size5) !== (value.length - 2) / 2) + throw new BytesSizeMismatchError2({ + expectedSize: Number.parseInt(size5), + value + }); + return padRight(value, isArray2 ? 32 : 0); + } + const arrayMatch = type.match(arrayRegex); + if (arrayMatch && Array.isArray(value)) { + const [_type, childType] = arrayMatch; + const data = []; + for (let i = 0; i < value.length; i++) { + data.push(encode6(childType, value[i], true)); + } + if (data.length === 0) + return "0x"; + return concat2(...data); + } + throw new InvalidTypeError(type); + } + encodePacked2.encode = encode6; +})(encodePacked || (encodePacked = {})); +var ArrayLengthMismatchError = class extends BaseError3 { + constructor({ expectedLength, givenLength, type }) { + super(`Array length mismatch for type \`${type}\`. Expected: \`${expectedLength}\`. Given: \`${givenLength}\`.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.ArrayLengthMismatchError" + }); + } +}; +var BytesSizeMismatchError2 = class extends BaseError3 { + constructor({ expectedSize, value }) { + super(`Size of bytes "${value}" (bytes${size4(value)}) does not match expected size (bytes${expectedSize}).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.BytesSizeMismatchError" + }); + } +}; +var LengthMismatchError = class extends BaseError3 { + constructor({ expectedLength, givenLength }) { + super([ + "ABI encoding parameters/values length mismatch.", + `Expected length (parameters): ${expectedLength}`, + `Given length (values): ${givenLength}` + ].join("\n")); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.LengthMismatchError" + }); + } +}; +var InvalidArrayError2 = class extends BaseError3 { + constructor(value) { + super(`Value \`${value}\` is not a valid array.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.InvalidArrayError" + }); + } +}; +var InvalidTypeError = class extends BaseError3 { + constructor(type) { + super(`Type \`${type}\` is not a valid ABI Type.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.InvalidTypeError" + }); + } +}; + +// node_modules/ox/_esm/core/AbiConstructor.js +function encode5(abiConstructor, options) { + const { bytecode, args } = options; + return concat2(bytecode, abiConstructor.inputs?.length && args?.length ? encode4(abiConstructor.inputs, args) : "0x"); +} +function from3(abiConstructor) { + return from2(abiConstructor); +} + +// node_modules/ox/_esm/core/AbiFunction.js +function encodeData2(abiFunction, ...args) { + const { overloads } = abiFunction; + const item = overloads ? fromAbi2([abiFunction, ...overloads], abiFunction.name, { + args: args[0] + }) : abiFunction; + const selector = getSelector2(item); + const data = args.length > 0 ? encode4(item.inputs, args[0]) : void 0; + return data ? concat2(selector, data) : selector; +} +function from4(abiFunction, options = {}) { + return from2(abiFunction, options); +} +function fromAbi2(abi4, name, options) { + const item = fromAbi(abi4, name, options); + if (item.type !== "function") + throw new NotFoundError2({ name, type: "function" }); + return item; +} +function getSelector2(abiItem) { + return getSelector(abiItem); +} + +// node_modules/viem/_esm/actions/public/simulateCalls.js +init_parseAccount(); + +// node_modules/viem/_esm/constants/address.js +var ethAddress = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; +var zeroAddress = "0x0000000000000000000000000000000000000000"; + +// node_modules/viem/_esm/actions/public/simulateCalls.js +init_contracts(); +init_base(); +init_encodeFunctionData(); +var getBalanceCode = "0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033"; +async function simulateCalls(client, parameters) { + const { blockNumber, blockTag, calls, stateOverrides, traceAssetChanges, traceTransfers, validation } = parameters; + const account = parameters.account ? parseAccount(parameters.account) : void 0; + if (traceAssetChanges && !account) + throw new BaseError2("`account` is required when `traceAssetChanges` is true"); + const getBalanceData = account ? encode5(from3("constructor(bytes, bytes)"), { + bytecode: deploylessCallViaBytecodeBytecode, + args: [ + getBalanceCode, + encodeData2(from4("function getBalance(address)"), [account.address]) + ] + }) : void 0; + const assetAddresses = traceAssetChanges ? await Promise.all(parameters.calls.map(async (call2) => { + if (!call2.data && !call2.abi) + return; + const { accessList } = await createAccessList(client, { + account: account.address, + ...call2, + data: call2.abi ? encodeFunctionData(call2) : call2.data + }); + return accessList.map(({ address, storageKeys }) => storageKeys.length > 0 ? address : null); + })).then((x2) => x2.flat().filter(Boolean)) : []; + const resultsStateOverrides = stateOverrides?.map((override) => { + if (override.address === account?.address) + return { + ...override, + nonce: 0 + }; + return override; + }); + const blocks = await simulateBlocks(client, { + blockNumber, + blockTag, + blocks: [ + ...traceAssetChanges ? [ + // ETH pre balances + { + calls: [{ data: getBalanceData }], + stateOverrides + }, + // Asset pre balances + { + calls: assetAddresses.map((address, i) => ({ + abi: [ + from4("function balanceOf(address) returns (uint256)") + ], + functionName: "balanceOf", + args: [account.address], + to: address, + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + } + ] : [], + { + calls: [...calls, {}].map((call2, index2) => ({ + ...call2, + from: account?.address, + nonce: index2 + })), + stateOverrides: resultsStateOverrides + }, + ...traceAssetChanges ? [ + // ETH post balances + { + calls: [{ data: getBalanceData }] + }, + // Asset post balances + { + calls: assetAddresses.map((address, i) => ({ + abi: [ + from4("function balanceOf(address) returns (uint256)") + ], + functionName: "balanceOf", + args: [account.address], + to: address, + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + }, + // Decimals + { + calls: assetAddresses.map((address, i) => ({ + to: address, + abi: [ + from4("function decimals() returns (uint256)") + ], + functionName: "decimals", + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + }, + // Token URI + { + calls: assetAddresses.map((address, i) => ({ + to: address, + abi: [ + from4("function tokenURI(uint256) returns (string)") + ], + functionName: "tokenURI", + args: [0n], + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + }, + // Symbols + { + calls: assetAddresses.map((address, i) => ({ + to: address, + abi: [from4("function symbol() returns (string)")], + functionName: "symbol", + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + } + ] : [] + ], + traceTransfers, + validation + }); + const block_results = traceAssetChanges ? blocks[2] : blocks[0]; + const [block_ethPre, block_assetsPre, , block_ethPost, block_assetsPost, block_decimals, block_tokenURI, block_symbols] = traceAssetChanges ? blocks : []; + const { calls: block_calls, ...block } = block_results; + const results = block_calls.slice(0, -1) ?? []; + const ethPre = block_ethPre?.calls ?? []; + const assetsPre = block_assetsPre?.calls ?? []; + const balancesPre = [...ethPre, ...assetsPre].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null); + const ethPost = block_ethPost?.calls ?? []; + const assetsPost = block_assetsPost?.calls ?? []; + const balancesPost = [...ethPost, ...assetsPost].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null); + const decimals = (block_decimals?.calls ?? []).map((x2) => x2.status === "success" ? x2.result : null); + const symbols = (block_symbols?.calls ?? []).map((x2) => x2.status === "success" ? x2.result : null); + const tokenURI = (block_tokenURI?.calls ?? []).map((x2) => x2.status === "success" ? x2.result : null); + const changes = []; + for (const [i, balancePost] of balancesPost.entries()) { + const balancePre = balancesPre[i]; + if (typeof balancePost !== "bigint") + continue; + if (typeof balancePre !== "bigint") + continue; + const decimals_ = decimals[i - 1]; + const symbol_ = symbols[i - 1]; + const tokenURI_ = tokenURI[i - 1]; + const token = (() => { + if (i === 0) + return { + address: ethAddress, + decimals: 18, + symbol: "ETH" + }; + return { + address: assetAddresses[i - 1], + decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : void 0, + symbol: symbol_ ?? void 0 + }; + })(); + if (changes.some((change) => change.token.address === token.address)) + continue; + changes.push({ + token, + value: { + pre: balancePre, + post: balancePost, + diff: balancePost - balancePre + } + }); + } + return { + assetChanges: changes, + block, + results + }; +} + +// node_modules/viem/_esm/actions/public/verifyHash.js +init_abis(); +init_contracts(); +init_contract(); +init_encodeDeployData(); +init_getAddress(); +init_isAddressEqual(); +init_isHex(); +init_toHex(); + +// node_modules/viem/_esm/utils/signature/serializeSignature.js +init_secp256k1(); +init_fromHex(); +init_toBytes(); +function serializeSignature({ r, s, to: to2 = "hex", v, yParity }) { + const yParity_ = (() => { + if (yParity === 0 || yParity === 1) + return yParity; + if (v && (v === 27n || v === 28n || v >= 35n)) + return v % 2n === 0n ? 1 : 0; + throw new Error("Invalid `v` or `yParity` value"); + })(); + const signature = `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`; + if (to2 === "hex") + return signature; + return hexToBytes(signature); +} + +// node_modules/viem/_esm/actions/public/verifyHash.js +init_call(); +async function verifyHash(client, parameters) { + const { address, factory, factoryData, hash: hash2, signature, universalSignatureVerifierAddress = client.chain?.contracts?.universalSignatureVerifier?.address, ...rest } = parameters; + const signatureHex = (() => { + if (isHex(signature)) + return signature; + if (typeof signature === "object" && "r" in signature && "s" in signature) + return serializeSignature(signature); + return bytesToHex(signature); + })(); + const wrappedSignature = await (async () => { + if (!factory && !factoryData) + return signatureHex; + if (isErc6492Signature(signatureHex)) + return signatureHex; + return serializeErc6492Signature({ + address: factory, + data: factoryData, + signature: signatureHex + }); + })(); + try { + const args = universalSignatureVerifierAddress ? { + to: universalSignatureVerifierAddress, + data: encodeFunctionData({ + abi: universalSignatureValidatorAbi, + functionName: "isValidSig", + args: [address, hash2, wrappedSignature] + }), + ...rest + } : { + data: encodeDeployData({ + abi: universalSignatureValidatorAbi, + args: [address, hash2, wrappedSignature], + bytecode: universalSignatureValidatorByteCode + }), + ...rest + }; + const { data } = await getAction(client, call, "call")(args); + return hexToBool(data ?? "0x0"); + } catch (error) { + try { + const verified = isAddressEqual(getAddress(address), await recoverAddress({ hash: hash2, signature })); + if (verified) + return true; + } catch { + } + if (error instanceof CallExecutionError) { + return false; + } + throw error; + } +} + +// node_modules/viem/_esm/actions/public/verifyMessage.js +async function verifyMessage(client, { address, message, factory, factoryData, signature, ...callRequest }) { + const hash2 = hashMessage(message); + return verifyHash(client, { + address, + factory, + factoryData, + hash: hash2, + signature, + ...callRequest + }); +} + +// node_modules/viem/_esm/actions/public/verifyTypedData.js +async function verifyTypedData(client, parameters) { + const { address, factory, factoryData, signature, message, primaryType, types, domain, ...callRequest } = parameters; + const hash2 = hashTypedData({ message, primaryType, types, domain }); + return verifyHash(client, { + address, + factory, + factoryData, + hash: hash2, + signature, + ...callRequest + }); +} + +// node_modules/viem/_esm/actions/public/waitForTransactionReceipt.js +init_transaction(); +init_withResolvers(); +init_stringify(); + +// node_modules/viem/_esm/actions/public/watchBlockNumber.js +init_fromHex(); +init_stringify(); +function watchBlockNumber(client, { emitOnBegin = false, emitMissed = false, onBlockNumber, onError, poll: poll_, pollingInterval = client.pollingInterval }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (client.transport.type === "webSocket") + return false; + if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + let prevBlockNumber; + const pollBlockNumber = () => { + const observerId = stringify([ + "watchBlockNumber", + client.uid, + emitOnBegin, + emitMissed, + pollingInterval + ]); + return observe(observerId, { onBlockNumber, onError }, (emit) => poll(async () => { + try { + const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({ cacheTime: 0 }); + if (prevBlockNumber) { + if (blockNumber === prevBlockNumber) + return; + if (blockNumber - prevBlockNumber > 1 && emitMissed) { + for (let i = prevBlockNumber + 1n; i < blockNumber; i++) { + emit.onBlockNumber(i, prevBlockNumber); + prevBlockNumber = i; + } + } + } + if (!prevBlockNumber || blockNumber > prevBlockNumber) { + emit.onBlockNumber(blockNumber, prevBlockNumber); + prevBlockNumber = blockNumber; + } + } catch (err) { + emit.onError?.(err); + } + }, { + emitOnBegin, + interval: pollingInterval + })); + }; + const subscribeBlockNumber = () => { + const observerId = stringify([ + "watchBlockNumber", + client.uid, + emitOnBegin, + emitMissed + ]); + return observe(observerId, { onBlockNumber, onError }, (emit) => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["newHeads"], + onData(data) { + if (!active) + return; + const blockNumber = hexToBigInt(data.result?.number); + emit.onBlockNumber(blockNumber, prevBlockNumber); + prevBlockNumber = blockNumber; + }, + onError(error) { + emit.onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }); + }; + return enablePolling ? pollBlockNumber() : subscribeBlockNumber(); +} + +// node_modules/viem/_esm/actions/public/waitForTransactionReceipt.js +async function waitForTransactionReceipt(client, { + confirmations = 1, + hash: hash2, + onReplaced, + pollingInterval = client.pollingInterval, + retryCount = 6, + retryDelay = ({ count }) => ~~(1 << count) * 200, + // exponential backoff + timeout = 18e4 +}) { + const observerId = stringify(["waitForTransactionReceipt", client.uid, hash2]); + let transaction; + let replacedTransaction; + let receipt; + let retrying = false; + const { promise, resolve, reject } = withResolvers(); + const timer = timeout ? setTimeout(() => reject(new WaitForTransactionReceiptTimeoutError({ hash: hash2 })), timeout) : void 0; + const _unobserve = observe(observerId, { onReplaced, resolve, reject }, (emit) => { + const _unwatch = getAction(client, watchBlockNumber, "watchBlockNumber")({ + emitMissed: true, + emitOnBegin: true, + poll: true, + pollingInterval, + async onBlockNumber(blockNumber_) { + const done = (fn2) => { + clearTimeout(timer); + _unwatch(); + fn2(); + _unobserve(); + }; + let blockNumber = blockNumber_; + if (retrying) + return; + try { + if (receipt) { + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + done(() => emit.resolve(receipt)); + return; + } + if (!transaction) { + retrying = true; + await withRetry(async () => { + transaction = await getAction(client, getTransaction, "getTransaction")({ hash: hash2 }); + if (transaction.blockNumber) + blockNumber = transaction.blockNumber; + }, { + delay: retryDelay, + retryCount + }); + retrying = false; + } + receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ hash: hash2 }); + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + done(() => emit.resolve(receipt)); + } catch (err) { + if (err instanceof TransactionNotFoundError || err instanceof TransactionReceiptNotFoundError) { + if (!transaction) { + retrying = false; + return; + } + try { + replacedTransaction = transaction; + retrying = true; + const block = await withRetry(() => getAction(client, getBlock, "getBlock")({ + blockNumber, + includeTransactions: true + }), { + delay: retryDelay, + retryCount, + shouldRetry: ({ error }) => error instanceof BlockNotFoundError + }); + retrying = false; + const replacementTransaction = block.transactions.find(({ from: from5, nonce }) => from5 === replacedTransaction.from && nonce === replacedTransaction.nonce); + if (!replacementTransaction) + return; + receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ + hash: replacementTransaction.hash + }); + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + let reason = "replaced"; + if (replacementTransaction.to === replacedTransaction.to && replacementTransaction.value === replacedTransaction.value && replacementTransaction.input === replacedTransaction.input) { + reason = "repriced"; + } else if (replacementTransaction.from === replacementTransaction.to && replacementTransaction.value === 0n) { + reason = "cancelled"; + } + done(() => { + emit.onReplaced?.({ + reason, + replacedTransaction, + transaction: replacementTransaction, + transactionReceipt: receipt + }); + emit.resolve(receipt); + }); + } catch (err_) { + done(() => emit.reject(err_)); + } + } else { + done(() => emit.reject(err)); + } + } + } + }); + }); + return promise; +} + +// node_modules/viem/_esm/actions/public/watchBlocks.js +init_stringify(); +function watchBlocks(client, { blockTag = "latest", emitMissed = false, emitOnBegin = false, onBlock, onError, includeTransactions: includeTransactions_, poll: poll_, pollingInterval = client.pollingInterval }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (client.transport.type === "webSocket") + return false; + if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + const includeTransactions = includeTransactions_ ?? false; + let prevBlock; + const pollBlocks = () => { + const observerId = stringify([ + "watchBlocks", + client.uid, + blockTag, + emitMissed, + emitOnBegin, + includeTransactions, + pollingInterval + ]); + return observe(observerId, { onBlock, onError }, (emit) => poll(async () => { + try { + const block = await getAction(client, getBlock, "getBlock")({ + blockTag, + includeTransactions + }); + if (block.number && prevBlock?.number) { + if (block.number === prevBlock.number) + return; + if (block.number - prevBlock.number > 1 && emitMissed) { + for (let i = prevBlock?.number + 1n; i < block.number; i++) { + const block2 = await getAction(client, getBlock, "getBlock")({ + blockNumber: i, + includeTransactions + }); + emit.onBlock(block2, prevBlock); + prevBlock = block2; + } + } + } + if ( + // If no previous block exists, emit. + !prevBlock?.number || // If the block tag is "pending" with no block number, emit. + blockTag === "pending" && !block?.number || // If the next block number is greater than the previous block number, emit. + // We don't want to emit blocks in the past. + block.number && block.number > prevBlock.number + ) { + emit.onBlock(block, prevBlock); + prevBlock = block; + } + } catch (err) { + emit.onError?.(err); + } + }, { + emitOnBegin, + interval: pollingInterval + })); + }; + const subscribeBlocks = () => { + let active = true; + let emitFetched = true; + let unsubscribe = () => active = false; + (async () => { + try { + if (emitOnBegin) { + getAction(client, getBlock, "getBlock")({ + blockTag, + includeTransactions + }).then((block) => { + if (!active) + return; + if (!emitFetched) + return; + onBlock(block, void 0); + emitFetched = false; + }); + } + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["newHeads"], + async onData(data) { + if (!active) + return; + const block = await getAction(client, getBlock, "getBlock")({ + blockNumber: data.blockNumber, + includeTransactions + }).catch(() => { + }); + if (!active) + return; + onBlock(block, prevBlock); + emitFetched = false; + prevBlock = block; + }, + onError(error) { + onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollBlocks() : subscribeBlocks(); +} + +// node_modules/viem/_esm/actions/public/watchEvent.js +init_stringify(); +init_abi(); +init_rpc(); +function watchEvent(client, { address, args, batch = true, event, events, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (typeof fromBlock === "bigint") + return true; + if (client.transport.type === "webSocket") + return false; + if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + const strict = strict_ ?? false; + const pollEvent = () => { + const observerId = stringify([ + "watchEvent", + address, + args, + batch, + client.uid, + event, + pollingInterval, + fromBlock + ]); + return observe(observerId, { onLogs, onError }, (emit) => { + let previousBlockNumber; + if (fromBlock !== void 0) + previousBlockNumber = fromBlock - 1n; + let filter2; + let initialized = false; + const unwatch = poll(async () => { + if (!initialized) { + try { + filter2 = await getAction(client, createEventFilter, "createEventFilter")({ + address, + args, + event, + events, + strict, + fromBlock + }); + } catch { + } + initialized = true; + return; + } + try { + let logs; + if (filter2) { + logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter: filter2 }); + } else { + const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({}); + if (previousBlockNumber && previousBlockNumber !== blockNumber) { + logs = await getAction(client, getLogs, "getLogs")({ + address, + args, + event, + events, + fromBlock: previousBlockNumber + 1n, + toBlock: blockNumber + }); + } else { + logs = []; + } + previousBlockNumber = blockNumber; + } + if (logs.length === 0) + return; + if (batch) + emit.onLogs(logs); + else + for (const log of logs) + emit.onLogs([log]); + } catch (err) { + if (filter2 && err instanceof InvalidInputRpcError) + initialized = false; + emit.onError?.(err); + } + }, { + emitOnBegin: true, + interval: pollingInterval + }); + return async () => { + if (filter2) + await getAction(client, uninstallFilter, "uninstallFilter")({ filter: filter2 }); + unwatch(); + }; + }); + }; + const subscribeEvent = () => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const events_ = events ?? (event ? [event] : void 0); + let topics = []; + if (events_) { + const encoded = events_.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["logs", { address, topics }], + onData(data) { + if (!active) + return; + const log = data.result; + try { + const { eventName, args: args2 } = decodeEventLog({ + abi: events_ ?? [], + data: log.data, + topics: log.topics, + strict + }); + const formatted = formatLog(log, { args: args2, eventName }); + onLogs([formatted]); + } catch (err) { + let eventName; + let isUnnamed; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict_) + return; + eventName = err.abiItem.name; + isUnnamed = err.abiItem.inputs?.some((x2) => !("name" in x2 && x2.name)); + } + const formatted = formatLog(log, { + args: isUnnamed ? [] : {}, + eventName + }); + onLogs([formatted]); + } + }, + onError(error) { + onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollEvent() : subscribeEvent(); +} + +// node_modules/viem/_esm/actions/public/watchPendingTransactions.js +init_stringify(); +function watchPendingTransactions(client, { batch = true, onError, onTransactions, poll: poll_, pollingInterval = client.pollingInterval }) { + const enablePolling = typeof poll_ !== "undefined" ? poll_ : client.transport.type !== "webSocket"; + const pollPendingTransactions = () => { + const observerId = stringify([ + "watchPendingTransactions", + client.uid, + batch, + pollingInterval + ]); + return observe(observerId, { onTransactions, onError }, (emit) => { + let filter2; + const unwatch = poll(async () => { + try { + if (!filter2) { + try { + filter2 = await getAction(client, createPendingTransactionFilter, "createPendingTransactionFilter")({}); + return; + } catch (err) { + unwatch(); + throw err; + } + } + const hashes = await getAction(client, getFilterChanges, "getFilterChanges")({ filter: filter2 }); + if (hashes.length === 0) + return; + if (batch) + emit.onTransactions(hashes); + else + for (const hash2 of hashes) + emit.onTransactions([hash2]); + } catch (err) { + emit.onError?.(err); + } + }, { + emitOnBegin: true, + interval: pollingInterval + }); + return async () => { + if (filter2) + await getAction(client, uninstallFilter, "uninstallFilter")({ filter: filter2 }); + unwatch(); + }; + }); + }; + const subscribePendingTransactions = () => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({ + params: ["newPendingTransactions"], + onData(data) { + if (!active) + return; + const transaction = data.result; + onTransactions([transaction]); + }, + onError(error) { + onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollPendingTransactions() : subscribePendingTransactions(); +} + +// node_modules/viem/_esm/utils/siwe/parseSiweMessage.js +function parseSiweMessage(message) { + const { scheme, statement, ...prefix } = message.match(prefixRegex)?.groups ?? {}; + const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = message.match(suffixRegex)?.groups ?? {}; + const resources = message.split("Resources:")[1]?.split("\n- ").slice(1); + return { + ...prefix, + ...suffix, + ...chainId ? { chainId: Number(chainId) } : {}, + ...expirationTime ? { expirationTime: new Date(expirationTime) } : {}, + ...issuedAt ? { issuedAt: new Date(issuedAt) } : {}, + ...notBefore ? { notBefore: new Date(notBefore) } : {}, + ...requestId ? { requestId } : {}, + ...resources ? { resources } : {}, + ...scheme ? { scheme } : {}, + ...statement ? { statement } : {} + }; +} +var prefixRegex = /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/; +var suffixRegex = /(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/; + +// node_modules/viem/_esm/utils/siwe/validateSiweMessage.js +init_isAddressEqual(); +function validateSiweMessage(parameters) { + const { address, domain, message, nonce, scheme, time = /* @__PURE__ */ new Date() } = parameters; + if (domain && message.domain !== domain) + return false; + if (nonce && message.nonce !== nonce) + return false; + if (scheme && message.scheme !== scheme) + return false; + if (message.expirationTime && time >= message.expirationTime) + return false; + if (message.notBefore && time < message.notBefore) + return false; + try { + if (!message.address) + return false; + if (address && !isAddressEqual(message.address, address)) + return false; + } catch { + return false; + } + return true; +} + +// node_modules/viem/_esm/actions/siwe/verifySiweMessage.js +async function verifySiweMessage(client, parameters) { + const { address, domain, message, nonce, scheme, signature, time = /* @__PURE__ */ new Date(), ...callRequest } = parameters; + const parsed = parseSiweMessage(message); + if (!parsed.address) + return false; + const isValid = validateSiweMessage({ + address, + domain, + message: parsed, + nonce, + scheme, + time + }); + if (!isValid) + return false; + const hash2 = hashMessage(message); + return verifyHash(client, { + address: parsed.address, + hash: hash2, + signature, + ...callRequest + }); +} + +// node_modules/viem/_esm/clients/decorators/public.js +function publicActions(client) { + return { + call: (args) => call(client, args), + createAccessList: (args) => createAccessList(client, args), + createBlockFilter: () => createBlockFilter(client), + createContractEventFilter: (args) => createContractEventFilter(client, args), + createEventFilter: (args) => createEventFilter(client, args), + createPendingTransactionFilter: () => createPendingTransactionFilter(client), + estimateContractGas: (args) => estimateContractGas(client, args), + estimateGas: (args) => estimateGas(client, args), + getBalance: (args) => getBalance(client, args), + getBlobBaseFee: () => getBlobBaseFee(client), + getBlock: (args) => getBlock(client, args), + getBlockNumber: (args) => getBlockNumber(client, args), + getBlockTransactionCount: (args) => getBlockTransactionCount(client, args), + getBytecode: (args) => getCode(client, args), + getChainId: () => getChainId(client), + getCode: (args) => getCode(client, args), + getContractEvents: (args) => getContractEvents(client, args), + getEip712Domain: (args) => getEip712Domain(client, args), + getEnsAddress: (args) => getEnsAddress(client, args), + getEnsAvatar: (args) => getEnsAvatar(client, args), + getEnsName: (args) => getEnsName(client, args), + getEnsResolver: (args) => getEnsResolver(client, args), + getEnsText: (args) => getEnsText(client, args), + getFeeHistory: (args) => getFeeHistory(client, args), + estimateFeesPerGas: (args) => estimateFeesPerGas(client, args), + getFilterChanges: (args) => getFilterChanges(client, args), + getFilterLogs: (args) => getFilterLogs(client, args), + getGasPrice: () => getGasPrice(client), + getLogs: (args) => getLogs(client, args), + getProof: (args) => getProof(client, args), + estimateMaxPriorityFeePerGas: (args) => estimateMaxPriorityFeePerGas(client, args), + getStorageAt: (args) => getStorageAt(client, args), + getTransaction: (args) => getTransaction(client, args), + getTransactionConfirmations: (args) => getTransactionConfirmations(client, args), + getTransactionCount: (args) => getTransactionCount(client, args), + getTransactionReceipt: (args) => getTransactionReceipt(client, args), + multicall: (args) => multicall(client, args), + prepareTransactionRequest: (args) => prepareTransactionRequest(client, args), + readContract: (args) => readContract(client, args), + sendRawTransaction: (args) => sendRawTransaction(client, args), + simulate: (args) => simulateBlocks(client, args), + simulateBlocks: (args) => simulateBlocks(client, args), + simulateCalls: (args) => simulateCalls(client, args), + simulateContract: (args) => simulateContract(client, args), + verifyMessage: (args) => verifyMessage(client, args), + verifySiweMessage: (args) => verifySiweMessage(client, args), + verifyTypedData: (args) => verifyTypedData(client, args), + uninstallFilter: (args) => uninstallFilter(client, args), + waitForTransactionReceipt: (args) => waitForTransactionReceipt(client, args), + watchBlocks: (args) => watchBlocks(client, args), + watchBlockNumber: (args) => watchBlockNumber(client, args), + watchContractEvent: (args) => watchContractEvent(client, args), + watchEvent: (args) => watchEvent(client, args), + watchPendingTransactions: (args) => watchPendingTransactions(client, args) + }; +} + +// node_modules/viem/_esm/clients/createPublicClient.js +function createPublicClient(parameters) { + const { key = "public", name = "Public Client" } = parameters; + const client = createClient({ + ...parameters, + key, + name, + type: "publicClient" + }); + return client.extend(publicActions); +} + +// node_modules/viem/_esm/actions/wallet/deployContract.js +init_encodeDeployData(); +function deployContract(walletClient, parameters) { + const { abi: abi4, args, bytecode, ...request } = parameters; + const calldata = encodeDeployData({ abi: abi4, args, bytecode }); + return sendTransaction(walletClient, { + ...request, + ...request.authorizationList ? { to: null } : {}, + data: calldata + }); +} + +// node_modules/viem/_esm/actions/wallet/getAddresses.js +init_getAddress(); +async function getAddresses(client) { + if (client.account?.type === "local") + return [client.account.address]; + const addresses = await client.request({ method: "eth_accounts" }, { dedupe: true }); + return addresses.map((address) => checksumAddress(address)); +} + +// node_modules/viem/_esm/actions/wallet/getPermissions.js +async function getPermissions(client) { + const permissions = await client.request({ method: "wallet_getPermissions" }, { dedupe: true }); + return permissions; +} + +// node_modules/viem/_esm/actions/wallet/prepareAuthorization.js +init_parseAccount(); +init_isAddressEqual(); +async function prepareAuthorization(client, parameters) { + const { account: account_ = client.account, chainId, nonce } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/eip7702/prepareAuthorization" + }); + const account = parseAccount(account_); + const executor = (() => { + if (!parameters.executor) + return void 0; + if (parameters.executor === "self") + return parameters.executor; + return parseAccount(parameters.executor); + })(); + const authorization = { + address: parameters.contractAddress ?? parameters.address, + chainId, + nonce + }; + if (typeof authorization.chainId === "undefined") + authorization.chainId = client.chain?.id ?? await getAction(client, getChainId, "getChainId")({}); + if (typeof authorization.nonce === "undefined") { + authorization.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({ + address: account.address, + blockTag: "pending" + }); + if (executor === "self" || executor?.address && isAddressEqual(executor.address, account.address)) + authorization.nonce += 1; + } + return authorization; +} + +// node_modules/viem/_esm/actions/wallet/requestAddresses.js +init_getAddress(); +async function requestAddresses(client) { + const addresses = await client.request({ method: "eth_requestAccounts" }, { dedupe: true, retryCount: 0 }); + return addresses.map((address) => getAddress(address)); +} + +// node_modules/viem/_esm/actions/wallet/requestPermissions.js +async function requestPermissions(client, permissions) { + return client.request({ + method: "wallet_requestPermissions", + params: [permissions] + }, { retryCount: 0 }); +} + +// node_modules/viem/_esm/actions/wallet/signAuthorization.js +init_parseAccount(); +async function signAuthorization(client, parameters) { + const { account: account_ = client.account } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/eip7702/signAuthorization" + }); + const account = parseAccount(account_); + if (!account.signAuthorization) + throw new AccountTypeNotSupportedError({ + docsPath: "/docs/eip7702/signAuthorization", + metaMessages: [ + "The `signAuthorization` Action does not support JSON-RPC Accounts." + ], + type: account.type + }); + const authorization = await prepareAuthorization(client, parameters); + return account.signAuthorization(authorization); +} + +// node_modules/viem/_esm/actions/wallet/signMessage.js +init_parseAccount(); +init_toHex(); +async function signMessage(client, { account: account_ = client.account, message }) { + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signMessage" + }); + const account = parseAccount(account_); + if (account.signMessage) + return account.signMessage({ message }); + const message_ = (() => { + if (typeof message === "string") + return stringToHex(message); + if (message.raw instanceof Uint8Array) + return toHex(message.raw); + return message.raw; + })(); + return client.request({ + method: "personal_sign", + params: [message_, account.address] + }, { retryCount: 0 }); +} + +// node_modules/viem/_esm/actions/wallet/signTransaction.js +init_parseAccount(); +init_toHex(); +init_transactionRequest(); +init_assertRequest(); +async function signTransaction(client, parameters) { + const { account: account_ = client.account, chain = client.chain, ...transaction } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signTransaction" + }); + const account = parseAccount(account_); + assertRequest({ + account, + ...parameters + }); + const chainId = await getAction(client, getChainId, "getChainId")({}); + if (chain !== null) + assertCurrentChain({ + currentChainId: chainId, + chain + }); + const formatters = chain?.formatters || client.chain?.formatters; + const format = formatters?.transactionRequest?.format || formatTransactionRequest; + if (account.signTransaction) + return account.signTransaction({ + ...transaction, + chainId + }, { serializer: client.chain?.serializers?.transaction }); + return await client.request({ + method: "eth_signTransaction", + params: [ + { + ...format(transaction), + chainId: numberToHex(chainId), + from: account.address + } + ] + }, { retryCount: 0 }); +} + +// node_modules/viem/_esm/actions/wallet/signTypedData.js +init_parseAccount(); +async function signTypedData(client, parameters) { + const { account: account_ = client.account, domain, message, primaryType } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signTypedData" + }); + const account = parseAccount(account_); + const types = { + EIP712Domain: getTypesForEIP712Domain({ domain }), + ...parameters.types + }; + validateTypedData({ domain, message, primaryType, types }); + if (account.signTypedData) + return account.signTypedData({ domain, message, primaryType, types }); + const typedData = serializeTypedData({ domain, message, primaryType, types }); + return client.request({ + method: "eth_signTypedData_v4", + params: [account.address, typedData] + }, { retryCount: 0 }); +} + +// node_modules/viem/_esm/actions/wallet/switchChain.js +init_toHex(); +async function switchChain(client, { id: id2 }) { + await client.request({ + method: "wallet_switchEthereumChain", + params: [ + { + chainId: numberToHex(id2) + } + ] + }, { retryCount: 0 }); +} + +// node_modules/viem/_esm/actions/wallet/watchAsset.js +async function watchAsset(client, params) { + const added = await client.request({ + method: "wallet_watchAsset", + params + }, { retryCount: 0 }); + return added; +} + +// node_modules/viem/_esm/clients/decorators/wallet.js +function walletActions(client) { + return { + addChain: (args) => addChain(client, args), + deployContract: (args) => deployContract(client, args), + getAddresses: () => getAddresses(client), + getChainId: () => getChainId(client), + getPermissions: () => getPermissions(client), + prepareAuthorization: (args) => prepareAuthorization(client, args), + prepareTransactionRequest: (args) => prepareTransactionRequest(client, args), + requestAddresses: () => requestAddresses(client), + requestPermissions: (args) => requestPermissions(client, args), + sendRawTransaction: (args) => sendRawTransaction(client, args), + sendTransaction: (args) => sendTransaction(client, args), + signAuthorization: (args) => signAuthorization(client, args), + signMessage: (args) => signMessage(client, args), + signTransaction: (args) => signTransaction(client, args), + signTypedData: (args) => signTypedData(client, args), + switchChain: (args) => switchChain(client, args), + watchAsset: (args) => watchAsset(client, args), + writeContract: (args) => writeContract(client, args) + }; +} + +// node_modules/viem/_esm/clients/createWalletClient.js +function createWalletClient(parameters) { + const { key = "wallet", name = "Wallet Client", transport } = parameters; + const client = createClient({ + ...parameters, + key, + name, + transport, + type: "walletClient" + }); + return client.extend(walletActions); +} + +// node_modules/viem/_esm/index.js +init_abi(); +init_contract(); +init_rpc(); +init_node(); +init_request(); +init_transaction(); +init_decodeAbiParameters(); +init_encodeAbiParameters(); +init_getAbiItem(); +init_toBytes(); +init_formatUnits(); +init_isHex(); +init_keccak256(); + +// src/common/utils/callContract.ts +async function executeTransaction(publicClient, walletClient, params, nonceManager) { + const chainId = publicClient.chain.id; + const address = walletClient.account.address; + let txHash; + if (globalConfig.VIEM.SIMULATE_TX) { + const { request } = await publicClient.simulateContract(params); + txHash = await walletClient.writeContract({ request }); + } else { + const nonce = await nonceManager.consume({ + address, + chainId, + client: publicClient + }); + const paramsToSend = { + gas: globalConfig.TX_MANAGER.GAS_LIMIT.DEFAULT, + ...params, + nonce + }; + txHash = await walletClient.writeContract(paramsToSend); + } + await publicClient.waitForTransactionReceipt({ + hash: txHash + }); + return txHash; +} +async function callContract(publicClient, walletClient, params) { + try { + const nonceManager = NonceManager.getInstance(); + const isRetryableError = async (error) => { + if (error instanceof ContractFunctionExecutionError && error.cause instanceof TransactionExecutionError && (error.cause.cause instanceof NonceTooHighError || error.cause.cause instanceof NonceTooLowError) || error instanceof TransactionNotFoundError || error instanceof WaitForTransactionReceiptTimeoutError) { + const chainId = publicClient.chain.id; + const address = walletClient.account.address; + nonceManager.reset({ chainId, address }); + return true; + } + return false; + }; + return asyncRetry( + () => executeTransaction(publicClient, walletClient, params, nonceManager), + { + maxRetries: 20, + delayMs: 1e3, + isRetryableError + } + ); + } catch (error) { + throw new AppError("ContractCallError" /* ContractCallError */, error); + } +} + +// src/common/utils/checkGas.ts +var import_web_api = __toESM(require_dist4(), 1); +var SAFE_TXS_COUNT_FOR_OPERATOR_BALANCE = 15n; +async function notifyInSlack(message) { + try { + if (!globalConfig.NOTIFICATIONS.SLACK.MONITORING_SYSTEM_CHANNEL_ID || !globalConfig.NOTIFICATIONS.SLACK.BOT_TOKEN) { + return; + } + const webClient = new import_web_api.WebClient(globalConfig.NOTIFICATIONS.SLACK.BOT_TOKEN); + const res = await webClient.chat.postMessage({ + channel: globalConfig.NOTIFICATIONS.SLACK.MONITORING_SYSTEM_CHANNEL_ID, + text: message + }); + if (!res.ok) { + console.error(`Failed to send message to slack: ${res.error}`); + } + } catch (error) { + console.error(JSON.stringify(error, null, 2)); + } +} +async function getChainOperatorMinBalance(publicClient) { + const currentGasPrice = await publicClient.getGasPrice(); + const averageTxCostInWei = currentGasPrice * globalConfig.TX_MANAGER.GAS_LIMIT.DEFAULT; + return averageTxCostInWei * SAFE_TXS_COUNT_FOR_OPERATOR_BALANCE; +} +async function checkAndNotifyInsufficientGas() { + const operatorAddress = globalConfig.OPERATOR_ADDRESS; + const viemClientManager = ViemClientManager.getInstance(); + const networkManager = NetworkManager.getInstance(); + const logger = Logger.getInstance().getLogger("GasChecker"); + try { + const activeNetworks = networkManager.getActiveNetworks(); + if (activeNetworks.length === 0) { + logger.warn("No active networks found when checking gas balances"); + return; + } + const balancePromises = activeNetworks.map(async (network) => { + const { publicClient } = viemClientManager.getClients(network); + const [balance, operatorMinBalance] = await Promise.all([ + publicClient.getBalance({ + address: operatorAddress + }), + getChainOperatorMinBalance(publicClient) + ]); + return { network, balance, operatorMinBalance }; + }); + const chainsInfo = await Promise.all(balancePromises); + for (const chainInfo of chainsInfo) { + const { balance, operatorMinBalance, network } = chainInfo; + if (balance < operatorMinBalance) { + const message = `Insufficient gas on ${network.name} (chain ID: ${network.id}). Minimum required: ${formatUnits(operatorMinBalance, 18)}, actual: ${formatUnits(balance, 18)}`; + await notifyInSlack(message); + logger.info(message); + } + } + } catch (error) { + logger.error("Error checking gas balances:", error); + } +} +async function checkGas() { + await checkAndNotifyInsufficientGas(); + setInterval(async () => { + await checkAndNotifyInsufficientGas(); + }, globalConfig.NOTIFICATIONS.INTERVAL); +} + +// src/common/utils/createViemChain.ts +function createViemChain(chainDefinition) { + return defineChain({ + id: chainDefinition.id, + name: chainDefinition.name, + nativeCurrency: { + decimals: 18, + name: "eth", + symbol: "eth" + }, + rpcUrls: { + default: { http: chainDefinition.rpcUrls } + }, + blockExplorers: chainDefinition.blockExplorer ? { + default: { + name: chainDefinition.blockExplorer.name, + url: chainDefinition.blockExplorer.url + } + } : void 0, + testnet: chainDefinition.isTestnet + }); +} + +// src/common/utils/customHttpTransport.ts +function createCustomHttpTransport(url2) { + const logger = Logger.getInstance().getLogger("ViemTransport"); + return (config3) => { + const transport = http2(url2, { + batch: true + })(config3); + return transport; + }; +} + +// src/common/utils/decoders/decodeCLFReport.ts +var clfReportSubmissionAbi = parseAbiParameters([ + "bytes32[3] reportContext", + "bytes report", + "bytes32[] rs", + "bytes32[] ss", + "bytes32 rawVs" +]); +var clfReportAbi = parseAbiParameters([ + "bytes32[] requestIds", + "bytes[] results", + "bytes[] errors", + "bytes[] onchainMetadata", + "bytes[] offchainMetadata" +]); +function decodeCLFReport(tx) { + const inputData = tx.input.slice(10); + const decodedData = decodeAbiParameters(clfReportSubmissionAbi, `0x${inputData}`); + const reportBytes = decodedData[1]; + const decodedReport = decodeAbiParameters(clfReportAbi, reportBytes); + const report = { + reportContext: decodedData[0], + report: { + requestIds: decodedReport[0], + results: decodedReport[1], + errors: decodedReport[2], + onchainMetadata: decodedReport[3], + offchainMetadata: decodedReport[4] + }, + rs: decodedData[2], + ss: decodedData[3], + rawVs: decodedData[4], + reportBytes + }; + return report; +} + +// src/common/utils/decoders/decodeMessageReportResult.ts +function decodeMessageReportResult(resultBytes) { + try { + const decodedClfResult = decodeAbiParameters( + [ + { + type: "tuple", + name: "reportConfig", + components: [ + { type: "uint8", name: "type" }, + { type: "uint8", name: "payloadVersion" }, + { type: "address", name: "requester" } + ] + }, + { type: "bytes", name: "payload" } + ], + resultBytes + ); + const decodedPayload = decodeAbiParameters( + [ + { + type: "tuple", + components: [ + { type: "bytes32", name: "messageId" }, + { type: "bytes32", name: "messageHashSum" }, + { type: "bytes", name: "messageSender" }, + { type: "uint24", name: "srcChainSelector" }, + { type: "uint24", name: "dstChainSelector" }, + { type: "uint256", name: "srcBlockNumber" }, + { + type: "tuple", + name: "dstChainData", + components: [ + { type: "address", name: "receiver" }, + { type: "uint256", name: "gasLimit" } + ] + }, + { type: "bytes[]", name: "allowedOperators" } + ] + } + ], + hexToBytes(decodedClfResult[1]) + ); + return { + reportConfig: decodedClfResult[0], + ...decodedPayload[0] + }; + } catch (error) { + console.error("Error decoding CLF message report response:", error); + throw new Error("Failed to decode CLF message report response"); + } +} + +// src/common/utils/fetchNetworkConfigs.ts +async function fetchNetworkConfigs() { + const httpClient = HttpClient.getQueueInstance(); + try { + const [mainnetSummary, testnetSummary] = await Promise.all([ + httpClient.get(globalConfig.URLS.V2_NETWORKS.MAINNET_SUMMARY), + httpClient.get(globalConfig.URLS.V2_NETWORKS.TESTNET_SUMMARY) + ]); + const mainnetDetailPromises = Object.keys(mainnetSummary).map(async (networkName) => { + const url2 = `${globalConfig.URLS.V2_NETWORKS.MAINNET_DETAIL_BASE}/${networkName}.json`; + const response = await httpClient.get(url2); + const details = await response; + return { networkName, details }; + }); + const testnetDetailPromises = Object.keys(testnetSummary).map(async (networkName) => { + const url2 = `${globalConfig.URLS.V2_NETWORKS.TESTNET_DETAIL_BASE}/${networkName}.json`; + const response = await httpClient.get(url2); + const details = await response; + return { networkName, details }; + }); + const mainnetDetails = await Promise.all(mainnetDetailPromises); + const testnetDetails = await Promise.all(testnetDetailPromises); + const processedMainnetNetworks = mainnetDetails.reduce((acc, { networkName, details }) => { + const chainDefinition = { + id: details.chainId, + name: details.name, + rpcUrls: details.rpcs, + blockExplorer: details.blockExplorers[0] ? { + name: details.blockExplorers[0].name, + url: details.blockExplorers[0].url + } : void 0, + isTestnet: false + }; + acc[networkName] = { + name: details.name, + chainId: details.chainId, + chainSelector: details.chainSelector.toString(), + viemChain: createViemChain(chainDefinition) + }; + return acc; + }, {}); + const processedTestnetNetworks = testnetDetails.reduce((acc, { networkName, details }) => { + const chainDefinition = { + id: details.chainId, + name: details.name, + rpcUrls: details.rpcs, + blockExplorer: details.blockExplorers[0] ? { + name: details.blockExplorers[0].name, + url: details.blockExplorers[0].url + } : void 0, + isTestnet: true + }; + acc[networkName] = { + name: details.name, + chainId: details.chainId, + chainSelector: details.chainSelector.toString(), + viemChain: createViemChain(chainDefinition) + }; + return acc; + }, {}); + return { + mainnetNetworks: processedMainnetNetworks, + testnetNetworks: processedTestnetNetworks + }; + } catch (error) { + console.error("Failed to fetch network configurations:", error); + return { mainnetNetworks: {}, testnetNetworks: {} }; + } +} + +// src/common/utils/getEnvVar.ts +import process2 from "process"; +function getEnvVar(key) { + const value = process2.env[key]; + if (value === void 0 || value === "") throw new Error(`Missing environment variable ${key}`); + return value; +} + +// src/common/utils/getGranularLogLevels.ts +import process3 from "process"; +function getGranularLogLevels() { + const logLevels = {}; + const LOG_LEVEL_PREFIX = "LOG_LEVEL_"; + Object.keys(process3.env).forEach((key) => { + if (key.startsWith(LOG_LEVEL_PREFIX) && key !== "LOG_LEVEL_DEFAULT") { + const componentName = key.substring(LOG_LEVEL_PREFIX.length); + const level = process3.env[key]; + if (componentName && level) { + logLevels[componentName] = level; + console.log( + `[getGranularLogLevels] Component-specific log level: ${componentName}=${level}` + ); + } + } + }); + return logLevels; +} + +// src/common/utils/getOptionalEnvVar.ts +function getOptionalEnvVar(key, defaultValue) { + const value = process.env[key]; + return value !== void 0 && value !== "" ? value : defaultValue; +} + +// src/common/utils/localhostViemChain.ts +var localhostViemChain = defineChain({ + id: 1, + name: "localhost", + nativeCurrency: { + decimals: 18, + name: "eth", + symbol: "eth" + }, + rpcUrls: { + default: { http: [process.env.LOCALHOST_RPC_URL] } + }, + blockExplorers: [ + { + name: "localhost", + url: process.env.LOCALHOST_RPC_URL + } + ], + testnet: true +}); + +// src/constants/localRpcLoaders.ts +function getRpcOverride() { + try { + return __require("../../rpcs.override.json"); + } catch { + return {}; + } +} +function getRpcExtension() { + try { + return __require("../../rpcs.extension.json"); + } catch { + return {}; + } +} + +// src/constants/globalConfig.ts +var globalConfig = { + NETWORK_MODE: getEnvVar("NETWORK_MODE"), + OPERATOR_ADDRESS: getEnvVar("OPERATOR_ADDRESS"), + IGNORED_NETWORK_IDS: [], + WHITELISTED_NETWORK_IDS: { + mainnet: [], + testnet: [], + localhost: [ + /* 1 */ + ] + }, + LOGGER: { + LOG_LEVEL_DEFAULT: getOptionalEnvVar("LOG_LEVEL_DEFAULT", "info"), + LOG_LEVELS_GRANULAR: getGranularLogLevels(), + LOG_DIR: "logs", + LOG_MAX_FILES: "7d", + LOG_MAX_SIZE: "20m" + }, + URLS: { + CONCERO_RPCS: `https://raw.githubusercontent.com/concero/rpcs/refs/heads/${process.env.RPC_SERVICE_GIT_BRANCH ?? "master"}/output/`, + CONCERO_DEPLOYMENTS: `https://raw.githubusercontent.com/concero/v2-contracts/refs/heads/${process.env.DEPLOYMENTS_SERVICE_GIT_BRANCH ?? "master"}/.env.deployments.${getEnvVar("NETWORK_MODE") === "localhost" || getEnvVar("NETWORK_MODE") === "testnet" ? "testnet" : "mainnet"}`, + V2_NETWORKS: { + MAINNET_SUMMARY: "https://github.com/concero/v2-networks/raw/refs/heads/master/networks/mainnet.json", + TESTNET_SUMMARY: "https://github.com/concero/v2-networks/raw/refs/heads/master/networks/testnet.json", + MAINNET_DETAIL_BASE: "https://github.com/concero/v2-networks/raw/refs/heads/master/networks/mainnet", + TESTNET_DETAIL_BASE: "https://github.com/concero/v2-networks/raw/refs/heads/master/networks/testnet" + } + }, + VIEM: { + RECEIPT: {}, + WRITE_CONTRACT: {}, + FALLBACK_TRANSPORT_OPTIONS: { + retryCount: 5, + retryDelay: 2e3 + }, + SIMULATE_TX: getEnvVar("SIMULATE_TX") === "true" + }, + HTTPCLIENT: { + DEFAULT_TIMEOUT: 5e3, + MAX_RETRIES: 3, + RETRY_DELAY: 1e3 + }, + ABI: { + CONCERO_VERIFIER: abi2, + CONCERO_ROUTER: abi, + EVM_DST_CHAIN_DATA: { + components: [ + { + internalType: "address", + name: "receiver", + type: "address" + }, + { + internalType: "uint256", + name: "gasLimit", + type: "uint256" + } + ], + internalType: "struct ConceroTypes.EvmDstChainData", + name: "dstChainData", + type: "tuple" + } + }, + RPC: { + OVERRIDE: getRpcOverride(), + EXTENSION: getRpcExtension() + }, + TX_MANAGER: { + DRY_RUN: getEnvVar("DRY_RUN") === "true", + DEFAULT_CONFIRMATIONS: 3, + DEFAULT_RECEIPT_TIMEOUT: 6e4, + GAS_LIMIT: { + DEFAULT: 2000000n, + SUBMIT_MESSAGE_REPORT_OVERHEAD: 1000000n + } + }, + NETWORK_MANAGER: { + NETWORK_UPDATE_INTERVAL_MS: 1e3 * 60 * 60 + // 1 hour + }, + BLOCK_MANAGER: { + POLLING_INTERVAL_MS: parseInt(getEnvVar("BLOCK_MANAGER_POLLING_INTERVAL_MS")) || 5e3, + SEQUENTIAL_BATCH_SIZE: 100n, + CATCHUP_BATCH_SIZE: 500n, + MAX_BLOCKS_TO_PROCESS: 100n, + USE_CHECKPOINTS: getEnvVar("USE_CHECKPOINTS") === "true" + }, + NOTIFICATIONS: { + SLACK: { + MONITORING_SYSTEM_CHANNEL_ID: process.env.SLACK_MONITORING_SYSTEM_CHANNEL_ID, + BOT_TOKEN: process.env.SLACK_BOT_TOKEN + }, + INTERVAL: 60 * 60 * 1e3 + } +}; + +// src/common/utils/httpClient.ts +var { RETRY_DELAY, MAX_RETRIES, DEFAULT_TIMEOUT } = globalConfig.HTTPCLIENT; +var HttpClient = class _HttpClient extends ManagerBase { + static defaultInstance; + static queueInstance; + axiosInstance; + logger; + requestQueue = []; + activeRequests = 0; + maxConcurrentRequests; + constructor(maxConcurrentRequests) { + super(); + this.maxConcurrentRequests = maxConcurrentRequests; + this.logger = Logger.getInstance().getLogger("HttpClient"); + } + static createInstance(maxConcurrentRequests) { + return new _HttpClient(maxConcurrentRequests); + } + static getInstance() { + if (!_HttpClient.defaultInstance) { + _HttpClient.defaultInstance = new _HttpClient(); + } + return _HttpClient.defaultInstance; + } + static getQueueInstance() { + if (!_HttpClient.queueInstance) { + _HttpClient.queueInstance = new _HttpClient(2); + } + return _HttpClient.queueInstance; + } + async initialize() { + if (this.initialized) { + return; + } + try { + await this.setupAxiosInstance(); + await super.initialize(); + } catch (error) { + throw error; + } + } + async setupAxiosInstance() { + this.axiosInstance = axios_default.create({ + timeout: DEFAULT_TIMEOUT + }); + this.axiosInstance.interceptors.response.use( + (response) => response, + async (error) => { + const config3 = error.config; + const logger = this.logger; + if (config3 && config3.__retryCount < MAX_RETRIES) { + config3.__retryCount = config3.__retryCount || 0; + config3.__retryCount += 1; + logger.warn( + `Retrying request to ${config3.url}. Attempt ${config3.__retryCount} of ${MAX_RETRIES}. Error: ${error.message}` + ); + await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY)); + return this.axiosInstance(config3); + } + logger.error( + `Request to ${config3?.url} failed after ${config3?.__retryCount || 0} attempts. Error: ${error.message}` + ); + throw new AppError("FailedHTTPRequest" /* FailedHTTPRequest */, error); + } + ); + } + dispose() { + this.requestQueue = []; + this.activeRequests = 0; + this.axiosInstance = void 0; + super.dispose(); + } + static disposeInstances() { + if (_HttpClient.defaultInstance) { + _HttpClient.defaultInstance.dispose(); + _HttpClient.defaultInstance = void 0; + } + if (_HttpClient.queueInstance) { + _HttpClient.queueInstance.dispose(); + _HttpClient.queueInstance = void 0; + } + } + async processQueue() { + if ((this.maxConcurrentRequests === void 0 || this.activeRequests < this.maxConcurrentRequests) && this.requestQueue.length > 0) { + const nextRequest = this.requestQueue.shift(); + if (nextRequest) { + this.activeRequests++; + try { + await nextRequest(); + } finally { + this.activeRequests--; + this.processQueue(); + } + } + } + } + enqueueRequest(requestFn) { + this.requestQueue.push(requestFn); + this.processQueue(); + } + async request(method, url2, config3 = {}, body) { + if (!this.initialized || !this.axiosInstance) { + throw new AppError( + "FailedHTTPRequest" /* FailedHTTPRequest */, + new Error("HttpClient not initialized") + ); + } + return new Promise((resolve, reject) => { + const executeRequest = async () => { + try { + this.logger.debug( + `${method} request to ${url2} with config: ${JSON.stringify(config3)} ${body ? `and body: ${JSON.stringify(body)}` : ""}` + ); + const response = await this.axiosInstance.request({ + method, + url: url2, + data: body, + ...config3 + }); + resolve(response.data); + } catch (error) { + this.logger.error(`Request failed for ${url2} with error:`, error); + reject(new AppError("FailedHTTPRequest" /* FailedHTTPRequest */, error)); + } + }; + this.enqueueRequest(executeRequest); + }); + } + async get(url2, config3 = {}) { + return this.request("GET", url2, config3); + } + async post(url2, body, config3 = {}) { + return this.request("POST", url2, config3, body); + } +}; + +// src/common/utils/initializeManagers.ts +async function initializeManagers() { + const logger = Logger.createInstance(); + await logger.initialize(); + const httpClient = HttpClient.getInstance(); + const httpQueue = HttpClient.getQueueInstance(); + httpClient.initialize(); + httpQueue.initialize(); + const rpcManager = RpcManager.createInstance(); + const viemClientManager = ViemClientManager.createInstance(rpcManager); + const deploymentManager = DeploymentManager.createInstance(); + const networkManager = NetworkManager.createInstance(rpcManager, deploymentManager); + const blockCheckpointManager = BlockCheckpointManager.createInstance(); + const blockManagerRegistry = BlockManagerRegistry.createInstance( + blockCheckpointManager, + networkManager, + viemClientManager, + rpcManager + ); + await rpcManager.initialize(); + await viemClientManager.initialize(); + await deploymentManager.initialize(); + await networkManager.initialize(); + await blockCheckpointManager.initialize(); + await blockManagerRegistry.initialize(); + const txWriter = TxWriter.createInstance(networkManager, viemClientManager); + const txReader = TxReader.createInstance( + networkManager, + viemClientManager, + blockManagerRegistry + ); + await txWriter.initialize(); + await txReader.initialize(); + const txMonitor = TxMonitor.createInstance( + viemClientManager, + (txHash, chainName) => txWriter.onTxFinality(txHash, chainName), + (txHash, chainName) => txWriter.onTxReorg(txHash, chainName) + ); + const txManager = TxManager.createInstance( + networkManager, + viemClientManager, + blockManagerRegistry, + txWriter, + txReader, + txMonitor + ); + await txManager.initialize(); + const nonceManager = NonceManager.createInstance(); + await nonceManager.initialize(); +} + +// src/common/managers/DbManager.ts +var import_client = __toESM(require_default2(), 1); +var DbManager = class _DbManager { + static instance = null; + constructor() { + } + static getClient() { + if (!_DbManager.instance) { + _DbManager.instance = new import_client.PrismaClient(); + } + return _DbManager.instance; + } + static async disconnect() { + if (_DbManager.instance) { + await _DbManager.instance.$disconnect(); + _DbManager.instance = null; + } + } +}; + +// src/common/managers/BlockCheckpointManager.ts +var BlockCheckpointManager = class _BlockCheckpointManager extends ManagerBase { + static instance; + prisma = DbManager.getClient(); + logger; + constructor() { + super(); + this.logger = Logger.getInstance().getLogger("BlockCheckpointManager"); + } + static createInstance() { + _BlockCheckpointManager.instance = new _BlockCheckpointManager(); + return _BlockCheckpointManager.instance; + } + static getInstance() { + if (!_BlockCheckpointManager.instance) { + throw new Error( + "BlockCheckpointManager is not initialized. Call createInstance() first." + ); + } + return _BlockCheckpointManager.instance; + } + async getCheckpoint(network) { + const checkpoint = await this.prisma.blockCheckpoint.findUnique({ + where: { network: network.name } + }); + if (checkpoint) { + this.logger.debug( + `Found checkpoint at block ${checkpoint} for network ${network.name}` + ); + return BigInt(checkpoint.blockNumber.toString()); + } else { + this.logger.debug(`No checkpoint found for network ${network.name}`); + } + } + async updateLastProcessedBlock(networkName, blockNumber) { + if (!globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS) return; + try { + await this.prisma.blockCheckpoint.upsert({ + where: { network: networkName }, + update: { blockNumber }, + create: { + network: networkName, + blockNumber + } + }); + } catch (error) { + this.logger.error( + `Upsert failed for network: ${networkName}, blockNumber: ${blockNumber.toString()}`, + error + ); + throw error; + } + } + async initialize() { + if (this.initialized) return; + await super.initialize(); + this.logger.debug("Initialized"); + } + dispose() { + super.dispose(); + this.logger.debug("Disposed"); + } +}; + +// src/common/managers/BlockManager.ts +var BlockManager = class _BlockManager { + lastProcessedBlockNumber; + latestBlock = null; + publicClient; + network; + blockCheckpointManager; + blockRangeHandlers = /* @__PURE__ */ new Map(); + logger; + isDisposed = false; + isPolling = false; + pollingIntervalMs = globalConfig.BLOCK_MANAGER.POLLING_INTERVAL_MS; + pollingTimeout = null; + constructor(initialBlock, network, publicClient, blockCheckpointManager) { + this.lastProcessedBlockNumber = initialBlock; + this.publicClient = publicClient; + this.network = network; + this.blockCheckpointManager = blockCheckpointManager; + this.logger = Logger.getInstance().getLogger("BlockManager"); + } + static async create(network, publicClient, blockCheckpointManager) { + let initialBlock; + const staticLogger = Logger.getInstance().getLogger("BlockManager"); + if (!globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS) { + initialBlock = await publicClient.getBlockNumber(); + staticLogger.debug( + `${network.name}: Checkpoints disabled. Starting from current chain tip: ${initialBlock}` + ); + } else { + const savedBlock = await blockCheckpointManager.getCheckpoint(network); + if (savedBlock !== void 0) { + staticLogger.info( + `${network.name}: Resuming from previously saved block ${savedBlock}` + ); + initialBlock = savedBlock; + } else { + initialBlock = await publicClient.getBlockNumber(); + staticLogger.debug( + `${network.name}: No checkpoint found. Starting from current chain tip: ${initialBlock}` + ); + } + } + staticLogger.debug( + `${network.name}: Creating new instance with initial block ${initialBlock}` + ); + const blockManager = new _BlockManager( + initialBlock, + network, + publicClient, + blockCheckpointManager + ); + return blockManager; + } + async startPolling() { + if (this.isPolling) { + this.logger.debug(`${this.network.name}: Already polling, ignoring start request`); + return; + } + this.isPolling = true; + await this.performCatchup(); + await this.poll(); + } + stopPolling() { + if (!this.isPolling) { + return; + } + this.logger.info(`${this.network.name}: Stopping block polling`); + this.isPolling = false; + if (this.pollingTimeout) { + clearTimeout(this.pollingTimeout); + this.pollingTimeout = null; + } + } + async poll() { + if (!this.isPolling || this.isDisposed) { + return; + } + try { + this.latestBlock = await this.publicClient.getBlockNumber(); + if (this.latestBlock > this.lastProcessedBlockNumber) { + const startBlock = this.lastProcessedBlockNumber + 1n; + await this.processBlockRange(startBlock, this.latestBlock); + } + } catch (error) { + this.logger.error(`${this.network.name}: Error in poll cycle:`, error); + } finally { + if (this.isPolling && !this.isDisposed) { + this.pollingTimeout = setTimeout(() => this.poll(), this.pollingIntervalMs); + } + } + } + async getLatestBlock() { + return this.latestBlock; + } + /** + * Process a range of blocks by: + * 1. Notifying all registered handlers about the new block range + * 2. Updating the last processed block checkpoint + */ + async processBlockRange(startBlock, endBlock) { + this.logger.debug( + `${this.network.name}: Processing ${this.latestBlock - startBlock + 1n} new blocks from ${startBlock} to ${this.latestBlock}` + ); + if (this.blockRangeHandlers.size > 0) { + for (const handler of this.blockRangeHandlers.values()) { + try { + await handler.onBlockRange(startBlock, endBlock); + } catch (error) { + this.logger.error( + `${this.network.name}: Error in block range handler ${handler.id}:`, + error + ); + if (handler.onError) { + handler.onError(error); + } + } + } + } + await this.updateLastProcessedBlock(endBlock); + } + /** + * Update the last processed block checkpoint + */ + async updateLastProcessedBlock(blockNumber) { + await this.blockCheckpointManager.updateLastProcessedBlock(this.network.name, blockNumber); + this.lastProcessedBlockNumber = blockNumber; + } + /** + * Initiates a catchup process from the current processed block to the latest block. + * This is typically called during initialization. + */ + async performCatchup() { + if (this.isDisposed) { + this.logger.debug(`${this.network.name}: Already disposed, skipping catchup`); + return; + } + try { + this.latestBlock = await this.publicClient.getBlockNumber(); + let currentBlock = this.lastProcessedBlockNumber; + this.logger.debug( + `${this.network.name}: Starting catchup from block ${currentBlock}, Chain tip: ${this.latestBlock}` + ); + while (currentBlock < this.latestBlock && !this.isDisposed) { + const startBlock = currentBlock + 1n; + const endBlock = startBlock + globalConfig.BLOCK_MANAGER.CATCHUP_BATCH_SIZE - 1n > this.latestBlock ? this.latestBlock : startBlock + globalConfig.BLOCK_MANAGER.CATCHUP_BATCH_SIZE - 1n; + await this.processBlockRange(startBlock, endBlock); + currentBlock = endBlock; + } + } catch (err) { + this.logger.error(`${this.network.name}:`, err); + } + } + /** + * Registers a handler that will be called when new blocks are processed. + * Returns an unregister function. + */ + watchBlocks(options) { + const { onBlockRange, onError } = options; + const handlerId = Math.random().toString(36).substring(2, 15); + this.blockRangeHandlers.set(handlerId, { + id: handlerId, + onBlockRange, + onError + }); + return () => { + this.logger.info(`${this.network.name}: Unregistered block range handler ${handlerId}`); + this.blockRangeHandlers.delete(handlerId); + }; + } + dispose() { + this.isDisposed = true; + this.stopPolling(); + this.blockRangeHandlers.clear(); + this.logger.debug(`${this.network.name}: Disposed`); + } +}; + +// src/common/managers/BlockManagerRegistry.ts +var BlockManagerRegistry = class _BlockManagerRegistry extends ManagerBase { + static instance; + blockManagers = /* @__PURE__ */ new Map(); + blockCheckpointManager; + networkManager; + viemClientManager; + rpcManager; + logger; + constructor(blockCheckpointManager, networkManager, viemClientManager, rpcManager) { + super(); + this.blockCheckpointManager = blockCheckpointManager; + this.networkManager = networkManager; + this.viemClientManager = viemClientManager; + this.rpcManager = rpcManager; + this.logger = Logger.getInstance().getLogger("BlockManagerRegistry"); + } + onNetworksUpdated(networks) { + this.logger.info(`Networks updated, syncing BlockManagers for ${networks.length} networks`); + this.updateBlockManagers(networks).catch((error) => { + this.logger.error("Failed to sync BlockManagers after network update", error); + }); + } + async ensureBlockManagerForNetwork(network) { + if (this.blockManagers.has(network.name)) { + this.logger.debug(`Using existing BlockManager for network ${network.name}`); + return this.blockManagers.get(network.name); + } + try { + await this.rpcManager.ensureRpcsForNetwork(network); + const { publicClient } = this.viemClientManager.getClients(network); + const blockManager = await this.createBlockManager(network, publicClient); + return blockManager; + } catch (error) { + this.logger.warn(`Failed to create BlockManager for network ${network.name}`, error); + } + } + async updateBlockManagers(networks) { + if (!this.initialized) return; + this.logger.info(`Syncing BlockManagers for ${networks.length} active networks`); + const currentNetworkNames = new Set(this.blockManagers.keys()); + const newNetworkNames = new Set(networks.map((network) => network.name)); + for (const networkName of currentNetworkNames) { + if (!newNetworkNames.has(networkName)) { + this.logger.info(`Removing BlockManager for inactive network ${networkName}`); + const blockManager = this.blockManagers.get(networkName); + if (blockManager && "dispose" in blockManager) { + blockManager.dispose(); + } + this.blockManagers.delete(networkName); + } + } + const newNetworks = networks.filter((network) => !currentNetworkNames.has(network.name)); + if (newNetworks.length > 0) { + this.logger.debug(`Creating ${newNetworks.length} new BlockManagers in parallel`); + const results = await Promise.all( + newNetworks.map((network) => this.ensureBlockManagerForNetwork(network)) + ); + } + } + //TODO: attempt to refactor createInstance to a base class + static createInstance(blockCheckpointManager, networkManager, viemClientManager, rpcManager) { + _BlockManagerRegistry.instance = new _BlockManagerRegistry( + blockCheckpointManager, + networkManager, + viemClientManager, + rpcManager + ); + return _BlockManagerRegistry.instance; + } + static getInstance() { + if (!_BlockManagerRegistry.instance) { + throw new Error( + "BlockManagerRegistry is not initialized. Call createInstance() first." + ); + } + return _BlockManagerRegistry.instance; + } + async initialize() { + if (this.initialized) return; + try { + this.networkManager.registerUpdateListener(this); + await super.initialize(); + this.logger.debug("Initialized"); + const activeNetworks = this.networkManager.getActiveNetworks(); + this.logger.debug(`Starting initial sync for ${activeNetworks.length} networks`); + await this.updateBlockManagers(activeNetworks); + } catch (error) { + this.logger.error("Failed to initialize", error); + throw error; + } + } + async createBlockManager(network, publicClient) { + if (this.blockManagers.has(network.name)) { + return this.blockManagers.get(network.name); + } + const blockManager = await BlockManager.create( + network, + publicClient, + this.blockCheckpointManager + ); + this.blockManagers.set(network.name, blockManager); + this.logger.debug(`Created BlockManager for network ${network.name}`); + return blockManager; + } + getBlockManager(networkName) { + if (this.blockManagers.has(networkName)) { + return this.blockManagers.get(networkName); + } + this.logger.warn(`BlockManager for ${networkName} not found`); + return null; + } + getAllBlockManagers() { + return Array.from(this.blockManagers.values()); + } + getAllManagedNetworks() { + return Array.from(this.blockManagers.keys()); + } + async getLatestBlockForChain(networkName) { + const blockManager = this.getBlockManager(networkName); + if (!blockManager) { + this.logger.error(`BlockManager for ${networkName} not found`); + return null; + } + return blockManager.getLatestBlock(); + } + dispose() { + if (this.initialized) { + this.networkManager.unregisterUpdateListener(this); + for (const [networkName, blockManager] of this.blockManagers.entries()) { + if ("dispose" in blockManager) { + blockManager.dispose(); + } + this.logger.debug(`Disposed BlockManager for ${networkName}`); + } + this.blockManagers.clear(); + super.dispose(); + this.logger.debug("Disposed"); + } + } +}; + +// src/common/managers/DeploymentManager.ts +var DeploymentManager = class _DeploymentManager extends ManagerBase { + static instance; + conceroRoutersMapByChainName = {}; + conceroVerifier; + httpClient; + logger; + constructor() { + super(); + this.httpClient = HttpClient.getQueueInstance(); + this.logger = Logger.getInstance().getLogger("DeploymentManager"); + } + static createInstance() { + _DeploymentManager.instance = new _DeploymentManager(); + return _DeploymentManager.instance; + } + static getInstance() { + if (!_DeploymentManager.instance) { + throw new Error("DeploymentManager is not initialized. Call createInstance() first."); + } + return _DeploymentManager.instance; + } + async initialize() { + if (this.initialized) return; + try { + await super.initialize(); + this.logger.debug("Initialized"); + } catch (error) { + this.logger.error("Failed to initialize:", error); + throw error; + } + } + async getRouterByChainName(chainName) { + if (this.isLocalhostEnv()) { + return getEnvVar("CONCERO_ROUTER_PROXY_LOCALHOST"); + } + const router = this.conceroRoutersMapByChainName[chainName]; + if (router !== void 0) return router; + await this.updateDeployments(); + const updatedRouter = this.conceroRoutersMapByChainName[chainName]; + if (!updatedRouter) { + throw new Error(`Router not found for chain: ${chainName}`); + } + return updatedRouter; + } + async getConceroRouters() { + if (this.isLocalhostEnv()) { + return { + [getEnvVar("LOCALHOST_FORK_CHAIN_ID")]: getEnvVar( + "CONCERO_ROUTER_PROXY_LOCALHOST" + ) + }; + } + const routers = this.conceroRoutersMapByChainName; + return routers; + } + async getConceroVerifier() { + if (this.isLocalhostEnv()) { + return getEnvVar("CONCERO_VERIFIER_PROXY_LOCALHOST"); + } + if (this.conceroVerifier !== void 0) return this.conceroVerifier; + await this.updateDeployments(); + if (!this.conceroVerifier) { + throw new Error("Concero verifier address not found after update"); + } + return this.conceroVerifier; + } + async updateDeployments() { + const now = Date.now(); + try { + const deployments = await this.httpClient.get(globalConfig.URLS.CONCERO_DEPLOYMENTS, { + responseType: "text" + // Ensure Axios returns raw text + }); + const deploymentsEnvArr = deployments.split("\n"); + const conceroRouterDeploymentsEnv = deploymentsEnvArr.filter( + (d) => d.startsWith("CONCERO_ROUTER_PROXY") && !d.startsWith("CONCERO_ROUTER_PROXY_ADMIN") + ); + const routerMap = {}; + for (const deploymentEnv of conceroRouterDeploymentsEnv) { + const [name, address] = deploymentEnv.split("="); + const networkName = this.extractNetworkName(name); + if (networkName) { + routerMap[networkName] = address; + } + } + this.conceroRoutersMapByChainName = routerMap; + const verifierEntry = deploymentsEnvArr.find((d) => { + const networkSuffix = globalConfig.NETWORK_MODE === "testnet" ? "ARBITRUM_SEPOLIA" : "ARBITRUM"; + return d.startsWith(`CONCERO_VERIFIER_PROXY_${networkSuffix}`); + }); + if (verifierEntry) { + this.conceroVerifier = verifierEntry.split("=")[1]; + } + this.lastUpdateTime = now; + this.logger.debug("Deployments updated"); + } catch (error) { + this.logger.error("Failed to update deployments:", error); + throw new Error( + `Failed to update deployments: ${error instanceof Error ? error.message : String(error)}` + ); + } + } + onNetworksUpdated() { + this.updateDeployments().catch( + (err) => this.logger.error("Failed to update deployments after network update:", err) + ); + } + extractNetworkName(key) { + const prefix = "CONCERO_ROUTER_PROXY_"; + const parts = key.slice(prefix.length).toLowerCase().split("_"); + return parts[0] + parts.slice(1).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(""); + } + isLocalhostEnv() { + return globalConfig.NETWORK_MODE === "localhost"; + } + dispose() { + super.dispose(); + this.logger.debug("Disposed"); + } +}; + +// src/common/managers/NetworkManager.ts +var NetworkManager = class _NetworkManager extends ManagerBase { + static instance; + mainnetNetworks = {}; + testnetNetworks = {}; + allNetworks = {}; + activeNetworks = []; + updateIntervalId = null; + rpcManager = null; + deploymentsManager = null; + updateListeners = []; + logger; + constructor(rpcManager, deploymentsManager) { + super(); + this.rpcManager = rpcManager || null; + this.deploymentsManager = deploymentsManager || null; + this.logger = Logger.getInstance().getLogger("NetworkManager"); + if (this.rpcManager && "onNetworksUpdated" in this.rpcManager) { + this.registerUpdateListener(this.rpcManager); + } + if (this.deploymentsManager && "onNetworksUpdated" in this.deploymentsManager) { + this.registerUpdateListener(this.deploymentsManager); + } + } + static getInstance() { + return _NetworkManager.instance; + } + static createInstance(rpcManager, deploymentsManager) { + this.instance = new _NetworkManager(rpcManager, deploymentsManager); + return this.instance; + } + async initialize() { + if (this.initialized) return; + try { + await this.updateNetworks(); + this.setupUpdateCycle(); + this.initialized = true; + this.logger.debug("Initialized"); + } catch (error) { + this.logger.error("Failed to initialize networks:", error); + throw error; + } + } + registerUpdateListener(listener) { + const existingIndex = this.updateListeners.findIndex( + (existing) => existing.constructor.name === listener.constructor.name + ); + if (existingIndex === -1) { + this.updateListeners.push(listener); + } else { + this.logger.warn(`Update listener already registered: ${listener.constructor.name}`); + } + } + unregisterUpdateListener(listener) { + const index2 = this.updateListeners.indexOf(listener); + if (index2 !== -1) { + this.updateListeners.splice(index2, 1); + } + } + getMainnetNetworks() { + return { ...this.mainnetNetworks }; + } + getTestnetNetworks() { + return { ...this.testnetNetworks }; + } + getAllNetworks() { + return { ...this.allNetworks }; + } + getActiveNetworks() { + return [...this.activeNetworks]; + } + getNetworkById(chainId) { + const network = Object.values(this.allNetworks).find((network2) => network2.id === chainId); + if (!network) { + throw new Error(`Network with chain ID ${chainId} not found`); + } + return network; + } + getNetworkByName(name) { + const network = Object.values(this.allNetworks).find((network2) => network2.name === name); + if (!network) { + throw new Error(`Network with name "${name}" not found`); + } + return network; + } + getNetworkBySelector(selector) { + const network = Object.values(this.allNetworks).find( + (network2) => network2.chainSelector === selector + ); + if (!network) { + throw new Error(`Network with selector "${selector}" not found`); + } + return network; + } + getVerifierNetwork() { + if (globalConfig.NETWORK_MODE === "mainnet") { + return this.mainnetNetworks["arbitrum"]; + } else if (globalConfig.NETWORK_MODE === "testnet") { + return this.testnetNetworks["arbitrumSepolia"]; + } else if (globalConfig.NETWORK_MODE === "localhost") { + const localNetwork = this.testnetNetworks["localhost"]; + if (!localNetwork) { + this.logger.error( + `Available testnet networks: ${Object.keys(this.testnetNetworks).join(", ")}` + ); + throw new Error("Localhost network not found in testnetNetworks"); + } + this.logger.debug( + `Using localhost network: ${localNetwork.name} (id: ${localNetwork.id})` + ); + return localNetwork; + } else { + throw new Error(`Unsupported network mode: ${globalConfig.NETWORK_MODE}`); + } + } + async forceUpdate() { + await this.updateNetworks(); + } + setupUpdateCycle() { + if (this.updateIntervalId) { + clearInterval(this.updateIntervalId); + } + this.updateIntervalId = setInterval( + () => this.updateNetworks().catch( + (err) => this.logger.error("Network update failed:", err) + ), + globalConfig.NETWORK_MANAGER.NETWORK_UPDATE_INTERVAL_MS + ); + } + async updateNetworks() { + try { + const operatorPK = getEnvVar("OPERATOR_PRIVATE_KEY"); + if (globalConfig.NETWORK_MODE === "localhost") { + this.mainnetNetworks = {}; + const localhostNetworks = this.getTestingNetworks(operatorPK); + this.testnetNetworks = localhostNetworks; + this.logger.debug( + `Using localhost networks only: ${Object.keys(localhostNetworks).join(", ")}` + ); + } else { + const { mainnetNetworks: fetchedMainnet, testnetNetworks: fetchedTestnet } = await fetchNetworkConfigs(); + this.mainnetNetworks = this.createNetworkConfig(fetchedMainnet, "mainnet", [ + operatorPK + ]); + this.testnetNetworks = { + ...this.createNetworkConfig(fetchedTestnet, "testnet", [operatorPK]) + }; + } + this.allNetworks = { ...this.testnetNetworks, ...this.mainnetNetworks }; + this.activeNetworks = this.filterNetworks( + globalConfig.NETWORK_MODE + ); + this.logger.debug( + `Networks updated - Active networks: ${this.activeNetworks.length} (${this.activeNetworks.map((n) => n.name).join(", ")})` + ); + this.notifyListeners(); + } catch (error) { + this.logger.error("Failed to update networks:", error); + throw error; + } + } + notifyListeners() { + for (const listener of this.updateListeners) { + try { + listener.onNetworksUpdated(this.activeNetworks); + } catch (error) { + this.logger.error("Error in network update listener:", error); + } + } + } + createNetworkConfig(networks, networkType, accounts) { + return Object.fromEntries( + Object.entries(networks).map(([key, network]) => { + const networkKey = key; + return [ + networkKey, + { + name: network.name || networkKey, + type: networkType, + id: network.chainId, + accounts, + chainSelector: network.chainSelector || network.chainId.toString(), + confirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS, + viemChain: network.viemChain + } + ]; + }) + ); + } + getTestingNetworks(operatorPK) { + return { + localhost: { + name: "localhost", + type: "localhost", + id: 1, + accounts: [operatorPK], + chainSelector: "1", + confirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS, + viemChain: localhostViemChain + } + }; + } + filterNetworks(networkType) { + let networks = []; + const ignoredIds = globalConfig.IGNORED_NETWORK_IDS || []; + const whitelistedIds = globalConfig.WHITELISTED_NETWORK_IDS[networkType] || []; + switch (networkType) { + case "localhost": + networks = Object.values( + this.getTestingNetworks(getEnvVar("OPERATOR_PRIVATE_KEY")) + ); + break; + case "testnet": + networks = Object.values(this.testnetNetworks); + break; + case "mainnet": + networks = Object.values(this.mainnetNetworks); + break; + } + networks = networks.filter((network) => !ignoredIds.includes(network.id)); + if (whitelistedIds.length > 0) { + networks = networks.filter((network) => whitelistedIds.includes(network.id)); + } + return networks; + } + dispose() { + if (this.updateIntervalId) { + clearInterval(this.updateIntervalId); + this.updateIntervalId = null; + } + this.updateListeners = []; + super.dispose(); + } +}; + +// node_modules/async-mutex/index.mjs +var E_TIMEOUT = new Error("timeout while waiting for mutex to become available"); +var E_ALREADY_LOCKED = new Error("mutex already locked"); +var E_CANCELED = new Error("request for lock canceled"); +var __awaiter$2 = function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var Semaphore = class { + constructor(_value, _cancelError = E_CANCELED) { + this._value = _value; + this._cancelError = _cancelError; + this._queue = []; + this._weightedWaiters = []; + } + acquire(weight = 1, priority = 0) { + if (weight <= 0) + throw new Error(`invalid weight ${weight}: must be positive`); + return new Promise((resolve, reject) => { + const task = { resolve, reject, weight, priority }; + const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority); + if (i === -1 && weight <= this._value) { + this._dispatchItem(task); + } else { + this._queue.splice(i + 1, 0, task); + } + }); + } + runExclusive(callback_1) { + return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) { + const [value, release] = yield this.acquire(weight, priority); + try { + return yield callback(value); + } finally { + release(); + } + }); + } + waitForUnlock(weight = 1, priority = 0) { + if (weight <= 0) + throw new Error(`invalid weight ${weight}: must be positive`); + if (this._couldLockImmediately(weight, priority)) { + return Promise.resolve(); + } else { + return new Promise((resolve) => { + if (!this._weightedWaiters[weight - 1]) + this._weightedWaiters[weight - 1] = []; + insertSorted(this._weightedWaiters[weight - 1], { resolve, priority }); + }); + } + } + isLocked() { + return this._value <= 0; + } + getValue() { + return this._value; + } + setValue(value) { + this._value = value; + this._dispatchQueue(); + } + release(weight = 1) { + if (weight <= 0) + throw new Error(`invalid weight ${weight}: must be positive`); + this._value += weight; + this._dispatchQueue(); + } + cancel() { + this._queue.forEach((entry) => entry.reject(this._cancelError)); + this._queue = []; + } + _dispatchQueue() { + this._drainUnlockWaiters(); + while (this._queue.length > 0 && this._queue[0].weight <= this._value) { + this._dispatchItem(this._queue.shift()); + this._drainUnlockWaiters(); + } + } + _dispatchItem(item) { + const previousValue = this._value; + this._value -= item.weight; + item.resolve([previousValue, this._newReleaser(item.weight)]); + } + _newReleaser(weight) { + let called = false; + return () => { + if (called) + return; + called = true; + this.release(weight); + }; + } + _drainUnlockWaiters() { + if (this._queue.length === 0) { + for (let weight = this._value; weight > 0; weight--) { + const waiters = this._weightedWaiters[weight - 1]; + if (!waiters) + continue; + waiters.forEach((waiter) => waiter.resolve()); + this._weightedWaiters[weight - 1] = []; + } + } else { + const queuedPriority = this._queue[0].priority; + for (let weight = this._value; weight > 0; weight--) { + const waiters = this._weightedWaiters[weight - 1]; + if (!waiters) + continue; + const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority); + (i === -1 ? waiters : waiters.splice(0, i)).forEach((waiter) => waiter.resolve()); + } + } + } + _couldLockImmediately(weight, priority) { + return (this._queue.length === 0 || this._queue[0].priority < priority) && weight <= this._value; + } +}; +function insertSorted(a, v) { + const i = findIndexFromEnd(a, (other) => v.priority <= other.priority); + a.splice(i + 1, 0, v); +} +function findIndexFromEnd(a, predicate) { + for (let i = a.length - 1; i >= 0; i--) { + if (predicate(a[i])) { + return i; + } + } + return -1; +} +var __awaiter$1 = function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var Mutex = class { + constructor(cancelError) { + this._semaphore = new Semaphore(1, cancelError); + } + acquire() { + return __awaiter$1(this, arguments, void 0, function* (priority = 0) { + const [, releaser] = yield this._semaphore.acquire(1, priority); + return releaser; + }); + } + runExclusive(callback, priority = 0) { + return this._semaphore.runExclusive(() => callback(), 1, priority); + } + isLocked() { + return this._semaphore.isLocked(); + } + waitForUnlock(priority = 0) { + return this._semaphore.waitForUnlock(1, priority); + } + release() { + if (this._semaphore.isLocked()) + this._semaphore.release(); + } + cancel() { + return this._semaphore.cancel(); + } +}; + +// src/common/managers/NonceManager.ts +var NonceManager = class _NonceManager extends ManagerBase { + static instance = null; + noncesMap = {}; + mutexMap = {}; + constructor() { + super(); + } + static createInstance() { + if (!_NonceManager.instance) { + _NonceManager.instance = new _NonceManager(); + } + return _NonceManager.instance; + } + static getInstance() { + if (!_NonceManager.instance) { + throw new Error( + "NonceManager instance has not been created. Call createInstance() first." + ); + } + return _NonceManager.instance; + } + static dispose() { + _NonceManager.instance = null; + } + async get(params) { + const m2 = this.getMutex(params.chainId); + return m2.runExclusive(async () => { + if (!this.noncesMap[params.chainId]) { + const actualNonce = await this.fetchNonce(params); + this.set(params, actualNonce); + return actualNonce; + } + return this.noncesMap[params.chainId]; + }); + } + async consume(params) { + const m2 = this.getMutex(params.chainId); + return m2.runExclusive(async () => { + const nonce = this.noncesMap[params.chainId] ? this.noncesMap[params.chainId] : await this.fetchNonce(params); + this.set(params, nonce + 1); + return nonce; + }); + } + reset(params) { + this.set(params, 0); + } + set(params, nonce) { + this.noncesMap[params.chainId] = nonce; + } + async fetchNonce(params) { + const publicClient = this.createPublicCLientFromGetNonceParams(params); + return await publicClient.getTransactionCount({ address: params.address }); + } + getMutex(chainId) { + if (!this.mutexMap[chainId]) { + this.mutexMap[chainId] = new Mutex(); + } + return this.mutexMap[chainId]; + } + createPublicCLientFromGetNonceParams(params) { + return createPublicClient({ + transport: () => params.client.transport, + chain: params.client.chain + }); + } +}; + +// src/common/managers/RpcManager.ts +var RpcManager = class _RpcManager extends ManagerBase { + static instance; + httpClient; + logger; + constructor() { + super(); + this.httpClient = HttpClient.getQueueInstance(); + this.logger = Logger.getInstance().getLogger("RpcManager"); + } + static createInstance() { + _RpcManager.instance = new _RpcManager(); + return _RpcManager.instance; + } + rpcUrls = {}; + lastUpdateTime = {}; + rpcUpdateListeners = []; + static getInstance() { + if (!_RpcManager.instance) { + throw new Error("RpcManager is not initialized. Call createInstance() first."); + } + return _RpcManager.instance; + } + async initialize() { + if (this.initialized) return; + await super.initialize(); + this.logger.debug("Initialized"); + } + registerRpcUpdateListener(listener) { + if (!this.rpcUpdateListeners.includes(listener)) { + this.rpcUpdateListeners.push(listener); + } + } + unregisterRpcUpdateListener(listener) { + const index2 = this.rpcUpdateListeners.indexOf(listener); + if (index2 !== -1) { + this.rpcUpdateListeners.splice(index2, 1); + } + } + async ensureRpcsForNetwork(network) { + const now = Date.now(); + const lastUpdate = this.lastUpdateTime[network.name] || 0; + if (!this.rpcUrls[network.name] || this.rpcUrls[network.name].length === 0) { + await this.updateRpcsForNetwork(network); + } + } + async fetchRpcUrls(chainId, chainName, chainType) { + try { + const rpcOverride = globalConfig.RPC.OVERRIDE[chainId.toString()]; + if (rpcOverride && rpcOverride.length) return rpcOverride; + if (chainType === "localhost") { + const localhostUrl = process.env.LOCALHOST_RPC_URL; + if (!localhostUrl) { + throw new Error("LOCALHOST_RPC_URL environment variable is not set"); + } + return [localhostUrl]; + } + const url2 = `${globalConfig.URLS.CONCERO_RPCS}${chainType}/${chainId}-${chainName}.json`; + const chainConfig = await this.httpClient.get(url2); + const response = await chainConfig; + const urls = response.urls; + const rpcsExtension = globalConfig.RPC.EXTENSION[chainId.toString()]; + if (rpcsExtension) { + rpcsExtension.forEach((url3) => { + urls.push(url3); + }); + } + if (!urls) { + throw new Error(`Invalid RPC URL response format for chain ${chainName}`); + } + return urls; + } catch (error) { + this.logger.error(`Error fetching RPC URLs for ${chainName}:`, error); + throw error; + } + } + async updateRpcsForNetworks(networks) { + const updatePromises = []; + const updatedNetworks = []; + for (const network of networks) { + updatePromises.push( + this.updateRpcsForNetwork(network).then(() => { + updatedNetworks.push(network); + }).catch((error) => { + this.logger.error( + `Failed to update RPC for network ${network.name}:`, + error + ); + }) + ); + } + await Promise.allSettled(updatePromises); + if (updatedNetworks.length > 0) { + this.notifyRpcUpdateListeners(updatedNetworks); + } + this.logger.debug( + `Updated RPC URLs for ${updatedNetworks.map((network) => network.name).join(", ")}: ${updatedNetworks.length} networks updated` + ); + } + async updateRpcsForNetwork(network) { + try { + const urls = await this.fetchRpcUrls(network.id, network.name, network.type); + if (urls.length > 0) { + const previousUrls = this.rpcUrls[network.name] || []; + this.rpcUrls[network.name] = urls; + this.lastUpdateTime[network.name] = Date.now(); + if (JSON.stringify(previousUrls) !== JSON.stringify(urls)) { + this.notifyRpcUpdateListeners([network]); + } + } else { + this.logger.warn(`No RPC URLs found for chain ${network.name}`); + this.rpcUrls[network.name] = []; + } + } catch (error) { + this.logger.error(`Failed to update RPC URLs for chain ${network.name}:`, error); + this.rpcUrls[network.name] = this.rpcUrls[network.name] || []; + throw error; + } + } + notifyRpcUpdateListeners(networks) { + for (const listener of this.rpcUpdateListeners) { + try { + listener.onRpcUrlsUpdated(networks); + } catch (error) { + this.logger.error("Error in RPC update listener:", error); + } + } + } + getRpcsForNetwork(networkName) { + return this.rpcUrls[networkName] || []; + } + onNetworksUpdated(networks) { + this.updateRpcsForNetworks(networks).catch( + (err) => this.logger.error("Failed to update RPCs after network update:", err) + ); + } +}; + +// src/common/managers/TxManager.ts +var TxManager = class _TxManager extends ManagerBase { + static instance; + txWriter; + txReader; + txMonitor; + networkManager; + viemClientManager; + blockManagerRegistry; + logger; + constructor(networkManager, viemClientManager, blockManagerRegistry, txWriter, txReader, txMonitor) { + super(); + this.networkManager = networkManager; + this.viemClientManager = viemClientManager; + this.blockManagerRegistry = blockManagerRegistry; + this.txWriter = txWriter; + this.txReader = txReader; + this.txMonitor = txMonitor; + this.logger = Logger.getInstance().getLogger("TxManager"); + } + static createInstance(networkManager, viemClientManager, blockManagerRegistry, txWriter, txReader, txMonitor) { + if (!_TxManager.instance) { + _TxManager.instance = new _TxManager( + networkManager, + viemClientManager, + blockManagerRegistry, + txWriter, + txReader, + txMonitor + ); + } + return _TxManager.instance; + } + static getInstance() { + if (!_TxManager.instance) { + throw new Error("TxManager is not initialized. Call createInstance() first."); + } + return _TxManager.instance; + } + async initialize() { + super.initialize(); + this.logger.info("initialized"); + } + async callContract(walletClient, publicClient, network, params) { + const managedTx = await this.txWriter.callContract( + walletClient, + publicClient, + network, + params + ); + this.txMonitor.addTransaction(managedTx.txHash, managedTx); + return managedTx; + } + // Transaction Monitoring Methods + async onTxReorg(txHash, chainName) { + return this.txWriter.onTxReorg(txHash, chainName); + } + onTxFinality(txHash, chainName) { + this.txWriter.onTxFinality(txHash, chainName); + } + // Log Reading Methods + async getLogs(query, network) { + return this.txReader.getLogs(query, network); + } + logWatcher = { + create: (contractAddress, chainName, onLogs, event) => { + return this.txReader.logWatcher.create(contractAddress, chainName, onLogs, event); + }, + remove: (watcherId) => { + return this.txReader.logWatcher.remove(watcherId); + } + }; + // Transaction status methods + getPendingTransactions(chainName) { + return this.txWriter.getPendingTransactions(chainName); + } + getTransactionsByMessageId(messageId) { + return this.txWriter.getTransactionsByMessageId(messageId); + } + dispose() { + this.txWriter.dispose(); + this.txReader.dispose(); + this.txMonitor.dispose(); + this.logger.info("disposed"); + } +}; + +// src/common/managers/TxMonitor.ts +var TxMonitor = class _TxMonitor { + static instance; + transactions = /* @__PURE__ */ new Map(); + viemClientManager; + disposed = false; + txFinalityCallback; + txReorgCallback; + logger; + constructor(viemClientManager, txFinalityCallback, txReorgCallback) { + this.viemClientManager = viemClientManager; + this.txFinalityCallback = txFinalityCallback; + this.txReorgCallback = txReorgCallback; + this.logger = Logger.getInstance().getLogger("TxMonitor"); + this.logger.info("initialized"); + } + static createInstance(viemClientManager, txFinalityCallback, txReorgCallback) { + _TxMonitor.instance = new _TxMonitor(viemClientManager, txFinalityCallback, txReorgCallback); + return _TxMonitor.instance; + } + static getInstance() { + if (!_TxMonitor.instance) { + throw new Error("TxMonitor is not initialized. Call createInstance() first."); + } + return _TxMonitor.instance; + } + addTransaction(txHash, managedTx) { + if (this.transactions.has(txHash)) { + this.logger.debug(`Transaction ${txHash} is already being monitored`); + return; + } + if (managedTx.txHash !== txHash) { + this.logger.error(`Transaction hash mismatch: ${txHash} vs ${managedTx.txHash}`); + return; + } + const monitoredTx = { + txHash, + chainName: managedTx.chainName, + messageId: managedTx.messageId, + blockNumber: managedTx.submissionBlock, + firstSeen: Date.now(), + lastChecked: Date.now(), + status: "pending" /* Pending */, + managedTxId: managedTx.id + }; + this.transactions.set(txHash, monitoredTx); + this.logger.debug( + `Started monitoring tx ${txHash} on ${managedTx.chainName}` + (managedTx.messageId ? ` for message ${managedTx.messageId}` : "") + ); + } + async checkTransactionsInRange(network, startBlock, endBlock) { + if (this.disposed) return; + const finalityConfirmations = network.finalityConfirmations ?? 12; + const finalityBlockNumber = endBlock - BigInt(finalityConfirmations); + const txsToCheck = Array.from(this.transactions.values()).filter( + (tx) => tx.chainName === network.name && tx.status === "pending" /* Pending */ && tx.blockNumber !== null && tx.blockNumber <= finalityBlockNumber + ); + if (txsToCheck.length === 0) return; + this.logger.debug( + `Checking ${txsToCheck.length} transactions for finality on ${network.name} at block ${endBlock}` + ); + for (const tx of txsToCheck) { + await this.checkTransaction(tx, finalityBlockNumber, network); + } + } + async checkTransaction(tx, finalityBlockNumber, network) { + if (!tx.blockNumber) return; + if (tx.blockNumber > finalityBlockNumber) { + return; + } + try { + const { publicClient } = this.viemClientManager.getClients(network); + const txInfo = await publicClient.getTransaction({ hash: tx.txHash }); + if (!txInfo) { + await this.handleMissingTransaction(tx, network); + return; + } + if (txInfo.blockNumber && tx.blockNumber !== txInfo.blockNumber) { + this.logger.info( + `Transaction ${tx.txHash} block number changed from ${tx.blockNumber} to ${txInfo.blockNumber} (potential reorg)` + ); + tx.blockNumber = txInfo.blockNumber; + if (txInfo.blockNumber > finalityBlockNumber) { + tx.lastChecked = Date.now(); + return; + } + } + tx.status = "finalized" /* Finalized */; + this.txFinalityCallback(tx.txHash, tx.chainName); + if (tx.messageId) { + await this.finalizeMessageTransactions(tx.messageId); + } + this.transactions.delete(tx.txHash); + this.logger.info(`Transaction ${tx.txHash} has reached finality on ${network.name}`); + tx.lastChecked = Date.now(); + } catch (error) { + this.logger.error(`Error checking transaction ${tx.txHash}:`, error); + } + } + async handleMissingTransaction(tx, network) { + tx.status = "reorged" /* Reorged */; + this.logger.info( + `Transaction ${tx.txHash} not found on chain ${network.name}, potential reorg` + ); + const newTxHash = await this.txReorgCallback(tx.txHash, tx.chainName); + if (newTxHash) { + this.transactions.delete(tx.txHash); + this.logger.info(`Transaction ${tx.txHash} replaced with ${newTxHash}`); + } else { + tx.status = "dropped" /* Dropped */; + this.logger.warn(`Failed to resubmit transaction ${tx.txHash} after reorg`); + } + } + async finalizeMessageTransactions(messageId) { + const relatedTxs = Array.from(this.transactions.values()).filter( + (tx) => tx.messageId === messageId + ); + for (const tx of relatedTxs) { + if (tx.status === "pending" /* Pending */) { + this.logger.info( + `Finalizing related transaction ${tx.txHash} for message ${messageId}` + ); + tx.status = "finalized" /* Finalized */; + this.txFinalityCallback(tx.txHash, tx.chainName); + this.transactions.delete(tx.txHash); + } + } + } + getMonitoredTransactions(chainName) { + if (chainName) { + return Array.from(this.transactions.values()).filter((tx) => tx.chainName === chainName); + } + return Array.from(this.transactions.values()); + } + getTransactionsByMessageId() { + const result = /* @__PURE__ */ new Map(); + for (const tx of this.transactions.values()) { + if (!tx.messageId) continue; + const existing = result.get(tx.messageId) || []; + existing.push(tx); + result.set(tx.messageId, existing); + } + return result; + } + dispose() { + this.disposed = true; + this.transactions.clear(); + this.logger.info("Disposed"); + } +}; + +// node_modules/uuid/dist/esm/stringify.js +var byteToHex = []; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 256).toString(16).slice(1)); +} +function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); +} + +// node_modules/uuid/dist/esm/rng.js +import { randomFillSync } from "crypto"; +var rnds8Pool = new Uint8Array(256); +var poolPtr = rnds8Pool.length; +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + randomFillSync(rnds8Pool); + poolPtr = 0; + } + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} + +// node_modules/uuid/dist/esm/native.js +import { randomUUID } from "crypto"; +var native_default = { randomUUID }; + +// node_modules/uuid/dist/esm/v4.js +function v4(options, buf, offset) { + if (native_default.randomUUID && !buf && !options) { + return native_default.randomUUID(); + } + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? rng(); + if (rnds.length < 16) { + throw new Error("Random bytes length must be >= 16"); + } + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return unsafeStringify(rnds); +} +var v4_default = v4; + +// src/common/managers/TxReader.ts +var TxReader = class _TxReader { + static instance; + logWatchers = /* @__PURE__ */ new Map(); + cachedLogs = /* @__PURE__ */ new Map(); + blockManagerUnwatchers = /* @__PURE__ */ new Map(); + logger; + networkManager; + viemClientManager; + blockManagerRegistry; + constructor(networkManager, viemClientManager, blockManagerRegistry) { + this.networkManager = networkManager; + this.viemClientManager = viemClientManager; + this.blockManagerRegistry = blockManagerRegistry; + this.logger = Logger.getInstance().getLogger("TxReader"); + } + static createInstance(networkManager, viemClientManager, blockManagerRegistry) { + _TxReader.instance = new _TxReader(networkManager, viemClientManager, blockManagerRegistry); + return _TxReader.instance; + } + static getInstance() { + if (!_TxReader.instance) { + throw new Error("TxReader is not initialized. Call createInstance() first."); + } + return _TxReader.instance; + } + async initialize() { + await this.subscribeToBlockUpdates(); + this.logger.info("Initialized"); + } + async subscribeToBlockUpdates() { + const activeNetworks = this.networkManager.getActiveNetworks(); + for (const network of activeNetworks) { + const blockManager = this.blockManagerRegistry.getBlockManager(network.name); + if (!blockManager) { + continue; + } + const unwatcher = blockManager.watchBlocks({ + onBlockRange: async (startBlock, endBlock) => { + await this.fetchLogsForWatchers(network.name, startBlock, endBlock); + } + }); + this.blockManagerUnwatchers.set(network.name, unwatcher); + } + } + logWatcher = { + create: (contractAddress, chainName, onLogs, event) => { + const id2 = v4_default(); + const watcher = { + id: id2, + chainName, + contractAddress, + event, + callback: onLogs + }; + this.logWatchers.set(id2, watcher); + this.logger.debug( + `Created log watcher for ${chainName}:${contractAddress} (${event.name})` + ); + return id2; + }, + remove: (watcherId) => { + const result = this.logWatchers.delete(watcherId); + if (result) { + this.logger.info(`Removed log watcher ${watcherId}`); + } else { + this.logger.warn(`Failed to remove log watcher ${watcherId} (not found)`); + } + return result; + } + }; + async fetchLogsForWatchers(chainName, fromBlock, toBlock) { + this.logger.debug(`fetching logs for blocks ${fromBlock} - ${toBlock}`); + const watchersForChain = Array.from(this.logWatchers.values()).filter( + (watcher) => watcher.chainName === chainName + ); + if (watchersForChain.length === 0) return; + const network = this.networkManager.getNetworkByName(chainName); + if (!network) { + this.logger.warn(`Unknown network: ${chainName}`); + return; + } + if (!this.cachedLogs.has(chainName)) { + this.cachedLogs.set(chainName, /* @__PURE__ */ new Map()); + } + const chainCache = this.cachedLogs.get(chainName); + const watchersByContract = this.groupWatchersByContract(watchersForChain); + for (const [contractAddress, contractWatchers] of watchersByContract) { + try { + const events = contractWatchers.map((w2) => w2.event); + const logs = await this.getContractLogs( + contractAddress, + fromBlock, + toBlock, + events, + network + ); + const logsByEvent = /* @__PURE__ */ new Map(); + for (const log of logs) { + const eventName = log.eventName || ""; + const logId = `${log.transactionHash}:${log.logIndex}`; + if (chainCache.has(logId)) continue; + chainCache.set(logId, log); + const existingLogs = logsByEvent.get(eventName) || []; + existingLogs.push(log); + logsByEvent.set(eventName, existingLogs); + } + for (const watcher of contractWatchers) { + const eventName = watcher.event?.name || ""; + const watcherLogs = logsByEvent.get(eventName) || []; + if (watcherLogs.length > 0) { + watcher.callback(watcherLogs, network).catch((error) => { + this.logger.error( + `Error in watcher callback (ID: ${watcher.id}):`, + error + ); + }); + } + } + } catch (error) { + this.logger.error( + `Error fetching logs for ${contractAddress} on ${chainName}:`, + error + ); + } + } + } + groupWatchersByContract(watchers) { + const result = /* @__PURE__ */ new Map(); + for (const watcher of watchers) { + const existing = result.get(watcher.contractAddress) || []; + existing.push(watcher); + result.set(watcher.contractAddress, existing); + } + return result; + } + async getContractLogs(contractAddress, fromBlock, toBlock, events, network) { + if (events.length === 0) return []; + const allLogs = []; + for (const event of events) { + const eventLogs = await this.getLogs( + { + address: contractAddress, + event, + fromBlock, + toBlock + }, + network + ); + allLogs.push(...eventLogs); + } + return allLogs; + } + async getLogs(query, network) { + const { publicClient } = this.viemClientManager.getClients(network); + try { + const filter2 = { + address: query.address, + fromBlock: query.fromBlock, + toBlock: query.toBlock, + event: query.event + }; + if (query.args) { + filter2.args = query.args; + } + const logs = await publicClient.getLogs(filter2); + return logs; + } catch (error) { + this.logger.error(`Error fetching logs on ${network.name}:`, error); + return []; + } + } + dispose() { + for (const [networkName, unwatcher] of this.blockManagerUnwatchers.entries()) { + unwatcher(); + this.logger.info(`Unsubscribed from block updates for ${networkName}`); + } + this.blockManagerUnwatchers.clear(); + this.logWatchers.clear(); + this.cachedLogs.clear(); + this.logger.info("Disposed"); + } +}; + +// src/common/managers/TxWriter.ts +var TxWriter = class _TxWriter { + static instance; + transactions = /* @__PURE__ */ new Map(); + txByType = /* @__PURE__ */ new Map([ + ["default" /* DEFAULT */, /* @__PURE__ */ new Set()], + ["message" /* MESSAGE */, /* @__PURE__ */ new Set()], + ["fee" /* FEE */, /* @__PURE__ */ new Set()], + ["admin" /* ADMIN */, /* @__PURE__ */ new Set()] + ]); + networkManager; + viemClientManager; + logger; + constructor(networkManager, viemClientManager) { + this.networkManager = networkManager; + this.viemClientManager = viemClientManager; + this.logger = Logger.getInstance().getLogger("TxWriter"); + } + static createInstance(networkManager, viemClientManager) { + _TxWriter.instance = new _TxWriter(networkManager, viemClientManager); + return _TxWriter.instance; + } + static getInstance() { + if (!_TxWriter.instance) { + throw new Error("TxWriter is not initialized. Call createInstance() first."); + } + return _TxWriter.instance; + } + async initialize() { + this.logger.info("Initialized"); + } + async callContract(walletClient, publicClient, network, params) { + const txType = this.determineTxType(params); + try { + if (globalConfig.TX_MANAGER.DRY_RUN) { + this.logger.info( + `[DRY_RUN][${network.name}] Contract call: ${params.functionName}` + ); + const mockTxHash = `0xdry${Date.now().toString(16)}`; + const managedTx2 = this.createManagedTx(network, params, txType, mockTxHash); + return managedTx2; + } + const txHash = await callContract(publicClient, walletClient, params); + this.logger.debug(`[${network.name}] Contract call transaction hash: ${txHash}`); + const managedTx = this.createManagedTx(network, params, txType, txHash); + return managedTx; + } catch (error) { + this.logger.error(`[${network.name}] Contract call failed: ${error}`); + throw error; + } + } + createManagedTx(network, params, txType, txHash) { + const id2 = v4_default(); + const managedTx = { + id: id2, + chainName: network.name, + txHash, + submittedAt: Date.now(), + submissionBlock: null, + status: "submitted" /* SUBMITTED */ + }; + this.transactions.set(id2, managedTx); + this.txByType.get(txType)?.add(id2); + return managedTx; + } + updateTxStatus(managedTx, status, blockNumber) { + managedTx.status = status; + if (blockNumber) { + managedTx.submissionBlock = blockNumber; + } + } + async determineTxType(params) { + return "default" /* DEFAULT */; + } + findTransactionByHash(txHash) { + for (const tx of this.transactions.values()) { + if (tx.txHash === txHash) { + return tx; + } + } + return null; + } + async onTxReorg(txHash, chainName) { + const tx = this.findTransactionByHash(txHash); + if (!tx) { + this.logger.warn(`[${chainName}] Cannot find transaction ${txHash} for reorg handling`); + return null; + } + this.logger.info(`[${chainName}] Handling reorg for transaction ${txHash}`); + tx.status = "failed" /* FAILED */; + return null; + } + onTxFinality(txHash, chainName) { + const tx = this.findTransactionByHash(txHash); + if (!tx) { + this.logger.warn( + `[${chainName}] Cannot find transaction ${txHash} for finality handling` + ); + return; + } + this.logger.info(`[${chainName}] Transaction ${txHash} is now final`); + tx.status = "finalized" /* FINALIZED */; + } + getPendingTransactions(chainName) { + const allTxs = Array.from(this.transactions.values()); + return allTxs.filter((tx) => { + if (chainName && tx.chainName !== chainName) return false; + return tx.status !== "finalized" /* FINALIZED */; + }); + } + dispose() { + this.transactions.clear(); + this.txByType.clear(); + this.logger.info("Disposed"); + } +}; + +// node_modules/viem/_esm/accounts/privateKeyToAccount.js +init_secp256k1(); +init_toHex(); + +// node_modules/viem/_esm/accounts/toAccount.js +init_address(); +init_isAddress(); +function toAccount(source) { + if (typeof source === "string") { + if (!isAddress(source, { strict: false })) + throw new InvalidAddressError({ address: source }); + return { + address: source, + type: "json-rpc" + }; + } + if (!isAddress(source.address, { strict: false })) + throw new InvalidAddressError({ address: source.address }); + return { + address: source.address, + nonceManager: source.nonceManager, + sign: source.sign, + signAuthorization: source.signAuthorization, + signMessage: source.signMessage, + signTransaction: source.signTransaction, + signTypedData: source.signTypedData, + source: "custom", + type: "local" + }; +} + +// node_modules/viem/_esm/accounts/utils/sign.js +init_secp256k1(); +init_toHex(); +var extraEntropy = false; +async function sign({ hash: hash2, privateKey, to: to2 = "object" }) { + const { r, s, recovery } = secp256k1.sign(hash2.slice(2), privateKey.slice(2), { lowS: true, extraEntropy }); + const signature = { + r: numberToHex(r, { size: 32 }), + s: numberToHex(s, { size: 32 }), + v: recovery ? 28n : 27n, + yParity: recovery + }; + return (() => { + if (to2 === "bytes" || to2 === "hex") + return serializeSignature({ ...signature, to: to2 }); + return signature; + })(); +} + +// node_modules/viem/_esm/accounts/utils/signAuthorization.js +async function signAuthorization2(parameters) { + const { chainId, nonce, privateKey, to: to2 = "object" } = parameters; + const address = parameters.contractAddress ?? parameters.address; + const signature = await sign({ + hash: hashAuthorization({ address, chainId, nonce }), + privateKey, + to: to2 + }); + if (to2 === "object") + return { + address, + chainId, + nonce, + ...signature + }; + return signature; +} + +// node_modules/viem/_esm/accounts/utils/signMessage.js +async function signMessage2({ message, privateKey }) { + return await sign({ hash: hashMessage(message), privateKey, to: "hex" }); +} + +// node_modules/viem/_esm/accounts/utils/signTransaction.js +init_keccak256(); +async function signTransaction2(parameters) { + const { privateKey, transaction, serializer = serializeTransaction } = parameters; + const signableTransaction = (() => { + if (transaction.type === "eip4844") + return { + ...transaction, + sidecars: false + }; + return transaction; + })(); + const signature = await sign({ + hash: keccak256(serializer(signableTransaction)), + privateKey + }); + return serializer(transaction, signature); +} + +// node_modules/viem/_esm/accounts/utils/signTypedData.js +async function signTypedData2(parameters) { + const { privateKey, ...typedData } = parameters; + return await sign({ + hash: hashTypedData(typedData), + privateKey, + to: "hex" + }); +} + +// node_modules/viem/_esm/accounts/privateKeyToAccount.js +function privateKeyToAccount(privateKey, options = {}) { + const { nonceManager } = options; + const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false)); + const address = publicKeyToAddress(publicKey); + const account = toAccount({ + address, + nonceManager, + async sign({ hash: hash2 }) { + return sign({ hash: hash2, privateKey, to: "hex" }); + }, + async signAuthorization(authorization) { + return signAuthorization2({ ...authorization, privateKey }); + }, + async signMessage({ message }) { + return signMessage2({ message, privateKey }); + }, + async signTransaction(transaction, { serializer } = {}) { + return signTransaction2({ privateKey, transaction, serializer }); + }, + async signTypedData(typedData) { + return signTypedData2({ ...typedData, privateKey }); + } + }); + return { + ...account, + publicKey, + source: "privateKey" + }; +} + +// src/common/managers/ViemClientManager.ts +var ViemClientManager = class _ViemClientManager extends ManagerBase { + static instance; + clients = /* @__PURE__ */ new Map(); + rpcManager; + logger; + constructor(rpcManager) { + super(); + this.rpcManager = rpcManager; + this.logger = Logger.getInstance().getLogger("ViemClientManager"); + } + static createInstance(rpcManager) { + _ViemClientManager.instance = new _ViemClientManager(rpcManager); + return _ViemClientManager.instance; + } + static getInstance() { + if (!_ViemClientManager.instance) { + throw new Error("ViemClientManager is not initialized. Call createInstance() first."); + } + return _ViemClientManager.instance; + } + async initialize() { + if (this.initialized) return; + this.rpcManager.registerRpcUpdateListener(this); + await super.initialize(); + this.logger.debug("Initialized"); + } + createTransport(chain) { + const rpcUrls = this.rpcManager.getRpcsForNetwork(chain.name); + if (!rpcUrls || rpcUrls.length === 0) { + throw new Error(`No RPC URLs available for chain ${chain.name}`); + } + return fallback( + rpcUrls.map((url2) => createCustomHttpTransport(url2)), + { + ...globalConfig.VIEM.FALLBACK_TRANSPORT_OPTIONS, + shouldThrow: (error) => { + if (error instanceof HttpRequestError || error instanceof RpcRequestError || error instanceof TransactionNotFoundError || error instanceof UnknownRpcError || error instanceof UnknownNodeError || error instanceof InvalidInputRpcError || error instanceof MethodNotFoundRpcError || error instanceof TimeoutError || error instanceof MethodNotSupportedRpcError) { + return false; + } else if (error instanceof ContractFunctionExecutionError) { + if (error.details.includes( + "the method eth_sendRawTransaction does not exist" + )) { + return false; + } + } + return true; + } + } + ); + } + initializeClients(chain) { + const privateKey = getEnvVar("OPERATOR_PRIVATE_KEY"); + const account = privateKeyToAccount(`0x${privateKey}`); + const transport = this.createTransport(chain); + const publicClient = createPublicClient({ + transport, + chain: chain.viemChain, + batch: { multicall: true } + }); + const walletClient = createWalletClient({ + transport, + chain: chain.viemChain, + account + }); + return { + publicClient, + walletClient, + account + }; + } + getClients(chain) { + if (!this.initialized) { + throw new Error("ViemClientManager not properly initialized"); + } + if (!chain) { + throw new Error("Cannot get clients: chain parameter is undefined or null"); + } + if (!chain.name) { + this.logger.error(`Invalid chain object provided: ${JSON.stringify(chain)}`); + throw new Error("Cannot get clients: chain.name is missing"); + } + const cachedClients = this.clients.get(chain.name); + if (cachedClients) { + return cachedClients; + } + this.logger.debug(`Creating new clients for chain: ${chain.name} (id: ${chain.id})`); + const newClients = this.initializeClients(chain); + this.clients.set(chain.name, newClients); + return newClients; + } + onRpcUrlsUpdated(networks) { + this.resetClientsForNetworks(networks); + } + resetClientsForNetworks(networks) { + for (const network of networks) { + try { + this.clients.delete(network.name); + } catch (error) { + this.logger.error(`Failed to update viem clients for ${network.name}:`, error); + } + } + this.logger.debug(`Viem clients reset for ${networks.map((n) => n.name).join(", ")}`); + } + onNetworksUpdated(networks) { + } + async updateClientsForNetworks(networks) { + for (const network of networks) { + try { + const newClients = this.initializeClients(network); + this.clients.set(network.name, newClients); + this.logger.debug(`Updated clients for chain ${network.name}`); + } catch (error) { + this.logger.error(`Failed to update clients for chain ${network.name}`, error); + } + } + } + dispose() { + if (this.rpcManager) { + this.rpcManager.unregisterRpcUpdateListener(this); + } + this.clients.clear(); + super.dispose(); + _ViemClientManager.instance = void 0; + this.logger.debug("Disposed"); + } +}; + +// src/relayer-a/businessLogic/ensureDeposit.ts +async function getMinimumDeposit(publicClient, verifierAddress) { + const depositAmount = await publicClient.readContract({ + address: verifierAddress, + abi: globalConfig.ABI.CONCERO_VERIFIER, + functionName: "getMinimumOperatorDeposit", + args: [] + }); + return BigInt(depositAmount); +} +async function getCurrentOperatorDeposit(publicClient, verifierAddress) { + const currentDeposit = await publicClient.readContract({ + address: verifierAddress, + abi: globalConfig.ABI.CONCERO_VERIFIER, + functionName: "getOperatorDeposit", + args: [globalConfig.OPERATOR_ADDRESS] + }); + return BigInt(currentDeposit); +} +async function fetchDepositAndDepositIfNeeded() { + const logger = Logger.getInstance().getLogger("ensureDeposit"); + const networkManager = NetworkManager.getInstance(); + const viemClientManager = ViemClientManager.getInstance(); + const deploymentManager = DeploymentManager.getInstance(); + const verifierNetwork = networkManager.getVerifierNetwork(); + const verifierAddress = await deploymentManager.getConceroVerifier(); + const { publicClient, walletClient, account } = viemClientManager.getClients(verifierNetwork); + const requiredDeposit = await getMinimumDeposit(publicClient, verifierAddress) * 200n; + const currentDeposit = await getCurrentOperatorDeposit(publicClient, verifierAddress); + if (currentDeposit >= requiredDeposit) { + logger.info(`Sufficient deposit of ${currentDeposit} already exists`); + return void 0; + } + const txHash = await callContract(publicClient, walletClient, { + chain: verifierNetwork.viemChain, + address: verifierAddress, + abi: globalConfig.ABI.CONCERO_VERIFIER, + functionName: "operatorDeposit", + args: [globalConfig.OPERATOR_ADDRESS], + value: requiredDeposit, + account + }); + logger.info(`Deposited ${requiredDeposit} to ConceroVerifier with hash ${txHash}`); +} +async function ensureDeposit() { + await fetchDepositAndDepositIfNeeded(); + setInterval(async () => { + await fetchDepositAndDepositIfNeeded(); + }, globalConfig.NOTIFICATIONS.INTERVAL); +} + +// src/relayer-a/businessLogic/ensureOperatorIsRegistered.ts +var ChainType = { + EVM: 0, + NON_EVM: 1 +}; +var OperatorRegistrationAction = { + Deregister: 0, + Register: 1 +}; +async function isOperatorRegistered(publicClient, networkManager, deploymentManager) { + const conceroVerifierNetwork = networkManager.getVerifierNetwork(); + const isRegistered = await publicClient.readContract({ + address: await deploymentManager.getConceroVerifier(), + abi: globalConfig.ABI.CONCERO_VERIFIER, + functionName: "isOperatorRegistered", + args: [globalConfig.OPERATOR_ADDRESS] + }); + return isRegistered; +} +async function requestOperatorRegistration(publicClient, walletClient, account, networkManager, deploymentManager) { + const conceroVerifierNetwork = networkManager.getVerifierNetwork(); + const chainTypes = [BigInt(ChainType.EVM)]; + const operatorActions = [BigInt(OperatorRegistrationAction.Register)]; + const operatorAddresses = [globalConfig.OPERATOR_ADDRESS]; + const transactionHash = await callContract(publicClient, walletClient, { + address: await deploymentManager.getConceroVerifier(), + abi: globalConfig.ABI.CONCERO_VERIFIER, + functionName: "requestOperatorRegistration", + args: [chainTypes, operatorActions, operatorAddresses], + account + }); + eventEmitter.emit("requestOperatorRegistration", { txHash: transactionHash }); + return transactionHash; +} +async function waitForOperatorRegistration(network, contractAddress, fromBlockNumber, operatorAddress) { + const logger = Logger.getInstance().getLogger("waitForOperatorRegistration"); + const viemClientManager = ViemClientManager.getInstance(); + const { publicClient } = viemClientManager.getClients(network); + const POLL_INTERVAL_MS = 3 * 1e3; + const MAX_RETRIES2 = 100; + const EVENT_NAME = "OperatorRegistered"; + let retries = 0; + logger.info( + `Waiting for operator registration event for ${operatorAddress} from block ${fromBlockNumber}` + ); + return new Promise((resolve, reject) => { + const checkForRegistrationEvent = async () => { + if (retries >= MAX_RETRIES2) { + reject(new Error("Max retries reached while waiting for operator registration")); + return; + } + retries++; + try { + const latestBlockNumber = await publicClient.getBlockNumber(); + if (latestBlockNumber <= fromBlockNumber && retries > 1) { + setTimeout(checkForRegistrationEvent, POLL_INTERVAL_MS); + return; + } + const logs = await publicClient.getLogs({ + address: contractAddress, + fromBlock: fromBlockNumber, + toBlock: latestBlockNumber, + event: getAbiItem({ + abi: globalConfig.ABI.CONCERO_VERIFIER, + name: "OperatorRegistered" + }) + }); + const matchingLog = findOperatorRegistrationLog(logs, operatorAddress); + if (matchingLog && matchingLog.transactionHash) { + resolve(matchingLog.transactionHash); + return; + } + setTimeout(checkForRegistrationEvent, POLL_INTERVAL_MS); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger.error(`Error while polling for operator registration: ${errorMessage}`); + setTimeout(checkForRegistrationEvent, POLL_INTERVAL_MS); + } + }; + checkForRegistrationEvent(); + }); +} +function findOperatorRegistrationLog(logs, operatorAddress) { + const EVENT_NAME = "OperatorRegistered"; + const logger = Logger.getInstance().getLogger("findOperatorRegistrationLog"); + for (const log of logs) { + try { + if (log?.args?.operator.toLowerCase() === operatorAddress.toLowerCase() && isHex(log.transactionHash)) { + return log; + } + } catch (error) { + logger.debug( + `Error decoding log: ${error instanceof Error ? error.message : String(error)}` + ); + } + } + return void 0; +} +async function ensureOperatorIsRegistered() { + const logger = Logger.getInstance().getLogger("ensureOperatorIsRegistered"); + const viemClientManager = ViemClientManager.getInstance(); + const networkManager = NetworkManager.getInstance(); + const deploymentManager = DeploymentManager.getInstance(); + const verifierNetwork = networkManager.getVerifierNetwork(); + const { publicClient, walletClient, account } = viemClientManager.getClients(verifierNetwork); + const registered = await isOperatorRegistered(publicClient, networkManager, deploymentManager); + if (registered) { + logger.info("Operator already registered"); + eventEmitter.emit("operatorRegistered", {}); + return; + } + const txHash = await requestOperatorRegistration( + publicClient, + walletClient, + account, + networkManager, + deploymentManager + ); + logger.info(`Requested operator registration with txHash ${txHash}`); + const transaction = await publicClient.getTransaction({ hash: txHash }); + const confirmedTxHash = await waitForOperatorRegistration( + verifierNetwork, + await deploymentManager.getConceroVerifier(), + transaction.blockNumber, + globalConfig.OPERATOR_ADDRESS + ); + logger.info(`Operator registration confirmed with txHash ${confirmedTxHash}`); + eventEmitter.emit("operatorRegistered", {}); +} + +// src/common/eventListener/setupEventListener.ts +async function setupEventListener(network, contractAddress, onLogs, event) { + const logger = Logger.getInstance().getLogger("setupEventListener"); + const txManager = TxManager.getInstance(); + const watcherId = txManager.logWatcher.create( + contractAddress, + network.name, + async (logs, network2) => { + if (logs.length === 0) return; + try { + await onLogs(logs, network2); + } catch (error) { + logger.error( + `${network2.name} Error in onLogs callback for contract ${contractAddress}:`, + error + ); + } + }, + event + ); + return { + stop: () => { + txManager.logWatcher.remove(watcherId); + logger.info( + `${network.name} Stopped monitoring contract ${contractAddress} for ${event.name}` + ); + } + }; +} + +// src/common/eventListener/decodeLogs.ts +function decodeLogs(logs, abi4) { + const decodedLogs = []; + logs.forEach((log) => { + try { + const decodedLog = decodeEventLog({ + abi: abi4, + data: log.data, + topics: log.topics, + strict: true + }); + decodedLogs.push({ ...log, ...decodedLog }); + } catch (error) { + if (error instanceof AbiEventSignatureNotFoundError) { + return; + } else { + throw error; + } + } + }); + return decodedLogs; +} + +// src/relayer-a/businessLogic/requestCLFMessageReport.ts +async function requestCLFMessageReport(logs, network) { + if (logs.length === 0) return; + const logger = Logger.getInstance().getLogger("requestCLFMessageReport"); + logger.debug( + `Processing ${logs.length} logs for CLF message report requests from ${network.name}` + ); + const networkManager = NetworkManager.getInstance(); + const verifierNetwork = networkManager.getVerifierNetwork(); + const verifierAddress = await DeploymentManager.getInstance().getConceroVerifier(); + const { publicClient, walletClient } = ViemClientManager.getInstance().getClients(verifierNetwork); + try { + const decodedLogs = decodeLogs(logs, globalConfig.ABI.CONCERO_ROUTER); + const promises = []; + for (const decodedLog of decodedLogs) { + promises.push( + processMessageReportRequest( + decodedLog, + network.chainSelector, + logger, + networkManager, + verifierNetwork, + verifierAddress, + publicClient, + walletClient + ) + ); + } + await Promise.all(promises); + } catch (error) { + logger.error(`Error processing logs from ${network.name}:`, error); + } +} +async function processMessageReportRequest(decodedLog, srcChainSelector, logger, networkManager, verifierNetwork, verifierAddress, publicClient, walletClient) { + try { + const { messageId, message, sender } = decodedLog.args; + if (!messageId || !message || !sender) { + logger.warn(`Missing required data in log: ${JSON.stringify(decodedLog)}`); + return; + } + const encodedSrcChainData = encodeAbiParameters( + [ + { + type: "tuple", + components: [ + { name: "blockNumber", type: "uint256" }, + { name: "sender", type: "address" } + ] + } + ], + [ + { + blockNumber: decodedLog.blockNumber, + sender + } + ] + ); + if (globalConfig.TX_MANAGER.DRY_RUN) { + const dryRunTxHash = `dry-run-${Date.now()}-${messageId}`; + logger.info( + `[DRY_RUN]:${verifierNetwork.name} CLF message report requested with hash: ${dryRunTxHash}` + ); + eventEmitter.emit("requestMessageReport", { txHash: dryRunTxHash }); + return; + } + const managedTx = await TxManager.getInstance().callContract( + walletClient, + publicClient, + verifierNetwork, + { + address: verifierAddress, + abi: globalConfig.ABI.CONCERO_VERIFIER, + functionName: "requestMessageReport", + args: [messageId, keccak256(message), srcChainSelector, encodedSrcChainData], + chain: verifierNetwork.viemChain, + options: { + receiptConfirmations: 3, + receiptTimeout: 6e4 + } + } + ); + if (managedTx && managedTx.txHash) { + eventEmitter.emit("requestMessageReport", { + txHash: managedTx.txHash + }); + logger.info( + `${verifierNetwork.name} CLF message report requested with hash: ${managedTx.txHash}` + ); + } else { + logger.error( + `${verifierNetwork.name} Failed to submit CLF message report request transaction` + ); + } + } catch (error) { + logger.error( + `[${verifierNetwork.name}] Error requesting CLF message report for messageId ${decodedLog.args?.messageId || "unknown"}:`, + error + ); + eventEmitter.emit("requestMessageReportError", { + messageId: decodedLog.args?.messageId, + error: error.message, + chainName: verifierNetwork.name + }); + } +} + +// src/relayer-a/businessLogic/submitCLFMessageReport.ts +async function parseMessageResults(decodedCLFReport, logger) { + const messageResults = []; + for (let i = 0; i < decodedCLFReport.report.results.length; i++) { + try { + const decodedResult = decodeMessageReportResult(decodedCLFReport.report.results[i]); + messageResults.push(decodedResult); + logger.debug(`Successfully decoded result ${i}: messageId ${decodedResult.messageId}`); + } catch (error) { + logger.error(`Failed to decode result ${i}: ${error}`); + } + } + return messageResults; +} +function groupMessagesByDestination(messageResults) { + const messagesByDstChain = /* @__PURE__ */ new Map(); + messageResults.forEach((result, index2) => { + const dstChainSelector = result.dstChainSelector.toString(); + if (!messagesByDstChain.has(dstChainSelector)) { + messagesByDstChain.set(dstChainSelector, { results: [], indexes: [] }); + } + messagesByDstChain.get(dstChainSelector).results.push(result); + messagesByDstChain.get(dstChainSelector).indexes.push(index2); + }); + return messagesByDstChain; +} +async function fetchOriginalMessage(result, activeNetworkNames, networkManager, deploymentManager, blockManagerRegistry, txManager, logger) { + const { srcChainSelector, messageId, srcBlockNumber } = result; + const srcChain = networkManager.getNetworkBySelector(srcChainSelector.toString()); + if (!activeNetworkNames.includes(srcChain.name)) { + logger.warn(`${srcChain.name} is not active. Skipping message with id ${messageId}`); + return { message: null, gasLimit: BigInt(0) }; + } + const srcContractAddress = await deploymentManager.getRouterByChainName(srcChain.name); + const srcBlockManager = blockManagerRegistry.getBlockManager(srcChain.name); + const decodedLogs = await txManager.getLogs( + { + address: srcContractAddress, + event: getAbiItem({ + abi: globalConfig.ABI.CONCERO_ROUTER, + name: "ConceroMessageSent" + }), + args: { + messageId + }, + fromBlock: srcBlockNumber - BigInt(1), + toBlock: srcBlockNumber + BigInt(1) + }, + srcChain + ); + if (decodedLogs.length === 0) { + logger.warn( + `${srcChain.name}: No decodedLogs found for messageId ${messageId} around block ${srcBlockNumber}.` + ); + return { message: null, gasLimit: BigInt(0) }; + } + const conceroMessageSentLog = decodedLogs.find( + (log) => log.eventName === "ConceroMessageSent" && log.args?.messageId?.toLowerCase() === messageId.toLowerCase() + ); + if (!conceroMessageSentLog) { + logger.error(`Could not find ConceroMessageSent event with messageId ${messageId}`); + return { message: null, gasLimit: BigInt(0) }; + } + const { message, dstChainData } = conceroMessageSentLog.args; + const decodedDstChainData = decodeAbiParameters( + [globalConfig.ABI.EVM_DST_CHAIN_DATA], + dstChainData + )[0]; + return { message, gasLimit: decodedDstChainData.gasLimit }; +} +async function submitBatchToDestination(dstChain, reportSubmission, messages, indexes, results, totalGasLimit, viemClientManager, deploymentManager, txManager, logger) { + if (globalConfig.TX_MANAGER.DRY_RUN) { + logger.info( + `[${dstChain.name}] Dry run: CLF message report with ${messages.length} messages would be submitted` + ); + return; + } + const dstConceroRouter = await deploymentManager.getRouterByChainName(dstChain.name); + const { walletClient, publicClient } = viemClientManager.getClients(dstChain); + const managedTx = await txManager.callContract(walletClient, publicClient, dstChain, { + address: dstConceroRouter, + abi: globalConfig.ABI.CONCERO_ROUTER, + functionName: "submitMessageReport", + args: [reportSubmission, messages, indexes.map((index2) => BigInt(index2))], + chain: dstChain.viemChain, + gas: totalGasLimit + BigInt(messages.length) * globalConfig.TX_MANAGER.GAS_LIMIT.SUBMIT_MESSAGE_REPORT_OVERHEAD + }); + const messageIds = results.map((result) => result.messageId).join(", "); + if (managedTx && managedTx.txHash) { + logger.info( + `[${dstChain.name}] CLF Report with ${messages.length} results submitted with hash: ${managedTx.txHash}` + ); + logger.debug(`[${dstChain.name}] Message IDs in batch: ${messageIds}`); + } else { + logger.error( + `[${dstChain.name}] Failed to submit batch of CLF message reports. Message IDs: ${messageIds}` + ); + } +} +async function submitCLFMessageReport(logs, network) { + if (logs.length === 0) return; + const logger = Logger.getInstance().getLogger("processMessageReports"); + logger.debug(`Processing ${logs.length} MessageReport logs`); + try { + const decodedLogs = decodeLogs(logs, globalConfig.ABI.CONCERO_VERIFIER); + await processMessageReports(decodedLogs); + } catch (error) { + logger.error(`Error processing message report logs: ${error}`); + } +} +async function processMessageReports(logs) { + const logger = Logger.getInstance().getLogger("submitCLFMessageReport"); + const networkManager = NetworkManager.getInstance(); + const blockManagerRegistry = BlockManagerRegistry.getInstance(); + const viemClientManager = ViemClientManager.getInstance(); + const deploymentManager = DeploymentManager.getInstance(); + const txManager = TxManager.getInstance(); + const activeNetworks = networkManager.getActiveNetworks(); + const activeNetworkNames = activeNetworks.map((network) => network.name); + try { + const txHashToLogs = /* @__PURE__ */ new Map(); + for (const log of logs) { + const txHash = log.transactionHash; + const existingLogs = txHashToLogs.get(txHash) || []; + existingLogs.push(log); + txHashToLogs.set(txHash, existingLogs); + } + const txProcessPromises = Array.from(txHashToLogs.entries()).map( + async ([txHash, txLogs]) => { + logger.debug(`Processing transaction ${txHash} with ${txLogs.length} logs`); + try { + const verifierNetwork = networkManager.getVerifierNetwork(); + const { publicClient: verifierPublicClient } = viemClientManager.getClients(verifierNetwork); + const messageReportTx = await verifierPublicClient.getTransaction({ + hash: txHash + }); + const decodedCLFReport = decodeCLFReport(messageReportTx); + logger.debug( + `Report contains ${decodedCLFReport.report.results.length} results` + ); + const messageResults = await parseMessageResults(decodedCLFReport, logger); + if (messageResults.length === 0) { + logger.warn( + `No valid message results found in the report for transaction ${txHash}` + ); + return; + } + const messagesByDstChain = groupMessagesByDestination(messageResults); + const reportSubmission = { + context: decodedCLFReport.reportContext, + report: decodedCLFReport.reportBytes, + rs: decodedCLFReport.rs, + ss: decodedCLFReport.ss, + rawVs: decodedCLFReport.rawVs + }; + const dstChainProcessPromises = Array.from(messagesByDstChain.entries()).map( + async ([dstChainSelector, { results, indexes }]) => { + const dstChain = networkManager.getNetworkBySelector(dstChainSelector); + if (!activeNetworkNames.includes(dstChain.name)) { + logger.warn( + `${dstChain.name} is not active. Skipping message submission.` + ); + return; + } + const dstBlockManager = blockManagerRegistry.getBlockManager( + dstChain.name + ); + if (!dstBlockManager) { + logger.error(`No BlockManager for ${dstChain.name}`); + return; + } + const messagePromises = results.map( + (result) => fetchOriginalMessage( + result, + activeNetworkNames, + networkManager, + deploymentManager, + blockManagerRegistry, + txManager, + logger + ) + ); + const resolvedMessages = await Promise.all(messagePromises); + const messages = []; + let totalGasLimit = BigInt(0); + for (const { message, gasLimit } of resolvedMessages) { + if (message) { + messages.push(message); + totalGasLimit += gasLimit; + } + } + if (messages.length !== results.length) { + logger.error( + `[${dstChain.name}] Could only find ${messages.length}/${results.length} messages. Skipping batch submission.` + ); + return; + } + await submitBatchToDestination( + dstChain, + reportSubmission, + messages, + indexes, + results, + totalGasLimit, + viemClientManager, + deploymentManager, + txManager, + logger + ); + } + ); + await Promise.all(dstChainProcessPromises); + } catch (error) { + logger.error(`Error processing transaction ${txHash}: ${error}`); + } + } + ); + await Promise.all(txProcessPromises); + } catch (e) { + logger.error(`Error when submitting clf report: ${e}`); + } +} + +// src/relayer-a/eventListener/setupEventListeners.ts +async function setupEventListeners() { + const logger = Logger.getInstance().getLogger("setupEventListeners"); + const networkManager = NetworkManager.getInstance(); + const deploymentManager = DeploymentManager.getInstance(); + const activeNetworks = networkManager.getActiveNetworks(); + const eventListenerHandles = []; + for (const network of activeNetworks) { + const routerAddress = await deploymentManager.getRouterByChainName(network.name); + try { + const sentEvent = getAbiItem({ + abi: globalConfig.ABI.CONCERO_ROUTER, + name: "ConceroMessageSent" + }); + const sentHandle = await setupEventListener( + network, + routerAddress, + requestCLFMessageReport, + sentEvent + ); + eventListenerHandles.push(sentHandle); + } catch (error) { + logger.error(`Failed to set up router event listeners for ${network.name}:`, error); + } + } + const verifierNetwork = networkManager.getVerifierNetwork(); + const verifierAddress = await deploymentManager.getConceroVerifier(); + try { + const messageReportEvent = getAbiItem({ + abi: globalConfig.ABI.CONCERO_VERIFIER, + name: "MessageReport" + }); + const messageReportHandle = await setupEventListener( + verifierNetwork, + verifierAddress, + submitCLFMessageReport, + messageReportEvent + ); + eventListenerHandles.push(messageReportHandle); + } catch (error) { + logger.error("Failed to set up verifier event listeners:", error); + } +} + +// src/relayer-a/index.ts +var globalErrorHandler = (error) => { + if (error instanceof AppError) { + if (!error.isOperational) { + } + } else { + const appError = new AppError("UnknownError" /* UnknownError */, error); + if (!appError.isOperational) { + } + } +}; +process.on("unhandledRejection", (reason) => { + globalErrorHandler( + new AppError( + "UnhandledRejection" /* UnhandledRejection */, + reason instanceof Error ? reason : new Error(String(reason)) + ) + ); +}); +process.on("uncaughtException", (error) => { + globalErrorHandler(new AppError("UncaughtException" /* UncaughtException */, error)); +}); +async function main() { + await initializeManagers(); + await checkGas(); + await ensureDeposit(); + await ensureOperatorIsRegistered(); + await setupEventListeners(); + const blockManagerRegistry = BlockManagerRegistry.getInstance(); + for (const blockManager of blockManagerRegistry.getAllBlockManagers()) { + await blockManager.startPolling(); + } +} +main().catch(globalErrorHandler); +export { + main +}; +/*! Bundled license information: + +mime-db/index.js: + (*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + *) + +mime-types/index.js: + (*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + *) + +safe-buffer/index.js: + (*! safe-buffer. MIT License. Feross Aboukhadijeh *) + +moment/moment.js: + (*! moment.js *) + (*! version : 2.30.1 *) + (*! authors : Tim Wood, Iskren Chernev, Moment.js contributors *) + (*! license : MIT *) + (*! momentjs.com *) + +file-stream-rotator/FileStreamRotator.js: + (*! + * FileStreamRotator + * Copyright(c) 2012-2017 Holiday Extras. + * Copyright(c) 2017 Roger C. + * MIT Licensed + *) + +@noble/hashes/esm/utils.js: +@noble/hashes/esm/utils.js: + (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/curves/esm/abstract/utils.js: +@noble/curves/esm/abstract/modular.js: +@noble/curves/esm/abstract/curve.js: +@noble/curves/esm/abstract/weierstrass.js: +@noble/curves/esm/_shortw_utils.js: +@noble/curves/esm/secp256k1.js: + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +axios/dist/node/axios.cjs: + (*! Axios v1.9.0 Copyright (c) 2025 Matt Zabriskie and contributors *) + +@prisma/client/runtime/library.js: + (*! Bundled license information: + + decimal.js/decimal.mjs: + (*! + * decimal.js v10.4.3 + * An arbitrary-precision Decimal type for JavaScript. + * https://github.com/MikeMcl/decimal.js + * Copyright (c) 2022 Michael Mclaughlin + * MIT Licence + *) + *) +*/ diff --git a/src/common/managers/BlockManagerRegistry.ts b/src/common/managers/BlockManagerRegistry.ts index 9d57891..2ea8dff 100644 --- a/src/common/managers/BlockManagerRegistry.ts +++ b/src/common/managers/BlockManagerRegistry.ts @@ -59,10 +59,6 @@ export class BlockManagerRegistry } try { - // Ensure RPC URLs are available for this network - await this.rpcManager.ensureRpcsForNetwork(network); - - // Get the client with the now-available RPC URLs const { publicClient } = this.viemClientManager.getClients(network); // Create the BlockManager @@ -92,10 +88,10 @@ export class BlockManagerRegistry } } - // Create BlockManagers for new networks in parallel + // Create BlockManagers for new networks const newNetworks = networks.filter(network => !currentNetworkNames.has(network.name)); if (newNetworks.length > 0) { - this.logger.debug(`Creating ${newNetworks.length} new BlockManagers in parallel`); + this.logger.debug(`Creating ${newNetworks.length} new BlockManagers`); const results = await Promise.all( newNetworks.map(network => this.ensureBlockManagerForNetwork(network)), diff --git a/src/common/managers/DeploymentManager.ts b/src/common/managers/DeploymentManager.ts index 17dcd02..1894976 100644 --- a/src/common/managers/DeploymentManager.ts +++ b/src/common/managers/DeploymentManager.ts @@ -23,7 +23,7 @@ export class DeploymentManager private constructor(logger: LoggerInterface, config: DeploymentManagerConfig) { super(); - this.httpClient = HttpClient.getQueueInstance(); + this.httpClient = HttpClient.getInstance(); this.logger = logger; this.config = config; } diff --git a/src/common/managers/NetworkManager.ts b/src/common/managers/NetworkManager.ts index 5d2f1f8..801921a 100644 --- a/src/common/managers/NetworkManager.ts +++ b/src/common/managers/NetworkManager.ts @@ -1,11 +1,6 @@ import { ConceroNetwork } from "../../types/ConceroNetwork"; import { NetworkManagerConfig } from "../../types/ManagerConfigs"; -import { - IDeploymentsManager, - INetworkManager, - IRpcManager, - NetworkUpdateListener, -} from "../../types/managers"; +import { INetworkManager, NetworkUpdateListener } from "../../types/managers"; import { fetchNetworkConfigs } from "../utils"; import { getEnvVar, localhostViemChain, LoggerInterface } from "../utils/"; @@ -19,31 +14,15 @@ export class NetworkManager extends ManagerBase implements INetworkManager { private allNetworks: Record = {}; private activeNetworks: ConceroNetwork[] = []; private updateIntervalId: NodeJS.Timeout | null = null; - private rpcManager: IRpcManager | null = null; - private deploymentsManager: IDeploymentsManager | null = null; + private updateListeners: NetworkUpdateListener[] = []; private logger: LoggerInterface; private config: NetworkManagerConfig; - private constructor( - logger: LoggerInterface, - config: NetworkManagerConfig, - rpcManager?: IRpcManager, - deploymentsManager?: IDeploymentsManager, - ) { + private constructor(logger: LoggerInterface, config: NetworkManagerConfig) { super(); this.config = config; - this.rpcManager = rpcManager || null; - this.deploymentsManager = deploymentsManager || null; this.logger = logger; - - if (this.rpcManager && "onNetworksUpdated" in this.rpcManager) { - this.registerUpdateListener(this.rpcManager as unknown as NetworkUpdateListener); - } - - if (this.deploymentsManager && "onNetworksUpdated" in this.deploymentsManager) { - this.registerUpdateListener(this.deploymentsManager as NetworkUpdateListener); - } } public static getInstance(): NetworkManager { @@ -53,10 +32,8 @@ export class NetworkManager extends ManagerBase implements INetworkManager { public static createInstance( logger: LoggerInterface, config: NetworkManagerConfig, - rpcManager?: IRpcManager, - deploymentsManager?: IDeploymentsManager, ): NetworkManager { - this.instance = new NetworkManager(logger, config, rpcManager, deploymentsManager); + this.instance = new NetworkManager(logger, config); return this.instance; } @@ -81,9 +58,6 @@ export class NetworkManager extends ManagerBase implements INetworkManager { if (existingIndex === -1) { this.updateListeners.push(listener); - // this.logger.debug( - // `Registered update listener: ${listener.constructor.name}`, - // ); } else { this.logger.warn(`Update listener already registered: ${listener.constructor.name}`); } @@ -197,7 +171,7 @@ export class NetworkManager extends ManagerBase implements INetworkManager { } else { try { const { mainnetNetworks: fetchedMainnet, testnetNetworks: fetchedTestnet } = - await fetchNetworkConfigs(); + await fetchNetworkConfigs(this.config.networkMode); const hasMainnetNetworks = Object.keys(fetchedMainnet).length > 0; const hasTestnetNetworks = Object.keys(fetchedTestnet).length > 0; diff --git a/src/common/managers/RpcManager.ts b/src/common/managers/RpcManager.ts index 3931d15..8f5f102 100644 --- a/src/common/managers/RpcManager.ts +++ b/src/common/managers/RpcManager.ts @@ -3,7 +3,6 @@ import { RpcManagerConfig } from "../../types/ManagerConfigs"; import { IRpcManager, NetworkUpdateListener, RpcUpdateListener } from "../../types/managers"; import { LoggerInterface } from "../utils/"; import { HttpClient } from "../utils/HttpClient"; - import { ManagerBase } from "./ManagerBase"; // Watches @concero/rpcs and keeps an updatable list of RPC endpoints for networks @@ -15,7 +14,11 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat constructor(logger: LoggerInterface, config: RpcManagerConfig) { super(); - this.httpClient = HttpClient.getInstance(); + this.httpClient = HttpClient.getInstance(logger, { + retryDelay: 1000, + maxRetries: 3, + defaultTimeout: 10000, + }); this.logger = logger; this.config = config; } @@ -26,7 +29,6 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat } private rpcUrls: Record = {}; - private lastUpdateTime: Record = {}; private rpcUpdateListeners: RpcUpdateListener[] = []; public static getInstance(): RpcManager { @@ -57,109 +59,41 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat } public async ensureRpcsForNetwork(network: ConceroNetwork): Promise { - const now = Date.now(); - const lastUpdate = this.lastUpdateTime[network.name] || 0; - if (!this.rpcUrls[network.name] || this.rpcUrls[network.name].length === 0) { - await this.updateRpcsForNetwork(network); + await this.updateRpcs([network]); } } - public async fetchRpcUrls( - chainId: number, - chainName: string, - chainType: "mainnet" | "testnet" | "localhost", - ): Promise { - try { - const rpcOverride = this.config.rpcOverrides[chainId.toString()]; - if (rpcOverride && rpcOverride.length) return rpcOverride; - - if (chainType === "localhost") { - const localhostUrl = process.env.LOCALHOST_RPC_URL; - if (!localhostUrl) { - throw new Error("LOCALHOST_RPC_URL environment variable is not set"); - } - return [localhostUrl]; - } - - const url = `${this.config.conceroRpcsUrl}${chainType}.json`; - const rpcData = await this.httpClient.get(url); - - let networkData = rpcData[chainName]; - - if (!networkData) { - throw new Error(`No RPC data found for chain ${chainName} (chainId: ${chainId})`); - } + public async updateRpcsForNetworks(networks: ConceroNetwork[]): Promise { + await this.updateRpcs(networks); + } - let urls = [...networkData.rpcUrls]; + public async updateRpcs(networks: ConceroNetwork[]): Promise { + try { + const url = `${this.config.conceroRpcsUrl}/${this.config.networkMode}.json`; - const rpcsExtension = this.config.rpcExtensions[chainId.toString()]; - if (rpcsExtension) { - urls.push(...rpcsExtension); - } + const response = await this.httpClient.get>(url); - if (urls.length === 0) { - throw new Error(`No RPC URLs available for chain ${chainName}`); + if (!response) { + throw new Error("Failed to fetch RPC data"); } - return urls; - } catch (error) { - this.logger.error(`Error fetching RPC URLs for ${chainName}:`, error); - throw error; - } - } + this.rpcUrls = response; - public async updateRpcsForNetworks(networks: ConceroNetwork[]): Promise { - const updatePromises: Promise[] = []; - const updatedNetworks: ConceroNetwork[] = []; - - for (const network of networks) { - updatePromises.push( - this.updateRpcsForNetwork(network) - .then(() => { - updatedNetworks.push(network); - }) - .catch(error => { - this.logger.error( - `Failed to update RPC for network ${network.name}:`, - error, - ); - }), + // Get list of networks that were updated + const updatedNetworks: ConceroNetwork[] = Object.keys(response).map( + networkName => + ({ + name: networkName, + }) as ConceroNetwork, ); - } - await Promise.allSettled(updatePromises); - - if (updatedNetworks.length > 0) { + // Notify listeners this.notifyRpcUpdateListeners(updatedNetworks); - } - this.logger.debug( - `Updated RPC URLs for ${updatedNetworks.map(network => network.name).join(", ")}: ${updatedNetworks.length} networks updated`, - ); - } - public async updateRpcsForNetwork(network: ConceroNetwork): Promise { - try { - const urls = await this.fetchRpcUrls(network.id, network.name, network.type); - - if (urls.length > 0) { - const previousUrls = this.rpcUrls[network.name] || []; - this.rpcUrls[network.name] = urls; - this.lastUpdateTime[network.name] = Date.now(); - // this.logger.debug( - // `Updated RPC URLs for ${network.name}: ${urls.length} URLs available`, - // ); - - if (JSON.stringify(previousUrls) !== JSON.stringify(urls)) { - this.notifyRpcUpdateListeners([network]); - } - } else { - this.logger.warn(`No RPC URLs found for chain ${network.name}`); - this.rpcUrls[network.name] = []; - } + this.logger.debug(`Updated RPCs for ${Object.keys(response).length} networks`); } catch (error) { - this.logger.error(`Failed to update RPC URLs for chain ${network.name}:`, error); - this.rpcUrls[network.name] = this.rpcUrls[network.name] || []; + this.logger.error("Failed to update RPCs:", error); throw error; } } @@ -179,7 +113,7 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat } public onNetworksUpdated(networks: ConceroNetwork[]): void { - this.updateRpcsForNetworks(networks).catch(err => + this.updateRpcs(networks).catch(err => this.logger.error("Failed to update RPCs after network update:", err), ); } diff --git a/src/common/managers/ViemClientManager.ts b/src/common/managers/ViemClientManager.ts index 59be9ea..8601a99 100644 --- a/src/common/managers/ViemClientManager.ts +++ b/src/common/managers/ViemClientManager.ts @@ -124,10 +124,16 @@ export class ViemClientManager return newClients; } + // hook from RPCManager public onRpcUrlsUpdated(networks: ConceroNetwork[]): void { this.resetClientsForNetworks(networks); } + // hook from NetworkManager + public onNetworksUpdated(networks: ConceroNetwork[]): void { + // Networks updated, no action needed as clients are created on demand + } + private resetClientsForNetworks(networks: ConceroNetwork[]): void { for (const network of networks) { try { @@ -140,11 +146,6 @@ export class ViemClientManager this.logger.debug(`Viem clients reset for ${networks.map(n => n.name).join(", ")}`); } - public onNetworksUpdated(networks: ConceroNetwork[]): void { - // We don't need to reset clients here as RpcManager will trigger onRpcUrlsUpdated - // which will handle the client resets - } - public async updateClientsForNetworks(networks: ConceroNetwork[]): Promise { for (const network of networks) { try { diff --git a/src/common/utils/HttpClient.ts b/src/common/utils/HttpClient.ts index 4fbf513..318ae7f 100644 --- a/src/common/utils/HttpClient.ts +++ b/src/common/utils/HttpClient.ts @@ -8,43 +8,26 @@ import { AppError } from "./AppError"; import { LoggerInterface } from "./Logger"; export class HttpClient extends ManagerBase { - private static defaultInstance?: HttpClient; - private static queueInstance?: HttpClient; + private static instance?: HttpClient; private axiosInstance?: AxiosInstance; private logger: LoggerInterface; - private requestQueue: Array<() => Promise> = []; - private activeRequests: number = 0; - private maxConcurrentRequests?: number; private config: HttpClientConfig; - constructor(logger: LoggerInterface, config: HttpClientConfig, maxConcurrentRequests?: number) { + constructor(logger: LoggerInterface, config: HttpClientConfig) { super(); - this.maxConcurrentRequests = maxConcurrentRequests; + this.logger = logger; this.config = config; } - public static createInstance( - logger: LoggerInterface, - config: HttpClientConfig, - maxConcurrentRequests?: number, - ): HttpClient { - return new HttpClient(logger, config, maxConcurrentRequests); + public static createInstance(logger: LoggerInterface, config: HttpClientConfig): HttpClient { + this.instance = new HttpClient(logger, config); + return this.instance; } - public static getInstance(logger: LoggerInterface, config: HttpClientConfig): HttpClient { - if (!HttpClient.defaultInstance) { - HttpClient.defaultInstance = new HttpClient(logger, config); - } - return HttpClient.defaultInstance; - } - - public static getQueueInstance(logger: LoggerInterface, config: HttpClientConfig): HttpClient { - if (!HttpClient.queueInstance) { - HttpClient.queueInstance = new HttpClient(logger, config, 2); - } - return HttpClient.queueInstance; + public static getInstance(): HttpClient { + return this.instance; } public async initialize(): Promise { @@ -93,48 +76,17 @@ export class HttpClient extends ManagerBase { } public dispose(): void { - // Clear the request queue - this.requestQueue = []; - this.activeRequests = 0; this.axiosInstance = undefined; super.dispose(); } public static disposeInstances(): void { - if (HttpClient.defaultInstance) { - HttpClient.defaultInstance.dispose(); - HttpClient.defaultInstance = undefined; - } - if (HttpClient.queueInstance) { - HttpClient.queueInstance.dispose(); - HttpClient.queueInstance = undefined; - } - } - - private async processQueue(): Promise { - if ( - (this.maxConcurrentRequests === undefined || - this.activeRequests < this.maxConcurrentRequests) && - this.requestQueue.length > 0 - ) { - const nextRequest = this.requestQueue.shift(); - if (nextRequest) { - this.activeRequests++; - try { - await nextRequest(); - } finally { - this.activeRequests--; - this.processQueue(); - } - } + if (HttpClient.instance) { + HttpClient.instance.dispose(); + HttpClient.instance = undefined; } } - private enqueueRequest(requestFn: () => Promise): void { - this.requestQueue.push(requestFn); - this.processQueue(); - } - private async request( method: "GET" | "POST", url: string, @@ -148,31 +100,25 @@ export class HttpClient extends ManagerBase { ); } - return new Promise((resolve, reject) => { - const executeRequest = async () => { - try { - this.logger.debug( - `${method} request to ${url} with config: ${JSON.stringify(config)} ${ - body ? `and body: ${JSON.stringify(body)}` : "" - }`, - ); + try { + this.logger.debug( + `${method} request to ${url} with config: ${JSON.stringify(config)} ${ + body ? `and body: ${JSON.stringify(body)}` : "" + }`, + ); - const response: AxiosResponse = await this.axiosInstance!.request({ - method, - url, - data: body, - ...config, - }); - - resolve(response.data); - } catch (error) { - this.logger.error(`Request failed for ${url} with error:`, error); - reject(new AppError(AppErrorEnum.FailedHTTPRequest, error)); - } - }; + const response: AxiosResponse = await this.axiosInstance.request({ + method, + url, + data: body, + ...config, + }); - this.enqueueRequest(executeRequest); - }); + return response.data; + } catch (error) { + this.logger.error(`Request failed for ${url} with error:`, error); + throw new AppError(AppErrorEnum.FailedHTTPRequest, error); + } } public async get(url: string, config: AxiosRequestConfig = {}): Promise { diff --git a/src/common/utils/fetchNetworkConfigs.ts b/src/common/utils/fetchNetworkConfigs.ts index 1032037..95b805f 100644 --- a/src/common/utils/fetchNetworkConfigs.ts +++ b/src/common/utils/fetchNetworkConfigs.ts @@ -33,38 +33,43 @@ export interface NetworkConfigs { testnetNetworks: Record; } -export async function fetchNetworkConfigs(): Promise { +export async function fetchNetworkConfigs( + networkMode: "mainnet" | "testnet" | "localhost" = "testnet", +): Promise { const logger = Logger.getInstance().getLogger("NetworkConfig"); - const httpClient = HttpClient.getInstance(logger, { - retryDelay: 1000, - maxRetries: 3, - defaultTimeout: 5000, - }); + const httpClient = HttpClient.getInstance(); try { - const [mainnetData, testnetData] = await Promise.all([ - httpClient.get(globalConfig.URLS.V2_NETWORKS.MAINNET), - httpClient.get(globalConfig.URLS.V2_NETWORKS.TESTNET), - ]); + let mainnetNetworks: Record = {}; + let testnetNetworks: Record = {}; - const mainnetNetworks = processNetworkData( - mainnetData as Record, - false, - logger, - ); + if (networkMode === "localhost") { + // For localhost mode, return empty networks as they are handled separately + return { mainnetNetworks, testnetNetworks }; + } - const testnetNetworks = processNetworkData( - testnetData as Record, - true, - logger, - ); + if (networkMode === "mainnet") { + const mainnetData = await httpClient.get(globalConfig.URLS.V2_NETWORKS.MAINNET); + mainnetNetworks = processNetworkData( + mainnetData as Record, + false, + logger, + ); + } else if (networkMode === "testnet") { + const testnetData = await httpClient.get(globalConfig.URLS.V2_NETWORKS.TESTNET); + testnetNetworks = processNetworkData( + testnetData as Record, + true, + logger, + ); + } return { mainnetNetworks, testnetNetworks, }; } catch (error: unknown) { - logger.error("Failed to fetch network configurations:", error); + logger.error(`Failed to fetch ${networkMode} network configurations:`, error); throw error; } } diff --git a/src/common/utils/initializeManagers.ts b/src/common/utils/initializeManagers.ts index 19710d3..5d13225 100644 --- a/src/common/utils/initializeManagers.ts +++ b/src/common/utils/initializeManagers.ts @@ -18,8 +18,6 @@ import { BlockManagerConfig, BlockManagerRegistryConfig, DeploymentManagerConfig, - HttpClientConfig, - LoggerConfig, NetworkManagerConfig, NonceManagerConfig, RpcManagerConfig, @@ -34,28 +32,23 @@ import { Logger } from "./Logger"; /** Initialize all managers in the correct dependency order */ export async function initializeManagers(): Promise { - const loggerConfig: LoggerConfig = { + const logger = Logger.createInstance({ logDir: globalConfig.LOGGER.LOG_DIR, logMaxSize: globalConfig.LOGGER.LOG_MAX_SIZE, logMaxFiles: globalConfig.LOGGER.LOG_MAX_FILES, logLevelDefault: globalConfig.LOGGER.LOG_LEVEL_DEFAULT, logLevelsGranular: globalConfig.LOGGER.LOG_LEVELS_GRANULAR, - }; - - const logger = Logger.createInstance(loggerConfig); + }); await logger.initialize(); - const httpClientConfig: HttpClientConfig = { + const httpLoggerInstance = logger.getLogger("HttpClient"); + const httpClient = HttpClient.createInstance(httpLoggerInstance, { retryDelay: globalConfig.HTTPCLIENT.RETRY_DELAY, maxRetries: globalConfig.HTTPCLIENT.MAX_RETRIES, defaultTimeout: globalConfig.HTTPCLIENT.DEFAULT_TIMEOUT, - }; + }); - const httpLoggerInstance = logger.getLogger("HttpClient"); - const httpClient = HttpClient.getInstance(httpLoggerInstance, httpClientConfig); - const httpQueue = HttpClient.getQueueInstance(httpLoggerInstance, httpClientConfig); - httpClient.initialize(); - httpQueue.initialize(); + await httpClient.initialize(); const blockCheckpointManagerConfig: BlockCheckpointManagerConfig = { useCheckpoints: globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS, @@ -75,6 +68,7 @@ export async function initializeManagers(): Promise { rpcOverrides: globalConfig.RPC.OVERRIDE, rpcExtensions: globalConfig.RPC.EXTENSION, conceroRpcsUrl: globalConfig.URLS.CONCERO_RPCS, + networkMode: globalConfig.NETWORK_MODE as "mainnet" | "testnet" | "localhost", }; const viemClientManagerConfig: ViemClientManagerConfig = { @@ -121,8 +115,6 @@ export async function initializeManagers(): Promise { const networkManager = NetworkManager.createInstance( logger.getLogger("NetworkManager"), networkManagerConfig, - rpcManager, - deploymentManager, ); const blockCheckpointManager = BlockCheckpointManager.createInstance( logger.getLogger("BlockCheckpointManager"), @@ -138,13 +130,19 @@ export async function initializeManagers(): Promise { blockManagerRegistryConfig, ); + await networkManager.initialize(); await rpcManager.initialize(); await viemClientManager.initialize(); await deploymentManager.initialize(); - await networkManager.initialize(); + + // Register network update listeners after all managers are initialized + networkManager.registerUpdateListener(rpcManager); + networkManager.registerUpdateListener(deploymentManager); + networkManager.registerUpdateListener(viemClientManager); + networkManager.registerUpdateListener(blockManagerRegistry); + await blockCheckpointManager.initialize(); await blockManagerRegistry.initialize(); - const txWriter = TxWriter.createInstance( logger.getLogger("TxWriter"), networkManager, diff --git a/src/constants/globalConfig.ts b/src/constants/globalConfig.ts index 8adb059..97d13c4 100644 --- a/src/constants/globalConfig.ts +++ b/src/constants/globalConfig.ts @@ -26,7 +26,7 @@ const globalConfig: GlobalConfig = { LOG_MAX_SIZE: "20m", }, URLS: { - CONCERO_RPCS: `https://raw.githubusercontent.com/concero/rpcs/refs/heads/${process.env.RPC_SERVICE_GIT_BRANCH ?? "master"}/output/`, + CONCERO_RPCS: `https://raw.githubusercontent.com/concero/rpcs/refs/heads/${process.env.RPC_SERVICE_GIT_BRANCH ?? "master"}/output`, CONCERO_DEPLOYMENTS: `https://raw.githubusercontent.com/concero/v2-contracts/refs/heads/${process.env.DEPLOYMENTS_SERVICE_GIT_BRANCH ?? "master"}/.env.deployments.${getEnvVar("NETWORK_MODE") === "localhost" || getEnvVar("NETWORK_MODE") === "testnet" ? "testnet" : "mainnet"}`, V2_NETWORKS: { MAINNET: diff --git a/src/types/ManagerConfigs.ts b/src/types/ManagerConfigs.ts index a6f54ca..c0aa3ba 100644 --- a/src/types/ManagerConfigs.ts +++ b/src/types/ManagerConfigs.ts @@ -31,6 +31,7 @@ export interface RpcManagerConfig extends BaseManagerConfig { rpcOverrides: Record; rpcExtensions: Record; conceroRpcsUrl: string; + networkMode: "mainnet" | "testnet" | "localhost"; } /** Configuration for DeploymentManager */ From a4565b2bd6be9bd2bca2c58d483ffc61ed16afbb Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 19 Jul 2025 14:42:55 +0100 Subject: [PATCH 02/11] upd --- dist/index.js | 113961 +++++++++-------- src/common/managers/BlockManagerRegistry.ts | 18 +- src/common/managers/DeploymentManager.ts | 12 +- src/common/managers/NetworkManager.ts | 26 +- src/common/managers/RpcManager.ts | 59 +- src/common/managers/ViemClientManager.ts | 20 +- src/common/utils/initializeManagers.ts | 8 +- src/constants/globalConfig.ts | 2 +- src/types/managers/INetworkManager.ts | 1 + src/types/managers/IRpcManager.ts | 4 - src/types/managers/IViemClientManager.ts | 4 +- src/types/managers/NetworkUpdateListener.ts | 2 +- src/types/managers/RpcUpdateListener.ts | 3 - src/types/managers/index.ts | 1 - 14 files changed, 57084 insertions(+), 57037 deletions(-) delete mode 100644 src/types/managers/RpcUpdateListener.ts diff --git a/dist/index.js b/dist/index.js index 861ecce..bc24e85 100644 --- a/dist/index.js +++ b/dist/index.js @@ -372,31375 +372,17136 @@ var require_main = __commonJS({ } }); -// node_modules/delayed-stream/lib/delayed_stream.js -var require_delayed_stream = __commonJS({ - "node_modules/delayed-stream/lib/delayed_stream.js"(exports2, module2) { - var Stream = __require("stream").Stream; - var util3 = __require("util"); - module2.exports = DelayedStream; - function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; - } - util3.inherits(DelayedStream, Stream); - DelayedStream.create = function(source, options) { - var delayedStream = new this(); - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; - } - delayedStream.source = source; - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; - source.on("error", function() { - }); - if (delayedStream.pauseStream) { - source.pause(); - } - return delayedStream; - }; - Object.defineProperty(DelayedStream.prototype, "readable", { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; +// node_modules/logform/format.js +var require_format = __commonJS({ + "node_modules/logform/format.js"(exports2, module2) { + "use strict"; + var InvalidFormatError = class _InvalidFormatError extends Error { + constructor(formatFn) { + super(`Format functions must be synchronous taking a two arguments: (info, opts) +Found: ${formatFn.toString().split("\n")[0]} +`); + Error.captureStackTrace(this, _InvalidFormatError); } - }); - DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); }; - DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); + module2.exports = (formatFn) => { + if (formatFn.length > 2) { + throw new InvalidFormatError(formatFn); } - this.source.resume(); - }; - DelayedStream.prototype.pause = function() { - this.source.pause(); - }; - DelayedStream.prototype.release = function() { - this._released = true; - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; - }; - DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; - }; - DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; + function Format(options = {}) { + this.options = options; } - if (args[0] === "data") { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); + Format.prototype.transform = formatFn; + function createFormatWrap(opts) { + return new Format(opts); } - this._bufferedEvents.push(args); + createFormatWrap.Format = Format; + return createFormatWrap; }; - DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } - if (this.dataSize <= this.maxDataSize) { - return; - } - this._maxDataSizeExceeded = true; - var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; - this.emit("error", new Error(message)); + } +}); + +// node_modules/@colors/colors/lib/styles.js +var require_styles = __commonJS({ + "node_modules/@colors/colors/lib/styles.js"(exports2, module2) { + var styles = {}; + module2["exports"] = styles; + var codes = { + reset: [0, 0], + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 39], + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + bgGray: [100, 49], + bgGrey: [100, 49], + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 49], + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49] }; + Object.keys(codes).forEach(function(key) { + var val = codes[key]; + var style = styles[key] = []; + style.open = "\x1B[" + val[0] + "m"; + style.close = "\x1B[" + val[1] + "m"; + }); } }); -// node_modules/combined-stream/lib/combined_stream.js -var require_combined_stream = __commonJS({ - "node_modules/combined-stream/lib/combined_stream.js"(exports2, module2) { - var util3 = __require("util"); - var Stream = __require("stream").Stream; - var DelayedStream = require_delayed_stream(); - module2.exports = CombinedStream; - function CombinedStream() { - this.writable = false; - this.readable = true; - this.dataSize = 0; - this.maxDataSize = 2 * 1024 * 1024; - this.pauseStreams = true; - this._released = false; - this._streams = []; - this._currentStream = null; - this._insideLoop = false; - this._pendingNext = false; +// node_modules/@colors/colors/lib/system/has-flag.js +var require_has_flag = __commonJS({ + "node_modules/@colors/colors/lib/system/has-flag.js"(exports2, module2) { + "use strict"; + module2.exports = function(flag, argv) { + argv = argv || process.argv || []; + var terminatorPos = argv.indexOf("--"); + var prefix = /^-{1,2}/.test(flag) ? "" : "--"; + var pos = argv.indexOf(prefix + flag); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + }; + } +}); + +// node_modules/@colors/colors/lib/system/supports-colors.js +var require_supports_colors = __commonJS({ + "node_modules/@colors/colors/lib/system/supports-colors.js"(exports2, module2) { + "use strict"; + var os2 = __require("os"); + var hasFlag = require_has_flag(); + var env = process.env; + var forceColor = void 0; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false")) { + forceColor = false; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + forceColor = true; } - util3.inherits(CombinedStream, Stream); - CombinedStream.create = function(options) { - var combinedStream = new this(); - options = options || {}; - for (var option in options) { - combinedStream[option] = options[option]; + if ("FORCE_COLOR" in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; + } + function translateLevel(level) { + if (level === 0) { + return false; } - return combinedStream; - }; - CombinedStream.isStreamLike = function(stream4) { - return typeof stream4 !== "function" && typeof stream4 !== "string" && typeof stream4 !== "boolean" && typeof stream4 !== "number" && !Buffer.isBuffer(stream4); - }; - CombinedStream.prototype.append = function(stream4) { - var isStreamLike = CombinedStream.isStreamLike(stream4); - if (isStreamLike) { - if (!(stream4 instanceof DelayedStream)) { - var newStream = DelayedStream.create(stream4, { - maxDataSize: Infinity, - pauseStream: this.pauseStreams - }); - stream4.on("data", this._checkDataSize.bind(this)); - stream4 = newStream; - } - this._handleErrors(stream4); - if (this.pauseStreams) { - stream4.pause(); - } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + function supportsColor(stream4) { + if (forceColor === false) { + return 0; } - this._streams.push(stream4); - return this; - }; - CombinedStream.prototype.pipe = function(dest, options) { - Stream.prototype.pipe.call(this, dest, options); - this.resume(); - return dest; - }; - CombinedStream.prototype._getNext = function() { - this._currentStream = null; - if (this._insideLoop) { - this._pendingNext = true; - return; + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; } - this._insideLoop = true; - try { - do { - this._pendingNext = false; - this._realGetNext(); - } while (this._pendingNext); - } finally { - this._insideLoop = false; + if (hasFlag("color=256")) { + return 2; } - }; - CombinedStream.prototype._realGetNext = function() { - var stream4 = this._streams.shift(); - if (typeof stream4 == "undefined") { - this.end(); - return; + if (stream4 && !stream4.isTTY && forceColor !== true) { + return 0; } - if (typeof stream4 !== "function") { - this._pipeNext(stream4); - return; + var min = forceColor ? 1 : 0; + if (process.platform === "win32") { + var osRelease = os2.release().split("."); + if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + return 1; } - var getStream = stream4; - getStream(function(stream5) { - var isStreamLike = CombinedStream.isStreamLike(stream5); - if (isStreamLike) { - stream5.on("data", this._checkDataSize.bind(this)); - this._handleErrors(stream5); + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign2) { + return sign2 in env; + }) || env.CI_NAME === "codeship") { + return 1; } - this._pipeNext(stream5); - }.bind(this)); - }; - CombinedStream.prototype._pipeNext = function(stream4) { - this._currentStream = stream4; - var isStreamLike = CombinedStream.isStreamLike(stream4); - if (isStreamLike) { - stream4.on("end", this._getNext.bind(this)); - stream4.pipe(this, { end: false }); - return; + return min; } - var value = stream4; - this.write(value); - this._getNext(); - }; - CombinedStream.prototype._handleErrors = function(stream4) { - var self2 = this; - stream4.on("error", function(err) { - self2._emitError(err); - }); - }; - CombinedStream.prototype.write = function(data) { - this.emit("data", data); - }; - CombinedStream.prototype.pause = function() { - if (!this.pauseStreams) { - return; + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } - if (this.pauseStreams && this._currentStream && typeof this._currentStream.pause == "function") this._currentStream.pause(); - this.emit("pause"); - }; - CombinedStream.prototype.resume = function() { - if (!this._released) { - this._released = true; - this.writable = true; - this._getNext(); + if ("TERM_PROGRAM" in env) { + var version4 = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version4 >= 3 ? 3 : 2; + case "Hyper": + return 3; + case "Apple_Terminal": + return 2; + } } - if (this.pauseStreams && this._currentStream && typeof this._currentStream.resume == "function") this._currentStream.resume(); - this.emit("resume"); - }; - CombinedStream.prototype.end = function() { - this._reset(); - this.emit("end"); - }; - CombinedStream.prototype.destroy = function() { - this._reset(); - this.emit("close"); - }; - CombinedStream.prototype._reset = function() { - this.writable = false; - this._streams = []; - this._currentStream = null; - }; - CombinedStream.prototype._checkDataSize = function() { - this._updateDataSize(); - if (this.dataSize <= this.maxDataSize) { - return; + if (/-256(color)?$/i.test(env.TERM)) { + return 2; } - var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; - this._emitError(new Error(message)); + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + if (env.TERM === "dumb") { + return min; + } + return min; + } + function getSupportLevel(stream4) { + var level = supportsColor(stream4); + return translateLevel(level); + } + module2.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) }; - CombinedStream.prototype._updateDataSize = function() { - this.dataSize = 0; - var self2 = this; - this._streams.forEach(function(stream4) { - if (!stream4.dataSize) { - return; + } +}); + +// node_modules/@colors/colors/lib/custom/trap.js +var require_trap = __commonJS({ + "node_modules/@colors/colors/lib/custom/trap.js"(exports2, module2) { + module2["exports"] = function runTheTrap(text, options) { + var result = ""; + text = text || "Run the trap, drop the bass"; + text = text.split(""); + var trap = { + a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"], + b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"], + c: ["\xA9", "\u023B", "\u03FE"], + d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"], + e: [ + "\xCB", + "\u0115", + "\u018E", + "\u0258", + "\u03A3", + "\u03BE", + "\u04BC", + "\u0A6C" + ], + f: ["\u04FA"], + g: ["\u0262"], + h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"], + i: ["\u0F0F"], + j: ["\u0134"], + k: ["\u0138", "\u04A0", "\u04C3", "\u051E"], + l: ["\u0139"], + m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"], + n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"], + o: [ + "\xD8", + "\xF5", + "\xF8", + "\u01FE", + "\u0298", + "\u047A", + "\u05DD", + "\u06DD", + "\u0E4F" + ], + p: ["\u01F7", "\u048E"], + q: ["\u09CD"], + r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"], + s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"], + t: ["\u0141", "\u0166", "\u0373"], + u: ["\u01B1", "\u054D"], + v: ["\u05D8"], + w: ["\u0428", "\u0460", "\u047C", "\u0D70"], + x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"], + y: ["\xA5", "\u04B0", "\u04CB"], + z: ["\u01B5", "\u0240"] + }; + text.forEach(function(c) { + c = c.toLowerCase(); + var chars = trap[c] || [" "]; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap[c] !== "undefined") { + result += trap[c][rand]; + } else { + result += c; } - self2.dataSize += stream4.dataSize; }); - if (this._currentStream && this._currentStream.dataSize) { - this.dataSize += this._currentStream.dataSize; - } - }; - CombinedStream.prototype._emitError = function(err) { - this._reset(); - this.emit("error", err); + return result; }; } }); -// node_modules/mime-db/db.json -var require_db = __commonJS({ - "node_modules/mime-db/db.json"(exports2, module2) { - module2.exports = { - "application/1d-interleaved-parityfec": { - source: "iana" - }, - "application/3gpdash-qoe-report+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/3gpp-ims+xml": { - source: "iana", - compressible: true - }, - "application/3gpphal+json": { - source: "iana", - compressible: true - }, - "application/3gpphalforms+json": { - source: "iana", - compressible: true - }, - "application/a2l": { - source: "iana" - }, - "application/ace+cbor": { - source: "iana" - }, - "application/activemessage": { - source: "iana" - }, - "application/activity+json": { - source: "iana", - compressible: true - }, - "application/alto-costmap+json": { - source: "iana", - compressible: true - }, - "application/alto-costmapfilter+json": { - source: "iana", - compressible: true - }, - "application/alto-directory+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointcost+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointcostparams+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointprop+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointpropparams+json": { - source: "iana", - compressible: true - }, - "application/alto-error+json": { - source: "iana", - compressible: true - }, - "application/alto-networkmap+json": { - source: "iana", - compressible: true - }, - "application/alto-networkmapfilter+json": { - source: "iana", - compressible: true - }, - "application/alto-updatestreamcontrol+json": { - source: "iana", - compressible: true - }, - "application/alto-updatestreamparams+json": { - source: "iana", - compressible: true - }, - "application/aml": { - source: "iana" - }, - "application/andrew-inset": { - source: "iana", - extensions: ["ez"] - }, - "application/applefile": { - source: "iana" - }, - "application/applixware": { - source: "apache", - extensions: ["aw"] - }, - "application/at+jwt": { - source: "iana" - }, - "application/atf": { - source: "iana" - }, - "application/atfx": { - source: "iana" - }, - "application/atom+xml": { - source: "iana", - compressible: true, - extensions: ["atom"] - }, - "application/atomcat+xml": { - source: "iana", - compressible: true, - extensions: ["atomcat"] - }, - "application/atomdeleted+xml": { - source: "iana", - compressible: true, - extensions: ["atomdeleted"] - }, - "application/atomicmail": { - source: "iana" - }, - "application/atomsvc+xml": { - source: "iana", - compressible: true, - extensions: ["atomsvc"] - }, - "application/atsc-dwd+xml": { - source: "iana", - compressible: true, - extensions: ["dwd"] - }, - "application/atsc-dynamic-event-message": { - source: "iana" - }, - "application/atsc-held+xml": { - source: "iana", - compressible: true, - extensions: ["held"] - }, - "application/atsc-rdt+json": { - source: "iana", - compressible: true - }, - "application/atsc-rsat+xml": { - source: "iana", - compressible: true, - extensions: ["rsat"] - }, - "application/atxml": { - source: "iana" - }, - "application/auth-policy+xml": { - source: "iana", - compressible: true - }, - "application/bacnet-xdd+zip": { - source: "iana", - compressible: false - }, - "application/batch-smtp": { - source: "iana" - }, - "application/bdoc": { - compressible: false, - extensions: ["bdoc"] - }, - "application/beep+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/calendar+json": { - source: "iana", - compressible: true - }, - "application/calendar+xml": { - source: "iana", - compressible: true, - extensions: ["xcs"] - }, - "application/call-completion": { - source: "iana" - }, - "application/cals-1840": { - source: "iana" - }, - "application/captive+json": { - source: "iana", - compressible: true - }, - "application/cbor": { - source: "iana" - }, - "application/cbor-seq": { - source: "iana" - }, - "application/cccex": { - source: "iana" - }, - "application/ccmp+xml": { - source: "iana", - compressible: true - }, - "application/ccxml+xml": { - source: "iana", - compressible: true, - extensions: ["ccxml"] - }, - "application/cdfx+xml": { - source: "iana", - compressible: true, - extensions: ["cdfx"] - }, - "application/cdmi-capability": { - source: "iana", - extensions: ["cdmia"] - }, - "application/cdmi-container": { - source: "iana", - extensions: ["cdmic"] - }, - "application/cdmi-domain": { - source: "iana", - extensions: ["cdmid"] - }, - "application/cdmi-object": { - source: "iana", - extensions: ["cdmio"] - }, - "application/cdmi-queue": { - source: "iana", - extensions: ["cdmiq"] - }, - "application/cdni": { - source: "iana" - }, - "application/cea": { - source: "iana" - }, - "application/cea-2018+xml": { - source: "iana", - compressible: true - }, - "application/cellml+xml": { - source: "iana", - compressible: true - }, - "application/cfw": { - source: "iana" - }, - "application/city+json": { - source: "iana", - compressible: true - }, - "application/clr": { - source: "iana" - }, - "application/clue+xml": { - source: "iana", - compressible: true - }, - "application/clue_info+xml": { - source: "iana", - compressible: true - }, - "application/cms": { - source: "iana" - }, - "application/cnrp+xml": { - source: "iana", - compressible: true - }, - "application/coap-group+json": { - source: "iana", - compressible: true - }, - "application/coap-payload": { - source: "iana" - }, - "application/commonground": { - source: "iana" - }, - "application/conference-info+xml": { - source: "iana", - compressible: true - }, - "application/cose": { - source: "iana" - }, - "application/cose-key": { - source: "iana" - }, - "application/cose-key-set": { - source: "iana" - }, - "application/cpl+xml": { - source: "iana", - compressible: true, - extensions: ["cpl"] - }, - "application/csrattrs": { - source: "iana" - }, - "application/csta+xml": { - source: "iana", - compressible: true - }, - "application/cstadata+xml": { - source: "iana", - compressible: true - }, - "application/csvm+json": { - source: "iana", - compressible: true - }, - "application/cu-seeme": { - source: "apache", - extensions: ["cu"] - }, - "application/cwt": { - source: "iana" - }, - "application/cybercash": { - source: "iana" - }, - "application/dart": { - compressible: true - }, - "application/dash+xml": { - source: "iana", - compressible: true, - extensions: ["mpd"] - }, - "application/dash-patch+xml": { - source: "iana", - compressible: true, - extensions: ["mpp"] - }, - "application/dashdelta": { - source: "iana" - }, - "application/davmount+xml": { - source: "iana", - compressible: true, - extensions: ["davmount"] - }, - "application/dca-rft": { - source: "iana" - }, - "application/dcd": { - source: "iana" - }, - "application/dec-dx": { - source: "iana" - }, - "application/dialog-info+xml": { - source: "iana", - compressible: true - }, - "application/dicom": { - source: "iana" - }, - "application/dicom+json": { - source: "iana", - compressible: true - }, - "application/dicom+xml": { - source: "iana", - compressible: true - }, - "application/dii": { - source: "iana" - }, - "application/dit": { - source: "iana" - }, - "application/dns": { - source: "iana" - }, - "application/dns+json": { - source: "iana", - compressible: true - }, - "application/dns-message": { - source: "iana" - }, - "application/docbook+xml": { - source: "apache", - compressible: true, - extensions: ["dbk"] - }, - "application/dots+cbor": { - source: "iana" - }, - "application/dskpp+xml": { - source: "iana", - compressible: true - }, - "application/dssc+der": { - source: "iana", - extensions: ["dssc"] - }, - "application/dssc+xml": { - source: "iana", - compressible: true, - extensions: ["xdssc"] - }, - "application/dvcs": { - source: "iana" - }, - "application/ecmascript": { - source: "iana", - compressible: true, - extensions: ["es", "ecma"] - }, - "application/edi-consent": { - source: "iana" - }, - "application/edi-x12": { - source: "iana", - compressible: false - }, - "application/edifact": { - source: "iana", - compressible: false - }, - "application/efi": { - source: "iana" - }, - "application/elm+json": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/elm+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.cap+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/emergencycalldata.comment+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.control+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.deviceinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.ecall.msd": { - source: "iana" - }, - "application/emergencycalldata.providerinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.serviceinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.subscriberinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.veds+xml": { - source: "iana", - compressible: true - }, - "application/emma+xml": { - source: "iana", - compressible: true, - extensions: ["emma"] - }, - "application/emotionml+xml": { - source: "iana", - compressible: true, - extensions: ["emotionml"] - }, - "application/encaprtp": { - source: "iana" - }, - "application/epp+xml": { - source: "iana", - compressible: true - }, - "application/epub+zip": { - source: "iana", - compressible: false, - extensions: ["epub"] - }, - "application/eshop": { - source: "iana" - }, - "application/exi": { - source: "iana", - extensions: ["exi"] - }, - "application/expect-ct-report+json": { - source: "iana", - compressible: true - }, - "application/express": { - source: "iana", - extensions: ["exp"] - }, - "application/fastinfoset": { - source: "iana" - }, - "application/fastsoap": { - source: "iana" - }, - "application/fdt+xml": { - source: "iana", - compressible: true, - extensions: ["fdt"] - }, - "application/fhir+json": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/fhir+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/fido.trusted-apps+json": { - compressible: true - }, - "application/fits": { - source: "iana" - }, - "application/flexfec": { - source: "iana" - }, - "application/font-sfnt": { - source: "iana" - }, - "application/font-tdpfr": { - source: "iana", - extensions: ["pfr"] - }, - "application/font-woff": { - source: "iana", - compressible: false - }, - "application/framework-attributes+xml": { - source: "iana", - compressible: true - }, - "application/geo+json": { - source: "iana", - compressible: true, - extensions: ["geojson"] - }, - "application/geo+json-seq": { - source: "iana" - }, - "application/geopackage+sqlite3": { - source: "iana" - }, - "application/geoxacml+xml": { - source: "iana", - compressible: true - }, - "application/gltf-buffer": { - source: "iana" - }, - "application/gml+xml": { - source: "iana", - compressible: true, - extensions: ["gml"] - }, - "application/gpx+xml": { - source: "apache", - compressible: true, - extensions: ["gpx"] - }, - "application/gxf": { - source: "apache", - extensions: ["gxf"] - }, - "application/gzip": { - source: "iana", - compressible: false, - extensions: ["gz"] - }, - "application/h224": { - source: "iana" - }, - "application/held+xml": { - source: "iana", - compressible: true - }, - "application/hjson": { - extensions: ["hjson"] - }, - "application/http": { - source: "iana" - }, - "application/hyperstudio": { - source: "iana", - extensions: ["stk"] - }, - "application/ibe-key-request+xml": { - source: "iana", - compressible: true - }, - "application/ibe-pkg-reply+xml": { - source: "iana", - compressible: true - }, - "application/ibe-pp-data": { - source: "iana" - }, - "application/iges": { - source: "iana" - }, - "application/im-iscomposing+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/index": { - source: "iana" - }, - "application/index.cmd": { - source: "iana" - }, - "application/index.obj": { - source: "iana" - }, - "application/index.response": { - source: "iana" - }, - "application/index.vnd": { - source: "iana" - }, - "application/inkml+xml": { - source: "iana", - compressible: true, - extensions: ["ink", "inkml"] - }, - "application/iotp": { - source: "iana" - }, - "application/ipfix": { - source: "iana", - extensions: ["ipfix"] - }, - "application/ipp": { - source: "iana" - }, - "application/isup": { - source: "iana" - }, - "application/its+xml": { - source: "iana", - compressible: true, - extensions: ["its"] - }, - "application/java-archive": { - source: "apache", - compressible: false, - extensions: ["jar", "war", "ear"] - }, - "application/java-serialized-object": { - source: "apache", - compressible: false, - extensions: ["ser"] - }, - "application/java-vm": { - source: "apache", - compressible: false, - extensions: ["class"] - }, - "application/javascript": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["js", "mjs"] - }, - "application/jf2feed+json": { - source: "iana", - compressible: true - }, - "application/jose": { - source: "iana" - }, - "application/jose+json": { - source: "iana", - compressible: true - }, - "application/jrd+json": { - source: "iana", - compressible: true - }, - "application/jscalendar+json": { - source: "iana", - compressible: true - }, - "application/json": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["json", "map"] - }, - "application/json-patch+json": { - source: "iana", - compressible: true - }, - "application/json-seq": { - source: "iana" - }, - "application/json5": { - extensions: ["json5"] - }, - "application/jsonml+json": { - source: "apache", - compressible: true, - extensions: ["jsonml"] - }, - "application/jwk+json": { - source: "iana", - compressible: true - }, - "application/jwk-set+json": { - source: "iana", - compressible: true - }, - "application/jwt": { - source: "iana" - }, - "application/kpml-request+xml": { - source: "iana", - compressible: true - }, - "application/kpml-response+xml": { - source: "iana", - compressible: true - }, - "application/ld+json": { - source: "iana", - compressible: true, - extensions: ["jsonld"] - }, - "application/lgr+xml": { - source: "iana", - compressible: true, - extensions: ["lgr"] - }, - "application/link-format": { - source: "iana" - }, - "application/load-control+xml": { - source: "iana", - compressible: true - }, - "application/lost+xml": { - source: "iana", - compressible: true, - extensions: ["lostxml"] - }, - "application/lostsync+xml": { - source: "iana", - compressible: true - }, - "application/lpf+zip": { - source: "iana", - compressible: false - }, - "application/lxf": { - source: "iana" - }, - "application/mac-binhex40": { - source: "iana", - extensions: ["hqx"] - }, - "application/mac-compactpro": { - source: "apache", - extensions: ["cpt"] - }, - "application/macwriteii": { - source: "iana" - }, - "application/mads+xml": { - source: "iana", - compressible: true, - extensions: ["mads"] - }, - "application/manifest+json": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["webmanifest"] - }, - "application/marc": { - source: "iana", - extensions: ["mrc"] - }, - "application/marcxml+xml": { - source: "iana", - compressible: true, - extensions: ["mrcx"] - }, - "application/mathematica": { - source: "iana", - extensions: ["ma", "nb", "mb"] - }, - "application/mathml+xml": { - source: "iana", - compressible: true, - extensions: ["mathml"] - }, - "application/mathml-content+xml": { - source: "iana", - compressible: true - }, - "application/mathml-presentation+xml": { - source: "iana", - compressible: true - }, - "application/mbms-associated-procedure-description+xml": { - source: "iana", - compressible: true - }, - "application/mbms-deregister+xml": { - source: "iana", - compressible: true - }, - "application/mbms-envelope+xml": { - source: "iana", - compressible: true - }, - "application/mbms-msk+xml": { - source: "iana", - compressible: true - }, - "application/mbms-msk-response+xml": { - source: "iana", - compressible: true - }, - "application/mbms-protection-description+xml": { - source: "iana", - compressible: true - }, - "application/mbms-reception-report+xml": { - source: "iana", - compressible: true - }, - "application/mbms-register+xml": { - source: "iana", - compressible: true - }, - "application/mbms-register-response+xml": { - source: "iana", - compressible: true - }, - "application/mbms-schedule+xml": { - source: "iana", - compressible: true - }, - "application/mbms-user-service-description+xml": { - source: "iana", - compressible: true - }, - "application/mbox": { - source: "iana", - extensions: ["mbox"] - }, - "application/media-policy-dataset+xml": { - source: "iana", - compressible: true, - extensions: ["mpf"] - }, - "application/media_control+xml": { - source: "iana", - compressible: true - }, - "application/mediaservercontrol+xml": { - source: "iana", - compressible: true, - extensions: ["mscml"] - }, - "application/merge-patch+json": { - source: "iana", - compressible: true - }, - "application/metalink+xml": { - source: "apache", - compressible: true, - extensions: ["metalink"] - }, - "application/metalink4+xml": { - source: "iana", - compressible: true, - extensions: ["meta4"] - }, - "application/mets+xml": { - source: "iana", - compressible: true, - extensions: ["mets"] - }, - "application/mf4": { - source: "iana" - }, - "application/mikey": { - source: "iana" - }, - "application/mipc": { - source: "iana" - }, - "application/missing-blocks+cbor-seq": { - source: "iana" - }, - "application/mmt-aei+xml": { - source: "iana", - compressible: true, - extensions: ["maei"] - }, - "application/mmt-usd+xml": { - source: "iana", - compressible: true, - extensions: ["musd"] - }, - "application/mods+xml": { - source: "iana", - compressible: true, - extensions: ["mods"] - }, - "application/moss-keys": { - source: "iana" - }, - "application/moss-signature": { - source: "iana" - }, - "application/mosskey-data": { - source: "iana" - }, - "application/mosskey-request": { - source: "iana" - }, - "application/mp21": { - source: "iana", - extensions: ["m21", "mp21"] - }, - "application/mp4": { - source: "iana", - extensions: ["mp4s", "m4p"] - }, - "application/mpeg4-generic": { - source: "iana" - }, - "application/mpeg4-iod": { - source: "iana" - }, - "application/mpeg4-iod-xmt": { - source: "iana" - }, - "application/mrb-consumer+xml": { - source: "iana", - compressible: true - }, - "application/mrb-publish+xml": { - source: "iana", - compressible: true - }, - "application/msc-ivr+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/msc-mixer+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/msword": { - source: "iana", - compressible: false, - extensions: ["doc", "dot"] - }, - "application/mud+json": { - source: "iana", - compressible: true - }, - "application/multipart-core": { - source: "iana" - }, - "application/mxf": { - source: "iana", - extensions: ["mxf"] - }, - "application/n-quads": { - source: "iana", - extensions: ["nq"] - }, - "application/n-triples": { - source: "iana", - extensions: ["nt"] - }, - "application/nasdata": { - source: "iana" - }, - "application/news-checkgroups": { - source: "iana", - charset: "US-ASCII" - }, - "application/news-groupinfo": { - source: "iana", - charset: "US-ASCII" - }, - "application/news-transmission": { - source: "iana" - }, - "application/nlsml+xml": { - source: "iana", - compressible: true - }, - "application/node": { - source: "iana", - extensions: ["cjs"] - }, - "application/nss": { - source: "iana" - }, - "application/oauth-authz-req+jwt": { - source: "iana" - }, - "application/oblivious-dns-message": { - source: "iana" - }, - "application/ocsp-request": { - source: "iana" - }, - "application/ocsp-response": { - source: "iana" - }, - "application/octet-stream": { - source: "iana", - compressible: false, - extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"] - }, - "application/oda": { - source: "iana", - extensions: ["oda"] - }, - "application/odm+xml": { - source: "iana", - compressible: true - }, - "application/odx": { - source: "iana" - }, - "application/oebps-package+xml": { - source: "iana", - compressible: true, - extensions: ["opf"] - }, - "application/ogg": { - source: "iana", - compressible: false, - extensions: ["ogx"] - }, - "application/omdoc+xml": { - source: "apache", - compressible: true, - extensions: ["omdoc"] - }, - "application/onenote": { - source: "apache", - extensions: ["onetoc", "onetoc2", "onetmp", "onepkg"] - }, - "application/opc-nodeset+xml": { - source: "iana", - compressible: true - }, - "application/oscore": { - source: "iana" - }, - "application/oxps": { - source: "iana", - extensions: ["oxps"] - }, - "application/p21": { - source: "iana" - }, - "application/p21+zip": { - source: "iana", - compressible: false - }, - "application/p2p-overlay+xml": { - source: "iana", - compressible: true, - extensions: ["relo"] - }, - "application/parityfec": { - source: "iana" - }, - "application/passport": { - source: "iana" - }, - "application/patch-ops-error+xml": { - source: "iana", - compressible: true, - extensions: ["xer"] - }, - "application/pdf": { - source: "iana", - compressible: false, - extensions: ["pdf"] - }, - "application/pdx": { - source: "iana" - }, - "application/pem-certificate-chain": { - source: "iana" - }, - "application/pgp-encrypted": { - source: "iana", - compressible: false, - extensions: ["pgp"] - }, - "application/pgp-keys": { - source: "iana", - extensions: ["asc"] - }, - "application/pgp-signature": { - source: "iana", - extensions: ["asc", "sig"] - }, - "application/pics-rules": { - source: "apache", - extensions: ["prf"] - }, - "application/pidf+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/pidf-diff+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/pkcs10": { - source: "iana", - extensions: ["p10"] - }, - "application/pkcs12": { - source: "iana" - }, - "application/pkcs7-mime": { - source: "iana", - extensions: ["p7m", "p7c"] - }, - "application/pkcs7-signature": { - source: "iana", - extensions: ["p7s"] - }, - "application/pkcs8": { - source: "iana", - extensions: ["p8"] - }, - "application/pkcs8-encrypted": { - source: "iana" - }, - "application/pkix-attr-cert": { - source: "iana", - extensions: ["ac"] - }, - "application/pkix-cert": { - source: "iana", - extensions: ["cer"] - }, - "application/pkix-crl": { - source: "iana", - extensions: ["crl"] - }, - "application/pkix-pkipath": { - source: "iana", - extensions: ["pkipath"] - }, - "application/pkixcmp": { - source: "iana", - extensions: ["pki"] - }, - "application/pls+xml": { - source: "iana", - compressible: true, - extensions: ["pls"] - }, - "application/poc-settings+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/postscript": { - source: "iana", - compressible: true, - extensions: ["ai", "eps", "ps"] - }, - "application/ppsp-tracker+json": { - source: "iana", - compressible: true - }, - "application/problem+json": { - source: "iana", - compressible: true - }, - "application/problem+xml": { - source: "iana", - compressible: true - }, - "application/provenance+xml": { - source: "iana", - compressible: true, - extensions: ["provx"] - }, - "application/prs.alvestrand.titrax-sheet": { - source: "iana" - }, - "application/prs.cww": { - source: "iana", - extensions: ["cww"] - }, - "application/prs.cyn": { - source: "iana", - charset: "7-BIT" - }, - "application/prs.hpub+zip": { - source: "iana", - compressible: false - }, - "application/prs.nprend": { - source: "iana" - }, - "application/prs.plucker": { - source: "iana" - }, - "application/prs.rdf-xml-crypt": { - source: "iana" - }, - "application/prs.xsf+xml": { - source: "iana", - compressible: true - }, - "application/pskc+xml": { - source: "iana", - compressible: true, - extensions: ["pskcxml"] - }, - "application/pvd+json": { - source: "iana", - compressible: true - }, - "application/qsig": { - source: "iana" - }, - "application/raml+yaml": { - compressible: true, - extensions: ["raml"] - }, - "application/raptorfec": { - source: "iana" - }, - "application/rdap+json": { - source: "iana", - compressible: true - }, - "application/rdf+xml": { - source: "iana", - compressible: true, - extensions: ["rdf", "owl"] - }, - "application/reginfo+xml": { - source: "iana", - compressible: true, - extensions: ["rif"] - }, - "application/relax-ng-compact-syntax": { - source: "iana", - extensions: ["rnc"] - }, - "application/remote-printing": { - source: "iana" - }, - "application/reputon+json": { - source: "iana", - compressible: true - }, - "application/resource-lists+xml": { - source: "iana", - compressible: true, - extensions: ["rl"] - }, - "application/resource-lists-diff+xml": { - source: "iana", - compressible: true, - extensions: ["rld"] - }, - "application/rfc+xml": { - source: "iana", - compressible: true - }, - "application/riscos": { - source: "iana" - }, - "application/rlmi+xml": { - source: "iana", - compressible: true - }, - "application/rls-services+xml": { - source: "iana", - compressible: true, - extensions: ["rs"] - }, - "application/route-apd+xml": { - source: "iana", - compressible: true, - extensions: ["rapd"] - }, - "application/route-s-tsid+xml": { - source: "iana", - compressible: true, - extensions: ["sls"] - }, - "application/route-usd+xml": { - source: "iana", - compressible: true, - extensions: ["rusd"] - }, - "application/rpki-ghostbusters": { - source: "iana", - extensions: ["gbr"] - }, - "application/rpki-manifest": { - source: "iana", - extensions: ["mft"] - }, - "application/rpki-publication": { - source: "iana" - }, - "application/rpki-roa": { - source: "iana", - extensions: ["roa"] - }, - "application/rpki-updown": { - source: "iana" - }, - "application/rsd+xml": { - source: "apache", - compressible: true, - extensions: ["rsd"] - }, - "application/rss+xml": { - source: "apache", - compressible: true, - extensions: ["rss"] - }, - "application/rtf": { - source: "iana", - compressible: true, - extensions: ["rtf"] - }, - "application/rtploopback": { - source: "iana" - }, - "application/rtx": { - source: "iana" - }, - "application/samlassertion+xml": { - source: "iana", - compressible: true - }, - "application/samlmetadata+xml": { - source: "iana", - compressible: true - }, - "application/sarif+json": { - source: "iana", - compressible: true - }, - "application/sarif-external-properties+json": { - source: "iana", - compressible: true - }, - "application/sbe": { - source: "iana" - }, - "application/sbml+xml": { - source: "iana", - compressible: true, - extensions: ["sbml"] - }, - "application/scaip+xml": { - source: "iana", - compressible: true - }, - "application/scim+json": { - source: "iana", - compressible: true - }, - "application/scvp-cv-request": { - source: "iana", - extensions: ["scq"] - }, - "application/scvp-cv-response": { - source: "iana", - extensions: ["scs"] - }, - "application/scvp-vp-request": { - source: "iana", - extensions: ["spq"] - }, - "application/scvp-vp-response": { - source: "iana", - extensions: ["spp"] - }, - "application/sdp": { - source: "iana", - extensions: ["sdp"] - }, - "application/secevent+jwt": { - source: "iana" - }, - "application/senml+cbor": { - source: "iana" - }, - "application/senml+json": { - source: "iana", - compressible: true - }, - "application/senml+xml": { - source: "iana", - compressible: true, - extensions: ["senmlx"] - }, - "application/senml-etch+cbor": { - source: "iana" - }, - "application/senml-etch+json": { - source: "iana", - compressible: true - }, - "application/senml-exi": { - source: "iana" - }, - "application/sensml+cbor": { - source: "iana" - }, - "application/sensml+json": { - source: "iana", - compressible: true - }, - "application/sensml+xml": { - source: "iana", - compressible: true, - extensions: ["sensmlx"] - }, - "application/sensml-exi": { - source: "iana" - }, - "application/sep+xml": { - source: "iana", - compressible: true - }, - "application/sep-exi": { - source: "iana" - }, - "application/session-info": { - source: "iana" - }, - "application/set-payment": { - source: "iana" - }, - "application/set-payment-initiation": { - source: "iana", - extensions: ["setpay"] - }, - "application/set-registration": { - source: "iana" - }, - "application/set-registration-initiation": { - source: "iana", - extensions: ["setreg"] - }, - "application/sgml": { - source: "iana" - }, - "application/sgml-open-catalog": { - source: "iana" - }, - "application/shf+xml": { - source: "iana", - compressible: true, - extensions: ["shf"] - }, - "application/sieve": { - source: "iana", - extensions: ["siv", "sieve"] - }, - "application/simple-filter+xml": { - source: "iana", - compressible: true - }, - "application/simple-message-summary": { - source: "iana" - }, - "application/simplesymbolcontainer": { - source: "iana" - }, - "application/sipc": { - source: "iana" - }, - "application/slate": { - source: "iana" - }, - "application/smil": { - source: "iana" - }, - "application/smil+xml": { - source: "iana", - compressible: true, - extensions: ["smi", "smil"] - }, - "application/smpte336m": { - source: "iana" - }, - "application/soap+fastinfoset": { - source: "iana" - }, - "application/soap+xml": { - source: "iana", - compressible: true - }, - "application/sparql-query": { - source: "iana", - extensions: ["rq"] - }, - "application/sparql-results+xml": { - source: "iana", - compressible: true, - extensions: ["srx"] - }, - "application/spdx+json": { - source: "iana", - compressible: true - }, - "application/spirits-event+xml": { - source: "iana", - compressible: true - }, - "application/sql": { - source: "iana" - }, - "application/srgs": { - source: "iana", - extensions: ["gram"] - }, - "application/srgs+xml": { - source: "iana", - compressible: true, - extensions: ["grxml"] - }, - "application/sru+xml": { - source: "iana", - compressible: true, - extensions: ["sru"] - }, - "application/ssdl+xml": { - source: "apache", - compressible: true, - extensions: ["ssdl"] - }, - "application/ssml+xml": { - source: "iana", - compressible: true, - extensions: ["ssml"] - }, - "application/stix+json": { - source: "iana", - compressible: true - }, - "application/swid+xml": { - source: "iana", - compressible: true, - extensions: ["swidtag"] - }, - "application/tamp-apex-update": { - source: "iana" - }, - "application/tamp-apex-update-confirm": { - source: "iana" - }, - "application/tamp-community-update": { - source: "iana" - }, - "application/tamp-community-update-confirm": { - source: "iana" - }, - "application/tamp-error": { - source: "iana" - }, - "application/tamp-sequence-adjust": { - source: "iana" - }, - "application/tamp-sequence-adjust-confirm": { - source: "iana" - }, - "application/tamp-status-query": { - source: "iana" - }, - "application/tamp-status-response": { - source: "iana" - }, - "application/tamp-update": { - source: "iana" - }, - "application/tamp-update-confirm": { - source: "iana" - }, - "application/tar": { - compressible: true - }, - "application/taxii+json": { - source: "iana", - compressible: true - }, - "application/td+json": { - source: "iana", - compressible: true - }, - "application/tei+xml": { - source: "iana", - compressible: true, - extensions: ["tei", "teicorpus"] - }, - "application/tetra_isi": { - source: "iana" - }, - "application/thraud+xml": { - source: "iana", - compressible: true, - extensions: ["tfi"] - }, - "application/timestamp-query": { - source: "iana" - }, - "application/timestamp-reply": { - source: "iana" - }, - "application/timestamped-data": { - source: "iana", - extensions: ["tsd"] - }, - "application/tlsrpt+gzip": { - source: "iana" - }, - "application/tlsrpt+json": { - source: "iana", - compressible: true - }, - "application/tnauthlist": { - source: "iana" - }, - "application/token-introspection+jwt": { - source: "iana" - }, - "application/toml": { - compressible: true, - extensions: ["toml"] - }, - "application/trickle-ice-sdpfrag": { - source: "iana" - }, - "application/trig": { - source: "iana", - extensions: ["trig"] - }, - "application/ttml+xml": { - source: "iana", - compressible: true, - extensions: ["ttml"] - }, - "application/tve-trigger": { - source: "iana" - }, - "application/tzif": { - source: "iana" - }, - "application/tzif-leap": { - source: "iana" - }, - "application/ubjson": { - compressible: false, - extensions: ["ubj"] - }, - "application/ulpfec": { - source: "iana" - }, - "application/urc-grpsheet+xml": { - source: "iana", - compressible: true - }, - "application/urc-ressheet+xml": { - source: "iana", - compressible: true, - extensions: ["rsheet"] - }, - "application/urc-targetdesc+xml": { - source: "iana", - compressible: true, - extensions: ["td"] - }, - "application/urc-uisocketdesc+xml": { - source: "iana", - compressible: true - }, - "application/vcard+json": { - source: "iana", - compressible: true - }, - "application/vcard+xml": { - source: "iana", - compressible: true - }, - "application/vemmi": { - source: "iana" - }, - "application/vividence.scriptfile": { - source: "apache" - }, - "application/vnd.1000minds.decision-model+xml": { - source: "iana", - compressible: true, - extensions: ["1km"] - }, - "application/vnd.3gpp-prose+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp-prose-pc3ch+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp-v2x-local-service-information": { - source: "iana" - }, - "application/vnd.3gpp.5gnas": { - source: "iana" - }, - "application/vnd.3gpp.access-transfer-events+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.bsf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.gmop+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.gtpc": { - source: "iana" - }, - "application/vnd.3gpp.interworking-data": { - source: "iana" - }, - "application/vnd.3gpp.lpp": { - source: "iana" - }, - "application/vnd.3gpp.mc-signalling-ear": { - source: "iana" - }, - "application/vnd.3gpp.mcdata-affiliation-command+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-payload": { - source: "iana" - }, - "application/vnd.3gpp.mcdata-service-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-signalling": { - source: "iana" - }, - "application/vnd.3gpp.mcdata-ue-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-user-profile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-affiliation-command+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-floor-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-location-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-service-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-signed+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-ue-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-ue-init-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-user-profile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-affiliation-command+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-affiliation-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-location-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-service-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-transmission-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-ue-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-user-profile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mid-call+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.ngap": { - source: "iana" - }, - "application/vnd.3gpp.pfcp": { - source: "iana" - }, - "application/vnd.3gpp.pic-bw-large": { - source: "iana", - extensions: ["plb"] - }, - "application/vnd.3gpp.pic-bw-small": { - source: "iana", - extensions: ["psb"] - }, - "application/vnd.3gpp.pic-bw-var": { - source: "iana", - extensions: ["pvb"] - }, - "application/vnd.3gpp.s1ap": { - source: "iana" - }, - "application/vnd.3gpp.sms": { - source: "iana" - }, - "application/vnd.3gpp.sms+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.srvcc-ext+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.srvcc-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.state-and-event-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.ussd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp2.bcmcsinfo+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp2.sms": { - source: "iana" - }, - "application/vnd.3gpp2.tcap": { - source: "iana", - extensions: ["tcap"] - }, - "application/vnd.3lightssoftware.imagescal": { - source: "iana" - }, - "application/vnd.3m.post-it-notes": { - source: "iana", - extensions: ["pwn"] - }, - "application/vnd.accpac.simply.aso": { - source: "iana", - extensions: ["aso"] - }, - "application/vnd.accpac.simply.imp": { - source: "iana", - extensions: ["imp"] - }, - "application/vnd.acucobol": { - source: "iana", - extensions: ["acu"] - }, - "application/vnd.acucorp": { - source: "iana", - extensions: ["atc", "acutc"] - }, - "application/vnd.adobe.air-application-installer-package+zip": { - source: "apache", - compressible: false, - extensions: ["air"] - }, - "application/vnd.adobe.flash.movie": { - source: "iana" - }, - "application/vnd.adobe.formscentral.fcdt": { - source: "iana", - extensions: ["fcdt"] - }, - "application/vnd.adobe.fxp": { - source: "iana", - extensions: ["fxp", "fxpl"] - }, - "application/vnd.adobe.partial-upload": { - source: "iana" - }, - "application/vnd.adobe.xdp+xml": { - source: "iana", - compressible: true, - extensions: ["xdp"] - }, - "application/vnd.adobe.xfdf": { - source: "iana", - extensions: ["xfdf"] - }, - "application/vnd.aether.imp": { - source: "iana" - }, - "application/vnd.afpc.afplinedata": { - source: "iana" - }, - "application/vnd.afpc.afplinedata-pagedef": { - source: "iana" - }, - "application/vnd.afpc.cmoca-cmresource": { - source: "iana" - }, - "application/vnd.afpc.foca-charset": { - source: "iana" - }, - "application/vnd.afpc.foca-codedfont": { - source: "iana" - }, - "application/vnd.afpc.foca-codepage": { - source: "iana" - }, - "application/vnd.afpc.modca": { - source: "iana" - }, - "application/vnd.afpc.modca-cmtable": { - source: "iana" - }, - "application/vnd.afpc.modca-formdef": { - source: "iana" - }, - "application/vnd.afpc.modca-mediummap": { - source: "iana" - }, - "application/vnd.afpc.modca-objectcontainer": { - source: "iana" - }, - "application/vnd.afpc.modca-overlay": { - source: "iana" - }, - "application/vnd.afpc.modca-pagesegment": { - source: "iana" - }, - "application/vnd.age": { - source: "iana", - extensions: ["age"] - }, - "application/vnd.ah-barcode": { - source: "iana" - }, - "application/vnd.ahead.space": { - source: "iana", - extensions: ["ahead"] - }, - "application/vnd.airzip.filesecure.azf": { - source: "iana", - extensions: ["azf"] - }, - "application/vnd.airzip.filesecure.azs": { - source: "iana", - extensions: ["azs"] - }, - "application/vnd.amadeus+json": { - source: "iana", - compressible: true - }, - "application/vnd.amazon.ebook": { - source: "apache", - extensions: ["azw"] - }, - "application/vnd.amazon.mobi8-ebook": { - source: "iana" - }, - "application/vnd.americandynamics.acc": { - source: "iana", - extensions: ["acc"] - }, - "application/vnd.amiga.ami": { - source: "iana", - extensions: ["ami"] - }, - "application/vnd.amundsen.maze+xml": { - source: "iana", - compressible: true - }, - "application/vnd.android.ota": { - source: "iana" - }, - "application/vnd.android.package-archive": { - source: "apache", - compressible: false, - extensions: ["apk"] - }, - "application/vnd.anki": { - source: "iana" - }, - "application/vnd.anser-web-certificate-issue-initiation": { - source: "iana", - extensions: ["cii"] - }, - "application/vnd.anser-web-funds-transfer-initiation": { - source: "apache", - extensions: ["fti"] - }, - "application/vnd.antix.game-component": { - source: "iana", - extensions: ["atx"] - }, - "application/vnd.apache.arrow.file": { - source: "iana" - }, - "application/vnd.apache.arrow.stream": { - source: "iana" - }, - "application/vnd.apache.thrift.binary": { - source: "iana" - }, - "application/vnd.apache.thrift.compact": { - source: "iana" - }, - "application/vnd.apache.thrift.json": { - source: "iana" - }, - "application/vnd.api+json": { - source: "iana", - compressible: true - }, - "application/vnd.aplextor.warrp+json": { - source: "iana", - compressible: true - }, - "application/vnd.apothekende.reservation+json": { - source: "iana", - compressible: true - }, - "application/vnd.apple.installer+xml": { - source: "iana", - compressible: true, - extensions: ["mpkg"] - }, - "application/vnd.apple.keynote": { - source: "iana", - extensions: ["key"] - }, - "application/vnd.apple.mpegurl": { - source: "iana", - extensions: ["m3u8"] - }, - "application/vnd.apple.numbers": { - source: "iana", - extensions: ["numbers"] - }, - "application/vnd.apple.pages": { - source: "iana", - extensions: ["pages"] - }, - "application/vnd.apple.pkpass": { - compressible: false, - extensions: ["pkpass"] - }, - "application/vnd.arastra.swi": { - source: "iana" - }, - "application/vnd.aristanetworks.swi": { - source: "iana", - extensions: ["swi"] - }, - "application/vnd.artisan+json": { - source: "iana", - compressible: true - }, - "application/vnd.artsquare": { - source: "iana" - }, - "application/vnd.astraea-software.iota": { - source: "iana", - extensions: ["iota"] - }, - "application/vnd.audiograph": { - source: "iana", - extensions: ["aep"] - }, - "application/vnd.autopackage": { - source: "iana" - }, - "application/vnd.avalon+json": { - source: "iana", - compressible: true - }, - "application/vnd.avistar+xml": { - source: "iana", - compressible: true - }, - "application/vnd.balsamiq.bmml+xml": { - source: "iana", - compressible: true, - extensions: ["bmml"] - }, - "application/vnd.balsamiq.bmpr": { - source: "iana" - }, - "application/vnd.banana-accounting": { - source: "iana" - }, - "application/vnd.bbf.usp.error": { - source: "iana" - }, - "application/vnd.bbf.usp.msg": { - source: "iana" - }, - "application/vnd.bbf.usp.msg+json": { - source: "iana", - compressible: true - }, - "application/vnd.bekitzur-stech+json": { - source: "iana", - compressible: true - }, - "application/vnd.bint.med-content": { - source: "iana" - }, - "application/vnd.biopax.rdf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.blink-idb-value-wrapper": { - source: "iana" - }, - "application/vnd.blueice.multipass": { - source: "iana", - extensions: ["mpm"] - }, - "application/vnd.bluetooth.ep.oob": { - source: "iana" - }, - "application/vnd.bluetooth.le.oob": { - source: "iana" - }, - "application/vnd.bmi": { - source: "iana", - extensions: ["bmi"] - }, - "application/vnd.bpf": { - source: "iana" - }, - "application/vnd.bpf3": { - source: "iana" - }, - "application/vnd.businessobjects": { - source: "iana", - extensions: ["rep"] - }, - "application/vnd.byu.uapi+json": { - source: "iana", - compressible: true - }, - "application/vnd.cab-jscript": { - source: "iana" - }, - "application/vnd.canon-cpdl": { - source: "iana" - }, - "application/vnd.canon-lips": { - source: "iana" - }, - "application/vnd.capasystems-pg+json": { - source: "iana", - compressible: true - }, - "application/vnd.cendio.thinlinc.clientconf": { - source: "iana" - }, - "application/vnd.century-systems.tcp_stream": { - source: "iana" - }, - "application/vnd.chemdraw+xml": { - source: "iana", - compressible: true, - extensions: ["cdxml"] - }, - "application/vnd.chess-pgn": { - source: "iana" - }, - "application/vnd.chipnuts.karaoke-mmd": { - source: "iana", - extensions: ["mmd"] - }, - "application/vnd.ciedi": { - source: "iana" - }, - "application/vnd.cinderella": { - source: "iana", - extensions: ["cdy"] - }, - "application/vnd.cirpack.isdn-ext": { - source: "iana" - }, - "application/vnd.citationstyles.style+xml": { - source: "iana", - compressible: true, - extensions: ["csl"] - }, - "application/vnd.claymore": { - source: "iana", - extensions: ["cla"] - }, - "application/vnd.cloanto.rp9": { - source: "iana", - extensions: ["rp9"] - }, - "application/vnd.clonk.c4group": { - source: "iana", - extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"] - }, - "application/vnd.cluetrust.cartomobile-config": { - source: "iana", - extensions: ["c11amc"] - }, - "application/vnd.cluetrust.cartomobile-config-pkg": { - source: "iana", - extensions: ["c11amz"] - }, - "application/vnd.coffeescript": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.document": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.document-template": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.presentation": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.presentation-template": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.spreadsheet": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.spreadsheet-template": { - source: "iana" - }, - "application/vnd.collection+json": { - source: "iana", - compressible: true - }, - "application/vnd.collection.doc+json": { - source: "iana", - compressible: true - }, - "application/vnd.collection.next+json": { - source: "iana", - compressible: true - }, - "application/vnd.comicbook+zip": { - source: "iana", - compressible: false - }, - "application/vnd.comicbook-rar": { - source: "iana" - }, - "application/vnd.commerce-battelle": { - source: "iana" - }, - "application/vnd.commonspace": { - source: "iana", - extensions: ["csp"] - }, - "application/vnd.contact.cmsg": { - source: "iana", - extensions: ["cdbcmsg"] - }, - "application/vnd.coreos.ignition+json": { - source: "iana", - compressible: true - }, - "application/vnd.cosmocaller": { - source: "iana", - extensions: ["cmc"] - }, - "application/vnd.crick.clicker": { - source: "iana", - extensions: ["clkx"] - }, - "application/vnd.crick.clicker.keyboard": { - source: "iana", - extensions: ["clkk"] - }, - "application/vnd.crick.clicker.palette": { - source: "iana", - extensions: ["clkp"] - }, - "application/vnd.crick.clicker.template": { - source: "iana", - extensions: ["clkt"] - }, - "application/vnd.crick.clicker.wordbank": { - source: "iana", - extensions: ["clkw"] - }, - "application/vnd.criticaltools.wbs+xml": { - source: "iana", - compressible: true, - extensions: ["wbs"] - }, - "application/vnd.cryptii.pipe+json": { - source: "iana", - compressible: true - }, - "application/vnd.crypto-shade-file": { - source: "iana" - }, - "application/vnd.cryptomator.encrypted": { - source: "iana" - }, - "application/vnd.cryptomator.vault": { - source: "iana" - }, - "application/vnd.ctc-posml": { - source: "iana", - extensions: ["pml"] - }, - "application/vnd.ctct.ws+xml": { - source: "iana", - compressible: true - }, - "application/vnd.cups-pdf": { - source: "iana" - }, - "application/vnd.cups-postscript": { - source: "iana" - }, - "application/vnd.cups-ppd": { - source: "iana", - extensions: ["ppd"] - }, - "application/vnd.cups-raster": { - source: "iana" - }, - "application/vnd.cups-raw": { - source: "iana" - }, - "application/vnd.curl": { - source: "iana" - }, - "application/vnd.curl.car": { - source: "apache", - extensions: ["car"] - }, - "application/vnd.curl.pcurl": { - source: "apache", - extensions: ["pcurl"] - }, - "application/vnd.cyan.dean.root+xml": { - source: "iana", - compressible: true - }, - "application/vnd.cybank": { - source: "iana" - }, - "application/vnd.cyclonedx+json": { - source: "iana", - compressible: true - }, - "application/vnd.cyclonedx+xml": { - source: "iana", - compressible: true - }, - "application/vnd.d2l.coursepackage1p0+zip": { - source: "iana", - compressible: false - }, - "application/vnd.d3m-dataset": { - source: "iana" - }, - "application/vnd.d3m-problem": { - source: "iana" - }, - "application/vnd.dart": { - source: "iana", - compressible: true, - extensions: ["dart"] - }, - "application/vnd.data-vision.rdz": { - source: "iana", - extensions: ["rdz"] - }, - "application/vnd.datapackage+json": { - source: "iana", - compressible: true - }, - "application/vnd.dataresource+json": { - source: "iana", - compressible: true - }, - "application/vnd.dbf": { - source: "iana", - extensions: ["dbf"] - }, - "application/vnd.debian.binary-package": { - source: "iana" - }, - "application/vnd.dece.data": { - source: "iana", - extensions: ["uvf", "uvvf", "uvd", "uvvd"] - }, - "application/vnd.dece.ttml+xml": { - source: "iana", - compressible: true, - extensions: ["uvt", "uvvt"] - }, - "application/vnd.dece.unspecified": { - source: "iana", - extensions: ["uvx", "uvvx"] - }, - "application/vnd.dece.zip": { - source: "iana", - extensions: ["uvz", "uvvz"] - }, - "application/vnd.denovo.fcselayout-link": { - source: "iana", - extensions: ["fe_launch"] - }, - "application/vnd.desmume.movie": { - source: "iana" - }, - "application/vnd.dir-bi.plate-dl-nosuffix": { - source: "iana" - }, - "application/vnd.dm.delegation+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dna": { - source: "iana", - extensions: ["dna"] - }, - "application/vnd.document+json": { - source: "iana", - compressible: true - }, - "application/vnd.dolby.mlp": { - source: "apache", - extensions: ["mlp"] - }, - "application/vnd.dolby.mobile.1": { - source: "iana" - }, - "application/vnd.dolby.mobile.2": { - source: "iana" - }, - "application/vnd.doremir.scorecloud-binary-document": { - source: "iana" - }, - "application/vnd.dpgraph": { - source: "iana", - extensions: ["dpg"] - }, - "application/vnd.dreamfactory": { - source: "iana", - extensions: ["dfac"] - }, - "application/vnd.drive+json": { - source: "iana", - compressible: true - }, - "application/vnd.ds-keypoint": { - source: "apache", - extensions: ["kpxx"] - }, - "application/vnd.dtg.local": { - source: "iana" - }, - "application/vnd.dtg.local.flash": { - source: "iana" - }, - "application/vnd.dtg.local.html": { - source: "iana" - }, - "application/vnd.dvb.ait": { - source: "iana", - extensions: ["ait"] - }, - "application/vnd.dvb.dvbisl+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.dvbj": { - source: "iana" - }, - "application/vnd.dvb.esgcontainer": { - source: "iana" - }, - "application/vnd.dvb.ipdcdftnotifaccess": { - source: "iana" - }, - "application/vnd.dvb.ipdcesgaccess": { - source: "iana" - }, - "application/vnd.dvb.ipdcesgaccess2": { - source: "iana" - }, - "application/vnd.dvb.ipdcesgpdd": { - source: "iana" - }, - "application/vnd.dvb.ipdcroaming": { - source: "iana" - }, - "application/vnd.dvb.iptv.alfec-base": { - source: "iana" - }, - "application/vnd.dvb.iptv.alfec-enhancement": { - source: "iana" - }, - "application/vnd.dvb.notif-aggregate-root+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-container+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-generic+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-ia-msglist+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-ia-registration-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-ia-registration-response+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-init+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.pfr": { - source: "iana" - }, - "application/vnd.dvb.service": { - source: "iana", - extensions: ["svc"] - }, - "application/vnd.dxr": { - source: "iana" - }, - "application/vnd.dynageo": { - source: "iana", - extensions: ["geo"] - }, - "application/vnd.dzr": { - source: "iana" - }, - "application/vnd.easykaraoke.cdgdownload": { - source: "iana" - }, - "application/vnd.ecdis-update": { - source: "iana" - }, - "application/vnd.ecip.rlp": { - source: "iana" - }, - "application/vnd.eclipse.ditto+json": { - source: "iana", - compressible: true - }, - "application/vnd.ecowin.chart": { - source: "iana", - extensions: ["mag"] - }, - "application/vnd.ecowin.filerequest": { - source: "iana" - }, - "application/vnd.ecowin.fileupdate": { - source: "iana" - }, - "application/vnd.ecowin.series": { - source: "iana" - }, - "application/vnd.ecowin.seriesrequest": { - source: "iana" - }, - "application/vnd.ecowin.seriesupdate": { - source: "iana" - }, - "application/vnd.efi.img": { - source: "iana" - }, - "application/vnd.efi.iso": { - source: "iana" - }, - "application/vnd.emclient.accessrequest+xml": { - source: "iana", - compressible: true - }, - "application/vnd.enliven": { - source: "iana", - extensions: ["nml"] - }, - "application/vnd.enphase.envoy": { - source: "iana" - }, - "application/vnd.eprints.data+xml": { - source: "iana", - compressible: true - }, - "application/vnd.epson.esf": { - source: "iana", - extensions: ["esf"] - }, - "application/vnd.epson.msf": { - source: "iana", - extensions: ["msf"] - }, - "application/vnd.epson.quickanime": { - source: "iana", - extensions: ["qam"] - }, - "application/vnd.epson.salt": { - source: "iana", - extensions: ["slt"] - }, - "application/vnd.epson.ssf": { - source: "iana", - extensions: ["ssf"] - }, - "application/vnd.ericsson.quickcall": { - source: "iana" - }, - "application/vnd.espass-espass+zip": { - source: "iana", - compressible: false - }, - "application/vnd.eszigno3+xml": { - source: "iana", - compressible: true, - extensions: ["es3", "et3"] - }, - "application/vnd.etsi.aoc+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.asic-e+zip": { - source: "iana", - compressible: false - }, - "application/vnd.etsi.asic-s+zip": { - source: "iana", - compressible: false - }, - "application/vnd.etsi.cug+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvcommand+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvdiscovery+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsad-bc+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsad-cod+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsad-npvr+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvservice+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsync+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvueprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.mcid+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.mheg5": { - source: "iana" - }, - "application/vnd.etsi.overload-control-policy-dataset+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.pstn+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.sci+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.simservs+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.timestamp-token": { - source: "iana" - }, - "application/vnd.etsi.tsl+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.tsl.der": { - source: "iana" - }, - "application/vnd.eu.kasparian.car+json": { - source: "iana", - compressible: true - }, - "application/vnd.eudora.data": { - source: "iana" - }, - "application/vnd.evolv.ecig.profile": { - source: "iana" - }, - "application/vnd.evolv.ecig.settings": { - source: "iana" - }, - "application/vnd.evolv.ecig.theme": { - source: "iana" - }, - "application/vnd.exstream-empower+zip": { - source: "iana", - compressible: false - }, - "application/vnd.exstream-package": { - source: "iana" - }, - "application/vnd.ezpix-album": { - source: "iana", - extensions: ["ez2"] - }, - "application/vnd.ezpix-package": { - source: "iana", - extensions: ["ez3"] - }, - "application/vnd.f-secure.mobile": { - source: "iana" - }, - "application/vnd.familysearch.gedcom+zip": { - source: "iana", - compressible: false - }, - "application/vnd.fastcopy-disk-image": { - source: "iana" - }, - "application/vnd.fdf": { - source: "iana", - extensions: ["fdf"] - }, - "application/vnd.fdsn.mseed": { - source: "iana", - extensions: ["mseed"] - }, - "application/vnd.fdsn.seed": { - source: "iana", - extensions: ["seed", "dataless"] - }, - "application/vnd.ffsns": { - source: "iana" - }, - "application/vnd.ficlab.flb+zip": { - source: "iana", - compressible: false - }, - "application/vnd.filmit.zfc": { - source: "iana" - }, - "application/vnd.fints": { - source: "iana" - }, - "application/vnd.firemonkeys.cloudcell": { - source: "iana" - }, - "application/vnd.flographit": { - source: "iana", - extensions: ["gph"] - }, - "application/vnd.fluxtime.clip": { - source: "iana", - extensions: ["ftc"] - }, - "application/vnd.font-fontforge-sfd": { - source: "iana" - }, - "application/vnd.framemaker": { - source: "iana", - extensions: ["fm", "frame", "maker", "book"] - }, - "application/vnd.frogans.fnc": { - source: "iana", - extensions: ["fnc"] - }, - "application/vnd.frogans.ltf": { - source: "iana", - extensions: ["ltf"] - }, - "application/vnd.fsc.weblaunch": { - source: "iana", - extensions: ["fsc"] - }, - "application/vnd.fujifilm.fb.docuworks": { - source: "iana" - }, - "application/vnd.fujifilm.fb.docuworks.binder": { - source: "iana" - }, - "application/vnd.fujifilm.fb.docuworks.container": { - source: "iana" - }, - "application/vnd.fujifilm.fb.jfi+xml": { - source: "iana", - compressible: true - }, - "application/vnd.fujitsu.oasys": { - source: "iana", - extensions: ["oas"] - }, - "application/vnd.fujitsu.oasys2": { - source: "iana", - extensions: ["oa2"] - }, - "application/vnd.fujitsu.oasys3": { - source: "iana", - extensions: ["oa3"] - }, - "application/vnd.fujitsu.oasysgp": { - source: "iana", - extensions: ["fg5"] - }, - "application/vnd.fujitsu.oasysprs": { - source: "iana", - extensions: ["bh2"] - }, - "application/vnd.fujixerox.art-ex": { - source: "iana" - }, - "application/vnd.fujixerox.art4": { - source: "iana" - }, - "application/vnd.fujixerox.ddd": { - source: "iana", - extensions: ["ddd"] - }, - "application/vnd.fujixerox.docuworks": { - source: "iana", - extensions: ["xdw"] - }, - "application/vnd.fujixerox.docuworks.binder": { - source: "iana", - extensions: ["xbd"] - }, - "application/vnd.fujixerox.docuworks.container": { - source: "iana" - }, - "application/vnd.fujixerox.hbpl": { - source: "iana" - }, - "application/vnd.fut-misnet": { - source: "iana" - }, - "application/vnd.futoin+cbor": { - source: "iana" - }, - "application/vnd.futoin+json": { - source: "iana", - compressible: true - }, - "application/vnd.fuzzysheet": { - source: "iana", - extensions: ["fzs"] - }, - "application/vnd.genomatix.tuxedo": { - source: "iana", - extensions: ["txd"] - }, - "application/vnd.gentics.grd+json": { - source: "iana", - compressible: true - }, - "application/vnd.geo+json": { - source: "iana", - compressible: true - }, - "application/vnd.geocube+xml": { - source: "iana", - compressible: true - }, - "application/vnd.geogebra.file": { - source: "iana", - extensions: ["ggb"] - }, - "application/vnd.geogebra.slides": { - source: "iana" - }, - "application/vnd.geogebra.tool": { - source: "iana", - extensions: ["ggt"] - }, - "application/vnd.geometry-explorer": { - source: "iana", - extensions: ["gex", "gre"] - }, - "application/vnd.geonext": { - source: "iana", - extensions: ["gxt"] - }, - "application/vnd.geoplan": { - source: "iana", - extensions: ["g2w"] - }, - "application/vnd.geospace": { - source: "iana", - extensions: ["g3w"] - }, - "application/vnd.gerber": { - source: "iana" - }, - "application/vnd.globalplatform.card-content-mgt": { - source: "iana" - }, - "application/vnd.globalplatform.card-content-mgt-response": { - source: "iana" - }, - "application/vnd.gmx": { - source: "iana", - extensions: ["gmx"] - }, - "application/vnd.google-apps.document": { - compressible: false, - extensions: ["gdoc"] - }, - "application/vnd.google-apps.presentation": { - compressible: false, - extensions: ["gslides"] - }, - "application/vnd.google-apps.spreadsheet": { - compressible: false, - extensions: ["gsheet"] - }, - "application/vnd.google-earth.kml+xml": { - source: "iana", - compressible: true, - extensions: ["kml"] - }, - "application/vnd.google-earth.kmz": { - source: "iana", - compressible: false, - extensions: ["kmz"] - }, - "application/vnd.gov.sk.e-form+xml": { - source: "iana", - compressible: true - }, - "application/vnd.gov.sk.e-form+zip": { - source: "iana", - compressible: false - }, - "application/vnd.gov.sk.xmldatacontainer+xml": { - source: "iana", - compressible: true - }, - "application/vnd.grafeq": { - source: "iana", - extensions: ["gqf", "gqs"] - }, - "application/vnd.gridmp": { - source: "iana" - }, - "application/vnd.groove-account": { - source: "iana", - extensions: ["gac"] - }, - "application/vnd.groove-help": { - source: "iana", - extensions: ["ghf"] - }, - "application/vnd.groove-identity-message": { - source: "iana", - extensions: ["gim"] - }, - "application/vnd.groove-injector": { - source: "iana", - extensions: ["grv"] - }, - "application/vnd.groove-tool-message": { - source: "iana", - extensions: ["gtm"] - }, - "application/vnd.groove-tool-template": { - source: "iana", - extensions: ["tpl"] - }, - "application/vnd.groove-vcard": { - source: "iana", - extensions: ["vcg"] - }, - "application/vnd.hal+json": { - source: "iana", - compressible: true - }, - "application/vnd.hal+xml": { - source: "iana", - compressible: true, - extensions: ["hal"] - }, - "application/vnd.handheld-entertainment+xml": { - source: "iana", - compressible: true, - extensions: ["zmm"] - }, - "application/vnd.hbci": { - source: "iana", - extensions: ["hbci"] - }, - "application/vnd.hc+json": { - source: "iana", - compressible: true - }, - "application/vnd.hcl-bireports": { - source: "iana" - }, - "application/vnd.hdt": { - source: "iana" - }, - "application/vnd.heroku+json": { - source: "iana", - compressible: true - }, - "application/vnd.hhe.lesson-player": { - source: "iana", - extensions: ["les"] - }, - "application/vnd.hl7cda+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.hl7v2+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.hp-hpgl": { - source: "iana", - extensions: ["hpgl"] - }, - "application/vnd.hp-hpid": { - source: "iana", - extensions: ["hpid"] - }, - "application/vnd.hp-hps": { - source: "iana", - extensions: ["hps"] - }, - "application/vnd.hp-jlyt": { - source: "iana", - extensions: ["jlt"] - }, - "application/vnd.hp-pcl": { - source: "iana", - extensions: ["pcl"] - }, - "application/vnd.hp-pclxl": { - source: "iana", - extensions: ["pclxl"] - }, - "application/vnd.httphone": { - source: "iana" - }, - "application/vnd.hydrostatix.sof-data": { - source: "iana", - extensions: ["sfd-hdstx"] - }, - "application/vnd.hyper+json": { - source: "iana", - compressible: true - }, - "application/vnd.hyper-item+json": { - source: "iana", - compressible: true - }, - "application/vnd.hyperdrive+json": { - source: "iana", - compressible: true - }, - "application/vnd.hzn-3d-crossword": { - source: "iana" - }, - "application/vnd.ibm.afplinedata": { - source: "iana" - }, - "application/vnd.ibm.electronic-media": { - source: "iana" - }, - "application/vnd.ibm.minipay": { - source: "iana", - extensions: ["mpy"] - }, - "application/vnd.ibm.modcap": { - source: "iana", - extensions: ["afp", "listafp", "list3820"] - }, - "application/vnd.ibm.rights-management": { - source: "iana", - extensions: ["irm"] - }, - "application/vnd.ibm.secure-container": { - source: "iana", - extensions: ["sc"] - }, - "application/vnd.iccprofile": { - source: "iana", - extensions: ["icc", "icm"] - }, - "application/vnd.ieee.1905": { - source: "iana" - }, - "application/vnd.igloader": { - source: "iana", - extensions: ["igl"] - }, - "application/vnd.imagemeter.folder+zip": { - source: "iana", - compressible: false - }, - "application/vnd.imagemeter.image+zip": { - source: "iana", - compressible: false - }, - "application/vnd.immervision-ivp": { - source: "iana", - extensions: ["ivp"] - }, - "application/vnd.immervision-ivu": { - source: "iana", - extensions: ["ivu"] - }, - "application/vnd.ims.imsccv1p1": { - source: "iana" - }, - "application/vnd.ims.imsccv1p2": { - source: "iana" - }, - "application/vnd.ims.imsccv1p3": { - source: "iana" - }, - "application/vnd.ims.lis.v2.result+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolconsumerprofile+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolproxy+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolproxy.id+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolsettings+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolsettings.simple+json": { - source: "iana", - compressible: true - }, - "application/vnd.informedcontrol.rms+xml": { - source: "iana", - compressible: true - }, - "application/vnd.informix-visionary": { - source: "iana" - }, - "application/vnd.infotech.project": { - source: "iana" - }, - "application/vnd.infotech.project+xml": { - source: "iana", - compressible: true - }, - "application/vnd.innopath.wamp.notification": { - source: "iana" - }, - "application/vnd.insors.igm": { - source: "iana", - extensions: ["igm"] - }, - "application/vnd.intercon.formnet": { - source: "iana", - extensions: ["xpw", "xpx"] - }, - "application/vnd.intergeo": { - source: "iana", - extensions: ["i2g"] - }, - "application/vnd.intertrust.digibox": { - source: "iana" - }, - "application/vnd.intertrust.nncp": { - source: "iana" - }, - "application/vnd.intu.qbo": { - source: "iana", - extensions: ["qbo"] - }, - "application/vnd.intu.qfx": { - source: "iana", - extensions: ["qfx"] - }, - "application/vnd.iptc.g2.catalogitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.conceptitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.knowledgeitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.newsitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.newsmessage+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.packageitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.planningitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ipunplugged.rcprofile": { - source: "iana", - extensions: ["rcprofile"] - }, - "application/vnd.irepository.package+xml": { - source: "iana", - compressible: true, - extensions: ["irp"] - }, - "application/vnd.is-xpr": { - source: "iana", - extensions: ["xpr"] - }, - "application/vnd.isac.fcs": { - source: "iana", - extensions: ["fcs"] - }, - "application/vnd.iso11783-10+zip": { - source: "iana", - compressible: false - }, - "application/vnd.jam": { - source: "iana", - extensions: ["jam"] - }, - "application/vnd.japannet-directory-service": { - source: "iana" - }, - "application/vnd.japannet-jpnstore-wakeup": { - source: "iana" - }, - "application/vnd.japannet-payment-wakeup": { - source: "iana" - }, - "application/vnd.japannet-registration": { - source: "iana" - }, - "application/vnd.japannet-registration-wakeup": { - source: "iana" - }, - "application/vnd.japannet-setstore-wakeup": { - source: "iana" - }, - "application/vnd.japannet-verification": { - source: "iana" - }, - "application/vnd.japannet-verification-wakeup": { - source: "iana" - }, - "application/vnd.jcp.javame.midlet-rms": { - source: "iana", - extensions: ["rms"] - }, - "application/vnd.jisp": { - source: "iana", - extensions: ["jisp"] - }, - "application/vnd.joost.joda-archive": { - source: "iana", - extensions: ["joda"] - }, - "application/vnd.jsk.isdn-ngn": { - source: "iana" - }, - "application/vnd.kahootz": { - source: "iana", - extensions: ["ktz", "ktr"] - }, - "application/vnd.kde.karbon": { - source: "iana", - extensions: ["karbon"] - }, - "application/vnd.kde.kchart": { - source: "iana", - extensions: ["chrt"] - }, - "application/vnd.kde.kformula": { - source: "iana", - extensions: ["kfo"] - }, - "application/vnd.kde.kivio": { - source: "iana", - extensions: ["flw"] - }, - "application/vnd.kde.kontour": { - source: "iana", - extensions: ["kon"] - }, - "application/vnd.kde.kpresenter": { - source: "iana", - extensions: ["kpr", "kpt"] - }, - "application/vnd.kde.kspread": { - source: "iana", - extensions: ["ksp"] - }, - "application/vnd.kde.kword": { - source: "iana", - extensions: ["kwd", "kwt"] - }, - "application/vnd.kenameaapp": { - source: "iana", - extensions: ["htke"] - }, - "application/vnd.kidspiration": { - source: "iana", - extensions: ["kia"] - }, - "application/vnd.kinar": { - source: "iana", - extensions: ["kne", "knp"] - }, - "application/vnd.koan": { - source: "iana", - extensions: ["skp", "skd", "skt", "skm"] - }, - "application/vnd.kodak-descriptor": { - source: "iana", - extensions: ["sse"] - }, - "application/vnd.las": { - source: "iana" - }, - "application/vnd.las.las+json": { - source: "iana", - compressible: true - }, - "application/vnd.las.las+xml": { - source: "iana", - compressible: true, - extensions: ["lasxml"] - }, - "application/vnd.laszip": { - source: "iana" - }, - "application/vnd.leap+json": { - source: "iana", - compressible: true - }, - "application/vnd.liberty-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.llamagraphics.life-balance.desktop": { - source: "iana", - extensions: ["lbd"] - }, - "application/vnd.llamagraphics.life-balance.exchange+xml": { - source: "iana", - compressible: true, - extensions: ["lbe"] - }, - "application/vnd.logipipe.circuit+zip": { - source: "iana", - compressible: false - }, - "application/vnd.loom": { - source: "iana" - }, - "application/vnd.lotus-1-2-3": { - source: "iana", - extensions: ["123"] - }, - "application/vnd.lotus-approach": { - source: "iana", - extensions: ["apr"] - }, - "application/vnd.lotus-freelance": { - source: "iana", - extensions: ["pre"] - }, - "application/vnd.lotus-notes": { - source: "iana", - extensions: ["nsf"] - }, - "application/vnd.lotus-organizer": { - source: "iana", - extensions: ["org"] - }, - "application/vnd.lotus-screencam": { - source: "iana", - extensions: ["scm"] - }, - "application/vnd.lotus-wordpro": { - source: "iana", - extensions: ["lwp"] - }, - "application/vnd.macports.portpkg": { - source: "iana", - extensions: ["portpkg"] - }, - "application/vnd.mapbox-vector-tile": { - source: "iana", - extensions: ["mvt"] - }, - "application/vnd.marlin.drm.actiontoken+xml": { - source: "iana", - compressible: true - }, - "application/vnd.marlin.drm.conftoken+xml": { - source: "iana", - compressible: true - }, - "application/vnd.marlin.drm.license+xml": { - source: "iana", - compressible: true - }, - "application/vnd.marlin.drm.mdcf": { - source: "iana" - }, - "application/vnd.mason+json": { - source: "iana", - compressible: true - }, - "application/vnd.maxar.archive.3tz+zip": { - source: "iana", - compressible: false - }, - "application/vnd.maxmind.maxmind-db": { - source: "iana" - }, - "application/vnd.mcd": { - source: "iana", - extensions: ["mcd"] - }, - "application/vnd.medcalcdata": { - source: "iana", - extensions: ["mc1"] - }, - "application/vnd.mediastation.cdkey": { - source: "iana", - extensions: ["cdkey"] - }, - "application/vnd.meridian-slingshot": { - source: "iana" - }, - "application/vnd.mfer": { - source: "iana", - extensions: ["mwf"] - }, - "application/vnd.mfmp": { - source: "iana", - extensions: ["mfm"] - }, - "application/vnd.micro+json": { - source: "iana", - compressible: true - }, - "application/vnd.micrografx.flo": { - source: "iana", - extensions: ["flo"] - }, - "application/vnd.micrografx.igx": { - source: "iana", - extensions: ["igx"] - }, - "application/vnd.microsoft.portable-executable": { - source: "iana" - }, - "application/vnd.microsoft.windows.thumbnail-cache": { - source: "iana" - }, - "application/vnd.miele+json": { - source: "iana", - compressible: true - }, - "application/vnd.mif": { - source: "iana", - extensions: ["mif"] - }, - "application/vnd.minisoft-hp3000-save": { - source: "iana" - }, - "application/vnd.mitsubishi.misty-guard.trustweb": { - source: "iana" - }, - "application/vnd.mobius.daf": { - source: "iana", - extensions: ["daf"] - }, - "application/vnd.mobius.dis": { - source: "iana", - extensions: ["dis"] - }, - "application/vnd.mobius.mbk": { - source: "iana", - extensions: ["mbk"] - }, - "application/vnd.mobius.mqy": { - source: "iana", - extensions: ["mqy"] - }, - "application/vnd.mobius.msl": { - source: "iana", - extensions: ["msl"] - }, - "application/vnd.mobius.plc": { - source: "iana", - extensions: ["plc"] - }, - "application/vnd.mobius.txf": { - source: "iana", - extensions: ["txf"] - }, - "application/vnd.mophun.application": { - source: "iana", - extensions: ["mpn"] - }, - "application/vnd.mophun.certificate": { - source: "iana", - extensions: ["mpc"] - }, - "application/vnd.motorola.flexsuite": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.adsi": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.fis": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.gotap": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.kmr": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.ttc": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.wem": { - source: "iana" - }, - "application/vnd.motorola.iprm": { - source: "iana" - }, - "application/vnd.mozilla.xul+xml": { - source: "iana", - compressible: true, - extensions: ["xul"] - }, - "application/vnd.ms-3mfdocument": { - source: "iana" - }, - "application/vnd.ms-artgalry": { - source: "iana", - extensions: ["cil"] - }, - "application/vnd.ms-asf": { - source: "iana" - }, - "application/vnd.ms-cab-compressed": { - source: "iana", - extensions: ["cab"] - }, - "application/vnd.ms-color.iccprofile": { - source: "apache" - }, - "application/vnd.ms-excel": { - source: "iana", - compressible: false, - extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"] - }, - "application/vnd.ms-excel.addin.macroenabled.12": { - source: "iana", - extensions: ["xlam"] - }, - "application/vnd.ms-excel.sheet.binary.macroenabled.12": { - source: "iana", - extensions: ["xlsb"] - }, - "application/vnd.ms-excel.sheet.macroenabled.12": { - source: "iana", - extensions: ["xlsm"] - }, - "application/vnd.ms-excel.template.macroenabled.12": { - source: "iana", - extensions: ["xltm"] - }, - "application/vnd.ms-fontobject": { - source: "iana", - compressible: true, - extensions: ["eot"] - }, - "application/vnd.ms-htmlhelp": { - source: "iana", - extensions: ["chm"] - }, - "application/vnd.ms-ims": { - source: "iana", - extensions: ["ims"] - }, - "application/vnd.ms-lrm": { - source: "iana", - extensions: ["lrm"] - }, - "application/vnd.ms-office.activex+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-officetheme": { - source: "iana", - extensions: ["thmx"] - }, - "application/vnd.ms-opentype": { - source: "apache", - compressible: true - }, - "application/vnd.ms-outlook": { - compressible: false, - extensions: ["msg"] - }, - "application/vnd.ms-package.obfuscated-opentype": { - source: "apache" - }, - "application/vnd.ms-pki.seccat": { - source: "apache", - extensions: ["cat"] - }, - "application/vnd.ms-pki.stl": { - source: "apache", - extensions: ["stl"] - }, - "application/vnd.ms-playready.initiator+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-powerpoint": { - source: "iana", - compressible: false, - extensions: ["ppt", "pps", "pot"] - }, - "application/vnd.ms-powerpoint.addin.macroenabled.12": { - source: "iana", - extensions: ["ppam"] - }, - "application/vnd.ms-powerpoint.presentation.macroenabled.12": { - source: "iana", - extensions: ["pptm"] - }, - "application/vnd.ms-powerpoint.slide.macroenabled.12": { - source: "iana", - extensions: ["sldm"] - }, - "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { - source: "iana", - extensions: ["ppsm"] - }, - "application/vnd.ms-powerpoint.template.macroenabled.12": { - source: "iana", - extensions: ["potm"] - }, - "application/vnd.ms-printdevicecapabilities+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-printing.printticket+xml": { - source: "apache", - compressible: true - }, - "application/vnd.ms-printschematicket+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-project": { - source: "iana", - extensions: ["mpp", "mpt"] - }, - "application/vnd.ms-tnef": { - source: "iana" - }, - "application/vnd.ms-windows.devicepairing": { - source: "iana" - }, - "application/vnd.ms-windows.nwprinting.oob": { - source: "iana" - }, - "application/vnd.ms-windows.printerpairing": { - source: "iana" - }, - "application/vnd.ms-windows.wsd.oob": { - source: "iana" - }, - "application/vnd.ms-wmdrm.lic-chlg-req": { - source: "iana" - }, - "application/vnd.ms-wmdrm.lic-resp": { - source: "iana" - }, - "application/vnd.ms-wmdrm.meter-chlg-req": { - source: "iana" - }, - "application/vnd.ms-wmdrm.meter-resp": { - source: "iana" - }, - "application/vnd.ms-word.document.macroenabled.12": { - source: "iana", - extensions: ["docm"] - }, - "application/vnd.ms-word.template.macroenabled.12": { - source: "iana", - extensions: ["dotm"] - }, - "application/vnd.ms-works": { - source: "iana", - extensions: ["wps", "wks", "wcm", "wdb"] - }, - "application/vnd.ms-wpl": { - source: "iana", - extensions: ["wpl"] - }, - "application/vnd.ms-xpsdocument": { - source: "iana", - compressible: false, - extensions: ["xps"] - }, - "application/vnd.msa-disk-image": { - source: "iana" - }, - "application/vnd.mseq": { - source: "iana", - extensions: ["mseq"] - }, - "application/vnd.msign": { - source: "iana" - }, - "application/vnd.multiad.creator": { - source: "iana" - }, - "application/vnd.multiad.creator.cif": { - source: "iana" - }, - "application/vnd.music-niff": { - source: "iana" - }, - "application/vnd.musician": { - source: "iana", - extensions: ["mus"] - }, - "application/vnd.muvee.style": { - source: "iana", - extensions: ["msty"] - }, - "application/vnd.mynfc": { - source: "iana", - extensions: ["taglet"] - }, - "application/vnd.nacamar.ybrid+json": { - source: "iana", - compressible: true - }, - "application/vnd.ncd.control": { - source: "iana" - }, - "application/vnd.ncd.reference": { - source: "iana" - }, - "application/vnd.nearst.inv+json": { - source: "iana", - compressible: true - }, - "application/vnd.nebumind.line": { - source: "iana" - }, - "application/vnd.nervana": { - source: "iana" - }, - "application/vnd.netfpx": { - source: "iana" - }, - "application/vnd.neurolanguage.nlu": { - source: "iana", - extensions: ["nlu"] - }, - "application/vnd.nimn": { - source: "iana" - }, - "application/vnd.nintendo.nitro.rom": { - source: "iana" - }, - "application/vnd.nintendo.snes.rom": { - source: "iana" - }, - "application/vnd.nitf": { - source: "iana", - extensions: ["ntf", "nitf"] - }, - "application/vnd.noblenet-directory": { - source: "iana", - extensions: ["nnd"] - }, - "application/vnd.noblenet-sealer": { - source: "iana", - extensions: ["nns"] - }, - "application/vnd.noblenet-web": { - source: "iana", - extensions: ["nnw"] - }, - "application/vnd.nokia.catalogs": { - source: "iana" - }, - "application/vnd.nokia.conml+wbxml": { - source: "iana" - }, - "application/vnd.nokia.conml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.iptv.config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.isds-radio-presets": { - source: "iana" - }, - "application/vnd.nokia.landmark+wbxml": { - source: "iana" - }, - "application/vnd.nokia.landmark+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.landmarkcollection+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.n-gage.ac+xml": { - source: "iana", - compressible: true, - extensions: ["ac"] - }, - "application/vnd.nokia.n-gage.data": { - source: "iana", - extensions: ["ngdat"] - }, - "application/vnd.nokia.n-gage.symbian.install": { - source: "iana", - extensions: ["n-gage"] - }, - "application/vnd.nokia.ncd": { - source: "iana" - }, - "application/vnd.nokia.pcd+wbxml": { - source: "iana" - }, - "application/vnd.nokia.pcd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.radio-preset": { - source: "iana", - extensions: ["rpst"] - }, - "application/vnd.nokia.radio-presets": { - source: "iana", - extensions: ["rpss"] - }, - "application/vnd.novadigm.edm": { - source: "iana", - extensions: ["edm"] - }, - "application/vnd.novadigm.edx": { - source: "iana", - extensions: ["edx"] - }, - "application/vnd.novadigm.ext": { - source: "iana", - extensions: ["ext"] - }, - "application/vnd.ntt-local.content-share": { - source: "iana" - }, - "application/vnd.ntt-local.file-transfer": { - source: "iana" - }, - "application/vnd.ntt-local.ogw_remote-access": { - source: "iana" - }, - "application/vnd.ntt-local.sip-ta_remote": { - source: "iana" - }, - "application/vnd.ntt-local.sip-ta_tcp_stream": { - source: "iana" - }, - "application/vnd.oasis.opendocument.chart": { - source: "iana", - extensions: ["odc"] - }, - "application/vnd.oasis.opendocument.chart-template": { - source: "iana", - extensions: ["otc"] - }, - "application/vnd.oasis.opendocument.database": { - source: "iana", - extensions: ["odb"] - }, - "application/vnd.oasis.opendocument.formula": { - source: "iana", - extensions: ["odf"] - }, - "application/vnd.oasis.opendocument.formula-template": { - source: "iana", - extensions: ["odft"] - }, - "application/vnd.oasis.opendocument.graphics": { - source: "iana", - compressible: false, - extensions: ["odg"] - }, - "application/vnd.oasis.opendocument.graphics-template": { - source: "iana", - extensions: ["otg"] - }, - "application/vnd.oasis.opendocument.image": { - source: "iana", - extensions: ["odi"] - }, - "application/vnd.oasis.opendocument.image-template": { - source: "iana", - extensions: ["oti"] - }, - "application/vnd.oasis.opendocument.presentation": { - source: "iana", - compressible: false, - extensions: ["odp"] - }, - "application/vnd.oasis.opendocument.presentation-template": { - source: "iana", - extensions: ["otp"] - }, - "application/vnd.oasis.opendocument.spreadsheet": { - source: "iana", - compressible: false, - extensions: ["ods"] - }, - "application/vnd.oasis.opendocument.spreadsheet-template": { - source: "iana", - extensions: ["ots"] - }, - "application/vnd.oasis.opendocument.text": { - source: "iana", - compressible: false, - extensions: ["odt"] - }, - "application/vnd.oasis.opendocument.text-master": { - source: "iana", - extensions: ["odm"] - }, - "application/vnd.oasis.opendocument.text-template": { - source: "iana", - extensions: ["ott"] - }, - "application/vnd.oasis.opendocument.text-web": { - source: "iana", - extensions: ["oth"] - }, - "application/vnd.obn": { - source: "iana" - }, - "application/vnd.ocf+cbor": { - source: "iana" - }, - "application/vnd.oci.image.manifest.v1+json": { - source: "iana", - compressible: true - }, - "application/vnd.oftn.l10n+json": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.contentaccessdownload+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.contentaccessstreaming+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.cspg-hexbinary": { - source: "iana" - }, - "application/vnd.oipf.dae.svg+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.dae.xhtml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.mippvcontrolmessage+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.pae.gem": { - source: "iana" - }, - "application/vnd.oipf.spdiscovery+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.spdlist+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.ueprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.userprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.olpc-sugar": { - source: "iana", - extensions: ["xo"] - }, - "application/vnd.oma-scws-config": { - source: "iana" - }, - "application/vnd.oma-scws-http-request": { - source: "iana" - }, - "application/vnd.oma-scws-http-response": { - source: "iana" - }, - "application/vnd.oma.bcast.associated-procedure-parameter+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.drm-trigger+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.imd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.ltkm": { - source: "iana" - }, - "application/vnd.oma.bcast.notification+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.provisioningtrigger": { - source: "iana" - }, - "application/vnd.oma.bcast.sgboot": { - source: "iana" - }, - "application/vnd.oma.bcast.sgdd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.sgdu": { - source: "iana" - }, - "application/vnd.oma.bcast.simple-symbol-container": { - source: "iana" - }, - "application/vnd.oma.bcast.smartcard-trigger+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.sprov+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.stkm": { - source: "iana" - }, - "application/vnd.oma.cab-address-book+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-feature-handler+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-pcc+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-subs-invite+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-user-prefs+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.dcd": { - source: "iana" - }, - "application/vnd.oma.dcdc": { - source: "iana" - }, - "application/vnd.oma.dd2+xml": { - source: "iana", - compressible: true, - extensions: ["dd2"] - }, - "application/vnd.oma.drm.risd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.group-usage-list+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.lwm2m+cbor": { - source: "iana" - }, - "application/vnd.oma.lwm2m+json": { - source: "iana", - compressible: true - }, - "application/vnd.oma.lwm2m+tlv": { - source: "iana" - }, - "application/vnd.oma.pal+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.detailed-progress-report+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.final-report+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.groups+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.invocation-descriptor+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.optimized-progress-report+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.push": { - source: "iana" - }, - "application/vnd.oma.scidm.messages+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.xcap-directory+xml": { - source: "iana", - compressible: true - }, - "application/vnd.omads-email+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.omads-file+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.omads-folder+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.omaloc-supl-init": { - source: "iana" - }, - "application/vnd.onepager": { - source: "iana" - }, - "application/vnd.onepagertamp": { - source: "iana" - }, - "application/vnd.onepagertamx": { - source: "iana" - }, - "application/vnd.onepagertat": { - source: "iana" - }, - "application/vnd.onepagertatp": { - source: "iana" - }, - "application/vnd.onepagertatx": { - source: "iana" - }, - "application/vnd.openblox.game+xml": { - source: "iana", - compressible: true, - extensions: ["obgx"] - }, - "application/vnd.openblox.game-binary": { - source: "iana" - }, - "application/vnd.openeye.oeb": { - source: "iana" - }, - "application/vnd.openofficeorg.extension": { - source: "apache", - extensions: ["oxt"] - }, - "application/vnd.openstreetmap.data+xml": { - source: "iana", - compressible: true, - extensions: ["osm"] - }, - "application/vnd.opentimestamps.ots": { - source: "iana" - }, - "application/vnd.openxmlformats-officedocument.custom-properties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawing+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.extended-properties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.presentation": { - source: "iana", - compressible: false, - extensions: ["pptx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slide": { - source: "iana", - extensions: ["sldx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { - source: "iana", - extensions: ["ppsx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.template": { - source: "iana", - extensions: ["potx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { - source: "iana", - compressible: false, - extensions: ["xlsx"] - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { - source: "iana", - extensions: ["xltx"] - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.theme+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.themeoverride+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.vmldrawing": { - source: "iana" - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { - source: "iana", - compressible: false, - extensions: ["docx"] - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { - source: "iana", - extensions: ["dotx"] - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-package.core-properties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-package.relationships+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oracle.resource+json": { - source: "iana", - compressible: true - }, - "application/vnd.orange.indata": { - source: "iana" - }, - "application/vnd.osa.netdeploy": { - source: "iana" - }, - "application/vnd.osgeo.mapguide.package": { - source: "iana", - extensions: ["mgp"] - }, - "application/vnd.osgi.bundle": { - source: "iana" - }, - "application/vnd.osgi.dp": { - source: "iana", - extensions: ["dp"] - }, - "application/vnd.osgi.subsystem": { - source: "iana", - extensions: ["esa"] - }, - "application/vnd.otps.ct-kip+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oxli.countgraph": { - source: "iana" - }, - "application/vnd.pagerduty+json": { - source: "iana", - compressible: true - }, - "application/vnd.palm": { - source: "iana", - extensions: ["pdb", "pqa", "oprc"] - }, - "application/vnd.panoply": { - source: "iana" - }, - "application/vnd.paos.xml": { - source: "iana" - }, - "application/vnd.patentdive": { - source: "iana" - }, - "application/vnd.patientecommsdoc": { - source: "iana" - }, - "application/vnd.pawaafile": { - source: "iana", - extensions: ["paw"] - }, - "application/vnd.pcos": { - source: "iana" - }, - "application/vnd.pg.format": { - source: "iana", - extensions: ["str"] - }, - "application/vnd.pg.osasli": { - source: "iana", - extensions: ["ei6"] - }, - "application/vnd.piaccess.application-licence": { - source: "iana" - }, - "application/vnd.picsel": { - source: "iana", - extensions: ["efif"] - }, - "application/vnd.pmi.widget": { - source: "iana", - extensions: ["wg"] - }, - "application/vnd.poc.group-advertisement+xml": { - source: "iana", - compressible: true - }, - "application/vnd.pocketlearn": { - source: "iana", - extensions: ["plf"] - }, - "application/vnd.powerbuilder6": { - source: "iana", - extensions: ["pbd"] - }, - "application/vnd.powerbuilder6-s": { - source: "iana" - }, - "application/vnd.powerbuilder7": { - source: "iana" - }, - "application/vnd.powerbuilder7-s": { - source: "iana" - }, - "application/vnd.powerbuilder75": { - source: "iana" - }, - "application/vnd.powerbuilder75-s": { - source: "iana" - }, - "application/vnd.preminet": { - source: "iana" - }, - "application/vnd.previewsystems.box": { - source: "iana", - extensions: ["box"] - }, - "application/vnd.proteus.magazine": { - source: "iana", - extensions: ["mgz"] - }, - "application/vnd.psfs": { - source: "iana" - }, - "application/vnd.publishare-delta-tree": { - source: "iana", - extensions: ["qps"] - }, - "application/vnd.pvi.ptid1": { - source: "iana", - extensions: ["ptid"] - }, - "application/vnd.pwg-multiplexed": { - source: "iana" - }, - "application/vnd.pwg-xhtml-print+xml": { - source: "iana", - compressible: true - }, - "application/vnd.qualcomm.brew-app-res": { - source: "iana" - }, - "application/vnd.quarantainenet": { - source: "iana" - }, - "application/vnd.quark.quarkxpress": { - source: "iana", - extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"] - }, - "application/vnd.quobject-quoxdocument": { - source: "iana" - }, - "application/vnd.radisys.moml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-conf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-conn+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-dialog+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-stream+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-conf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-base+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-fax-detect+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-group+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-speech+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-transform+xml": { - source: "iana", - compressible: true - }, - "application/vnd.rainstor.data": { - source: "iana" - }, - "application/vnd.rapid": { - source: "iana" - }, - "application/vnd.rar": { - source: "iana", - extensions: ["rar"] - }, - "application/vnd.realvnc.bed": { - source: "iana", - extensions: ["bed"] - }, - "application/vnd.recordare.musicxml": { - source: "iana", - extensions: ["mxl"] - }, - "application/vnd.recordare.musicxml+xml": { - source: "iana", - compressible: true, - extensions: ["musicxml"] - }, - "application/vnd.renlearn.rlprint": { - source: "iana" - }, - "application/vnd.resilient.logic": { - source: "iana" - }, - "application/vnd.restful+json": { - source: "iana", - compressible: true - }, - "application/vnd.rig.cryptonote": { - source: "iana", - extensions: ["cryptonote"] - }, - "application/vnd.rim.cod": { - source: "apache", - extensions: ["cod"] - }, - "application/vnd.rn-realmedia": { - source: "apache", - extensions: ["rm"] - }, - "application/vnd.rn-realmedia-vbr": { - source: "apache", - extensions: ["rmvb"] - }, - "application/vnd.route66.link66+xml": { - source: "iana", - compressible: true, - extensions: ["link66"] - }, - "application/vnd.rs-274x": { - source: "iana" - }, - "application/vnd.ruckus.download": { - source: "iana" - }, - "application/vnd.s3sms": { - source: "iana" - }, - "application/vnd.sailingtracker.track": { - source: "iana", - extensions: ["st"] - }, - "application/vnd.sar": { - source: "iana" - }, - "application/vnd.sbm.cid": { - source: "iana" - }, - "application/vnd.sbm.mid2": { - source: "iana" - }, - "application/vnd.scribus": { - source: "iana" - }, - "application/vnd.sealed.3df": { - source: "iana" - }, - "application/vnd.sealed.csf": { - source: "iana" - }, - "application/vnd.sealed.doc": { - source: "iana" - }, - "application/vnd.sealed.eml": { - source: "iana" - }, - "application/vnd.sealed.mht": { - source: "iana" - }, - "application/vnd.sealed.net": { - source: "iana" - }, - "application/vnd.sealed.ppt": { - source: "iana" - }, - "application/vnd.sealed.tiff": { - source: "iana" - }, - "application/vnd.sealed.xls": { - source: "iana" - }, - "application/vnd.sealedmedia.softseal.html": { - source: "iana" - }, - "application/vnd.sealedmedia.softseal.pdf": { - source: "iana" - }, - "application/vnd.seemail": { - source: "iana", - extensions: ["see"] - }, - "application/vnd.seis+json": { - source: "iana", - compressible: true - }, - "application/vnd.sema": { - source: "iana", - extensions: ["sema"] - }, - "application/vnd.semd": { - source: "iana", - extensions: ["semd"] - }, - "application/vnd.semf": { - source: "iana", - extensions: ["semf"] - }, - "application/vnd.shade-save-file": { - source: "iana" - }, - "application/vnd.shana.informed.formdata": { - source: "iana", - extensions: ["ifm"] - }, - "application/vnd.shana.informed.formtemplate": { - source: "iana", - extensions: ["itp"] - }, - "application/vnd.shana.informed.interchange": { - source: "iana", - extensions: ["iif"] - }, - "application/vnd.shana.informed.package": { - source: "iana", - extensions: ["ipk"] - }, - "application/vnd.shootproof+json": { - source: "iana", - compressible: true - }, - "application/vnd.shopkick+json": { - source: "iana", - compressible: true - }, - "application/vnd.shp": { - source: "iana" - }, - "application/vnd.shx": { - source: "iana" - }, - "application/vnd.sigrok.session": { - source: "iana" - }, - "application/vnd.simtech-mindmapper": { - source: "iana", - extensions: ["twd", "twds"] - }, - "application/vnd.siren+json": { - source: "iana", - compressible: true - }, - "application/vnd.smaf": { - source: "iana", - extensions: ["mmf"] - }, - "application/vnd.smart.notebook": { - source: "iana" - }, - "application/vnd.smart.teacher": { - source: "iana", - extensions: ["teacher"] - }, - "application/vnd.snesdev-page-table": { - source: "iana" - }, - "application/vnd.software602.filler.form+xml": { - source: "iana", - compressible: true, - extensions: ["fo"] - }, - "application/vnd.software602.filler.form-xml-zip": { - source: "iana" - }, - "application/vnd.solent.sdkm+xml": { - source: "iana", - compressible: true, - extensions: ["sdkm", "sdkd"] - }, - "application/vnd.spotfire.dxp": { - source: "iana", - extensions: ["dxp"] - }, - "application/vnd.spotfire.sfs": { - source: "iana", - extensions: ["sfs"] - }, - "application/vnd.sqlite3": { - source: "iana" - }, - "application/vnd.sss-cod": { - source: "iana" - }, - "application/vnd.sss-dtf": { - source: "iana" - }, - "application/vnd.sss-ntf": { - source: "iana" - }, - "application/vnd.stardivision.calc": { - source: "apache", - extensions: ["sdc"] - }, - "application/vnd.stardivision.draw": { - source: "apache", - extensions: ["sda"] - }, - "application/vnd.stardivision.impress": { - source: "apache", - extensions: ["sdd"] - }, - "application/vnd.stardivision.math": { - source: "apache", - extensions: ["smf"] - }, - "application/vnd.stardivision.writer": { - source: "apache", - extensions: ["sdw", "vor"] - }, - "application/vnd.stardivision.writer-global": { - source: "apache", - extensions: ["sgl"] - }, - "application/vnd.stepmania.package": { - source: "iana", - extensions: ["smzip"] - }, - "application/vnd.stepmania.stepchart": { - source: "iana", - extensions: ["sm"] - }, - "application/vnd.street-stream": { - source: "iana" - }, - "application/vnd.sun.wadl+xml": { - source: "iana", - compressible: true, - extensions: ["wadl"] - }, - "application/vnd.sun.xml.calc": { - source: "apache", - extensions: ["sxc"] - }, - "application/vnd.sun.xml.calc.template": { - source: "apache", - extensions: ["stc"] - }, - "application/vnd.sun.xml.draw": { - source: "apache", - extensions: ["sxd"] - }, - "application/vnd.sun.xml.draw.template": { - source: "apache", - extensions: ["std"] - }, - "application/vnd.sun.xml.impress": { - source: "apache", - extensions: ["sxi"] - }, - "application/vnd.sun.xml.impress.template": { - source: "apache", - extensions: ["sti"] - }, - "application/vnd.sun.xml.math": { - source: "apache", - extensions: ["sxm"] - }, - "application/vnd.sun.xml.writer": { - source: "apache", - extensions: ["sxw"] - }, - "application/vnd.sun.xml.writer.global": { - source: "apache", - extensions: ["sxg"] - }, - "application/vnd.sun.xml.writer.template": { - source: "apache", - extensions: ["stw"] - }, - "application/vnd.sus-calendar": { - source: "iana", - extensions: ["sus", "susp"] - }, - "application/vnd.svd": { - source: "iana", - extensions: ["svd"] - }, - "application/vnd.swiftview-ics": { - source: "iana" - }, - "application/vnd.sycle+xml": { - source: "iana", - compressible: true - }, - "application/vnd.syft+json": { - source: "iana", - compressible: true - }, - "application/vnd.symbian.install": { - source: "apache", - extensions: ["sis", "sisx"] - }, - "application/vnd.syncml+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["xsm"] - }, - "application/vnd.syncml.dm+wbxml": { - source: "iana", - charset: "UTF-8", - extensions: ["bdm"] - }, - "application/vnd.syncml.dm+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["xdm"] - }, - "application/vnd.syncml.dm.notification": { - source: "iana" - }, - "application/vnd.syncml.dmddf+wbxml": { - source: "iana" - }, - "application/vnd.syncml.dmddf+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["ddf"] - }, - "application/vnd.syncml.dmtnds+wbxml": { - source: "iana" - }, - "application/vnd.syncml.dmtnds+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.syncml.ds.notification": { - source: "iana" - }, - "application/vnd.tableschema+json": { - source: "iana", - compressible: true - }, - "application/vnd.tao.intent-module-archive": { - source: "iana", - extensions: ["tao"] - }, - "application/vnd.tcpdump.pcap": { - source: "iana", - extensions: ["pcap", "cap", "dmp"] - }, - "application/vnd.think-cell.ppttc+json": { - source: "iana", - compressible: true - }, - "application/vnd.tmd.mediaflex.api+xml": { - source: "iana", - compressible: true - }, - "application/vnd.tml": { - source: "iana" - }, - "application/vnd.tmobile-livetv": { - source: "iana", - extensions: ["tmo"] - }, - "application/vnd.tri.onesource": { - source: "iana" - }, - "application/vnd.trid.tpt": { - source: "iana", - extensions: ["tpt"] - }, - "application/vnd.triscape.mxs": { - source: "iana", - extensions: ["mxs"] - }, - "application/vnd.trueapp": { - source: "iana", - extensions: ["tra"] - }, - "application/vnd.truedoc": { - source: "iana" - }, - "application/vnd.ubisoft.webplayer": { - source: "iana" - }, - "application/vnd.ufdl": { - source: "iana", - extensions: ["ufd", "ufdl"] - }, - "application/vnd.uiq.theme": { - source: "iana", - extensions: ["utz"] - }, - "application/vnd.umajin": { - source: "iana", - extensions: ["umj"] - }, - "application/vnd.unity": { - source: "iana", - extensions: ["unityweb"] - }, - "application/vnd.uoml+xml": { - source: "iana", - compressible: true, - extensions: ["uoml"] - }, - "application/vnd.uplanet.alert": { - source: "iana" - }, - "application/vnd.uplanet.alert-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.bearer-choice": { - source: "iana" - }, - "application/vnd.uplanet.bearer-choice-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.cacheop": { - source: "iana" - }, - "application/vnd.uplanet.cacheop-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.channel": { - source: "iana" - }, - "application/vnd.uplanet.channel-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.list": { - source: "iana" - }, - "application/vnd.uplanet.list-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.listcmd": { - source: "iana" - }, - "application/vnd.uplanet.listcmd-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.signal": { - source: "iana" - }, - "application/vnd.uri-map": { - source: "iana" - }, - "application/vnd.valve.source.material": { - source: "iana" - }, - "application/vnd.vcx": { - source: "iana", - extensions: ["vcx"] - }, - "application/vnd.vd-study": { - source: "iana" - }, - "application/vnd.vectorworks": { - source: "iana" - }, - "application/vnd.vel+json": { - source: "iana", - compressible: true - }, - "application/vnd.verimatrix.vcas": { - source: "iana" - }, - "application/vnd.veritone.aion+json": { - source: "iana", - compressible: true - }, - "application/vnd.veryant.thin": { - source: "iana" - }, - "application/vnd.ves.encrypted": { - source: "iana" - }, - "application/vnd.vidsoft.vidconference": { - source: "iana" - }, - "application/vnd.visio": { - source: "iana", - extensions: ["vsd", "vst", "vss", "vsw"] - }, - "application/vnd.visionary": { - source: "iana", - extensions: ["vis"] - }, - "application/vnd.vividence.scriptfile": { - source: "iana" - }, - "application/vnd.vsf": { - source: "iana", - extensions: ["vsf"] - }, - "application/vnd.wap.sic": { - source: "iana" - }, - "application/vnd.wap.slc": { - source: "iana" - }, - "application/vnd.wap.wbxml": { - source: "iana", - charset: "UTF-8", - extensions: ["wbxml"] - }, - "application/vnd.wap.wmlc": { - source: "iana", - extensions: ["wmlc"] - }, - "application/vnd.wap.wmlscriptc": { - source: "iana", - extensions: ["wmlsc"] - }, - "application/vnd.webturbo": { - source: "iana", - extensions: ["wtb"] - }, - "application/vnd.wfa.dpp": { - source: "iana" - }, - "application/vnd.wfa.p2p": { - source: "iana" - }, - "application/vnd.wfa.wsc": { - source: "iana" - }, - "application/vnd.windows.devicepairing": { - source: "iana" - }, - "application/vnd.wmc": { - source: "iana" - }, - "application/vnd.wmf.bootstrap": { - source: "iana" - }, - "application/vnd.wolfram.mathematica": { - source: "iana" - }, - "application/vnd.wolfram.mathematica.package": { - source: "iana" - }, - "application/vnd.wolfram.player": { - source: "iana", - extensions: ["nbp"] - }, - "application/vnd.wordperfect": { - source: "iana", - extensions: ["wpd"] - }, - "application/vnd.wqd": { - source: "iana", - extensions: ["wqd"] - }, - "application/vnd.wrq-hp3000-labelled": { - source: "iana" - }, - "application/vnd.wt.stf": { - source: "iana", - extensions: ["stf"] - }, - "application/vnd.wv.csp+wbxml": { - source: "iana" - }, - "application/vnd.wv.csp+xml": { - source: "iana", - compressible: true - }, - "application/vnd.wv.ssp+xml": { - source: "iana", - compressible: true - }, - "application/vnd.xacml+json": { - source: "iana", - compressible: true - }, - "application/vnd.xara": { - source: "iana", - extensions: ["xar"] - }, - "application/vnd.xfdl": { - source: "iana", - extensions: ["xfdl"] - }, - "application/vnd.xfdl.webform": { - source: "iana" - }, - "application/vnd.xmi+xml": { - source: "iana", - compressible: true - }, - "application/vnd.xmpie.cpkg": { - source: "iana" - }, - "application/vnd.xmpie.dpkg": { - source: "iana" - }, - "application/vnd.xmpie.plan": { - source: "iana" - }, - "application/vnd.xmpie.ppkg": { - source: "iana" - }, - "application/vnd.xmpie.xlim": { - source: "iana" - }, - "application/vnd.yamaha.hv-dic": { - source: "iana", - extensions: ["hvd"] - }, - "application/vnd.yamaha.hv-script": { - source: "iana", - extensions: ["hvs"] - }, - "application/vnd.yamaha.hv-voice": { - source: "iana", - extensions: ["hvp"] - }, - "application/vnd.yamaha.openscoreformat": { - source: "iana", - extensions: ["osf"] - }, - "application/vnd.yamaha.openscoreformat.osfpvg+xml": { - source: "iana", - compressible: true, - extensions: ["osfpvg"] - }, - "application/vnd.yamaha.remote-setup": { - source: "iana" - }, - "application/vnd.yamaha.smaf-audio": { - source: "iana", - extensions: ["saf"] - }, - "application/vnd.yamaha.smaf-phrase": { - source: "iana", - extensions: ["spf"] - }, - "application/vnd.yamaha.through-ngn": { - source: "iana" - }, - "application/vnd.yamaha.tunnel-udpencap": { - source: "iana" - }, - "application/vnd.yaoweme": { - source: "iana" - }, - "application/vnd.yellowriver-custom-menu": { - source: "iana", - extensions: ["cmp"] - }, - "application/vnd.youtube.yt": { - source: "iana" - }, - "application/vnd.zul": { - source: "iana", - extensions: ["zir", "zirz"] - }, - "application/vnd.zzazz.deck+xml": { - source: "iana", - compressible: true, - extensions: ["zaz"] - }, - "application/voicexml+xml": { - source: "iana", - compressible: true, - extensions: ["vxml"] - }, - "application/voucher-cms+json": { - source: "iana", - compressible: true - }, - "application/vq-rtcpxr": { - source: "iana" - }, - "application/wasm": { - source: "iana", - compressible: true, - extensions: ["wasm"] - }, - "application/watcherinfo+xml": { - source: "iana", - compressible: true, - extensions: ["wif"] - }, - "application/webpush-options+json": { - source: "iana", - compressible: true - }, - "application/whoispp-query": { - source: "iana" - }, - "application/whoispp-response": { - source: "iana" - }, - "application/widget": { - source: "iana", - extensions: ["wgt"] - }, - "application/winhlp": { - source: "apache", - extensions: ["hlp"] - }, - "application/wita": { - source: "iana" - }, - "application/wordperfect5.1": { - source: "iana" - }, - "application/wsdl+xml": { - source: "iana", - compressible: true, - extensions: ["wsdl"] - }, - "application/wspolicy+xml": { - source: "iana", - compressible: true, - extensions: ["wspolicy"] - }, - "application/x-7z-compressed": { - source: "apache", - compressible: false, - extensions: ["7z"] - }, - "application/x-abiword": { - source: "apache", - extensions: ["abw"] - }, - "application/x-ace-compressed": { - source: "apache", - extensions: ["ace"] - }, - "application/x-amf": { - source: "apache" - }, - "application/x-apple-diskimage": { - source: "apache", - extensions: ["dmg"] - }, - "application/x-arj": { - compressible: false, - extensions: ["arj"] - }, - "application/x-authorware-bin": { - source: "apache", - extensions: ["aab", "x32", "u32", "vox"] - }, - "application/x-authorware-map": { - source: "apache", - extensions: ["aam"] - }, - "application/x-authorware-seg": { - source: "apache", - extensions: ["aas"] - }, - "application/x-bcpio": { - source: "apache", - extensions: ["bcpio"] - }, - "application/x-bdoc": { - compressible: false, - extensions: ["bdoc"] - }, - "application/x-bittorrent": { - source: "apache", - extensions: ["torrent"] - }, - "application/x-blorb": { - source: "apache", - extensions: ["blb", "blorb"] - }, - "application/x-bzip": { - source: "apache", - compressible: false, - extensions: ["bz"] - }, - "application/x-bzip2": { - source: "apache", - compressible: false, - extensions: ["bz2", "boz"] - }, - "application/x-cbr": { - source: "apache", - extensions: ["cbr", "cba", "cbt", "cbz", "cb7"] - }, - "application/x-cdlink": { - source: "apache", - extensions: ["vcd"] - }, - "application/x-cfs-compressed": { - source: "apache", - extensions: ["cfs"] - }, - "application/x-chat": { - source: "apache", - extensions: ["chat"] - }, - "application/x-chess-pgn": { - source: "apache", - extensions: ["pgn"] - }, - "application/x-chrome-extension": { - extensions: ["crx"] - }, - "application/x-cocoa": { - source: "nginx", - extensions: ["cco"] - }, - "application/x-compress": { - source: "apache" - }, - "application/x-conference": { - source: "apache", - extensions: ["nsc"] - }, - "application/x-cpio": { - source: "apache", - extensions: ["cpio"] - }, - "application/x-csh": { - source: "apache", - extensions: ["csh"] - }, - "application/x-deb": { - compressible: false - }, - "application/x-debian-package": { - source: "apache", - extensions: ["deb", "udeb"] - }, - "application/x-dgc-compressed": { - source: "apache", - extensions: ["dgc"] - }, - "application/x-director": { - source: "apache", - extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"] - }, - "application/x-doom": { - source: "apache", - extensions: ["wad"] - }, - "application/x-dtbncx+xml": { - source: "apache", - compressible: true, - extensions: ["ncx"] - }, - "application/x-dtbook+xml": { - source: "apache", - compressible: true, - extensions: ["dtb"] - }, - "application/x-dtbresource+xml": { - source: "apache", - compressible: true, - extensions: ["res"] - }, - "application/x-dvi": { - source: "apache", - compressible: false, - extensions: ["dvi"] - }, - "application/x-envoy": { - source: "apache", - extensions: ["evy"] - }, - "application/x-eva": { - source: "apache", - extensions: ["eva"] - }, - "application/x-font-bdf": { - source: "apache", - extensions: ["bdf"] - }, - "application/x-font-dos": { - source: "apache" - }, - "application/x-font-framemaker": { - source: "apache" - }, - "application/x-font-ghostscript": { - source: "apache", - extensions: ["gsf"] - }, - "application/x-font-libgrx": { - source: "apache" - }, - "application/x-font-linux-psf": { - source: "apache", - extensions: ["psf"] - }, - "application/x-font-pcf": { - source: "apache", - extensions: ["pcf"] - }, - "application/x-font-snf": { - source: "apache", - extensions: ["snf"] - }, - "application/x-font-speedo": { - source: "apache" - }, - "application/x-font-sunos-news": { - source: "apache" - }, - "application/x-font-type1": { - source: "apache", - extensions: ["pfa", "pfb", "pfm", "afm"] - }, - "application/x-font-vfont": { - source: "apache" - }, - "application/x-freearc": { - source: "apache", - extensions: ["arc"] - }, - "application/x-futuresplash": { - source: "apache", - extensions: ["spl"] - }, - "application/x-gca-compressed": { - source: "apache", - extensions: ["gca"] - }, - "application/x-glulx": { - source: "apache", - extensions: ["ulx"] - }, - "application/x-gnumeric": { - source: "apache", - extensions: ["gnumeric"] - }, - "application/x-gramps-xml": { - source: "apache", - extensions: ["gramps"] - }, - "application/x-gtar": { - source: "apache", - extensions: ["gtar"] - }, - "application/x-gzip": { - source: "apache" - }, - "application/x-hdf": { - source: "apache", - extensions: ["hdf"] - }, - "application/x-httpd-php": { - compressible: true, - extensions: ["php"] - }, - "application/x-install-instructions": { - source: "apache", - extensions: ["install"] - }, - "application/x-iso9660-image": { - source: "apache", - extensions: ["iso"] - }, - "application/x-iwork-keynote-sffkey": { - extensions: ["key"] - }, - "application/x-iwork-numbers-sffnumbers": { - extensions: ["numbers"] - }, - "application/x-iwork-pages-sffpages": { - extensions: ["pages"] - }, - "application/x-java-archive-diff": { - source: "nginx", - extensions: ["jardiff"] - }, - "application/x-java-jnlp-file": { - source: "apache", - compressible: false, - extensions: ["jnlp"] - }, - "application/x-javascript": { - compressible: true - }, - "application/x-keepass2": { - extensions: ["kdbx"] - }, - "application/x-latex": { - source: "apache", - compressible: false, - extensions: ["latex"] - }, - "application/x-lua-bytecode": { - extensions: ["luac"] - }, - "application/x-lzh-compressed": { - source: "apache", - extensions: ["lzh", "lha"] - }, - "application/x-makeself": { - source: "nginx", - extensions: ["run"] - }, - "application/x-mie": { - source: "apache", - extensions: ["mie"] - }, - "application/x-mobipocket-ebook": { - source: "apache", - extensions: ["prc", "mobi"] - }, - "application/x-mpegurl": { - compressible: false - }, - "application/x-ms-application": { - source: "apache", - extensions: ["application"] - }, - "application/x-ms-shortcut": { - source: "apache", - extensions: ["lnk"] - }, - "application/x-ms-wmd": { - source: "apache", - extensions: ["wmd"] - }, - "application/x-ms-wmz": { - source: "apache", - extensions: ["wmz"] - }, - "application/x-ms-xbap": { - source: "apache", - extensions: ["xbap"] - }, - "application/x-msaccess": { - source: "apache", - extensions: ["mdb"] - }, - "application/x-msbinder": { - source: "apache", - extensions: ["obd"] - }, - "application/x-mscardfile": { - source: "apache", - extensions: ["crd"] - }, - "application/x-msclip": { - source: "apache", - extensions: ["clp"] - }, - "application/x-msdos-program": { - extensions: ["exe"] - }, - "application/x-msdownload": { - source: "apache", - extensions: ["exe", "dll", "com", "bat", "msi"] - }, - "application/x-msmediaview": { - source: "apache", - extensions: ["mvb", "m13", "m14"] - }, - "application/x-msmetafile": { - source: "apache", - extensions: ["wmf", "wmz", "emf", "emz"] - }, - "application/x-msmoney": { - source: "apache", - extensions: ["mny"] - }, - "application/x-mspublisher": { - source: "apache", - extensions: ["pub"] - }, - "application/x-msschedule": { - source: "apache", - extensions: ["scd"] - }, - "application/x-msterminal": { - source: "apache", - extensions: ["trm"] - }, - "application/x-mswrite": { - source: "apache", - extensions: ["wri"] - }, - "application/x-netcdf": { - source: "apache", - extensions: ["nc", "cdf"] - }, - "application/x-ns-proxy-autoconfig": { - compressible: true, - extensions: ["pac"] - }, - "application/x-nzb": { - source: "apache", - extensions: ["nzb"] - }, - "application/x-perl": { - source: "nginx", - extensions: ["pl", "pm"] - }, - "application/x-pilot": { - source: "nginx", - extensions: ["prc", "pdb"] - }, - "application/x-pkcs12": { - source: "apache", - compressible: false, - extensions: ["p12", "pfx"] - }, - "application/x-pkcs7-certificates": { - source: "apache", - extensions: ["p7b", "spc"] - }, - "application/x-pkcs7-certreqresp": { - source: "apache", - extensions: ["p7r"] - }, - "application/x-pki-message": { - source: "iana" - }, - "application/x-rar-compressed": { - source: "apache", - compressible: false, - extensions: ["rar"] - }, - "application/x-redhat-package-manager": { - source: "nginx", - extensions: ["rpm"] - }, - "application/x-research-info-systems": { - source: "apache", - extensions: ["ris"] - }, - "application/x-sea": { - source: "nginx", - extensions: ["sea"] - }, - "application/x-sh": { - source: "apache", - compressible: true, - extensions: ["sh"] - }, - "application/x-shar": { - source: "apache", - extensions: ["shar"] - }, - "application/x-shockwave-flash": { - source: "apache", - compressible: false, - extensions: ["swf"] - }, - "application/x-silverlight-app": { - source: "apache", - extensions: ["xap"] - }, - "application/x-sql": { - source: "apache", - extensions: ["sql"] - }, - "application/x-stuffit": { - source: "apache", - compressible: false, - extensions: ["sit"] - }, - "application/x-stuffitx": { - source: "apache", - extensions: ["sitx"] - }, - "application/x-subrip": { - source: "apache", - extensions: ["srt"] - }, - "application/x-sv4cpio": { - source: "apache", - extensions: ["sv4cpio"] - }, - "application/x-sv4crc": { - source: "apache", - extensions: ["sv4crc"] - }, - "application/x-t3vm-image": { - source: "apache", - extensions: ["t3"] - }, - "application/x-tads": { - source: "apache", - extensions: ["gam"] - }, - "application/x-tar": { - source: "apache", - compressible: true, - extensions: ["tar"] - }, - "application/x-tcl": { - source: "apache", - extensions: ["tcl", "tk"] - }, - "application/x-tex": { - source: "apache", - extensions: ["tex"] - }, - "application/x-tex-tfm": { - source: "apache", - extensions: ["tfm"] - }, - "application/x-texinfo": { - source: "apache", - extensions: ["texinfo", "texi"] - }, - "application/x-tgif": { - source: "apache", - extensions: ["obj"] - }, - "application/x-ustar": { - source: "apache", - extensions: ["ustar"] - }, - "application/x-virtualbox-hdd": { - compressible: true, - extensions: ["hdd"] - }, - "application/x-virtualbox-ova": { - compressible: true, - extensions: ["ova"] - }, - "application/x-virtualbox-ovf": { - compressible: true, - extensions: ["ovf"] - }, - "application/x-virtualbox-vbox": { - compressible: true, - extensions: ["vbox"] - }, - "application/x-virtualbox-vbox-extpack": { - compressible: false, - extensions: ["vbox-extpack"] - }, - "application/x-virtualbox-vdi": { - compressible: true, - extensions: ["vdi"] - }, - "application/x-virtualbox-vhd": { - compressible: true, - extensions: ["vhd"] - }, - "application/x-virtualbox-vmdk": { - compressible: true, - extensions: ["vmdk"] - }, - "application/x-wais-source": { - source: "apache", - extensions: ["src"] - }, - "application/x-web-app-manifest+json": { - compressible: true, - extensions: ["webapp"] - }, - "application/x-www-form-urlencoded": { - source: "iana", - compressible: true - }, - "application/x-x509-ca-cert": { - source: "iana", - extensions: ["der", "crt", "pem"] - }, - "application/x-x509-ca-ra-cert": { - source: "iana" - }, - "application/x-x509-next-ca-cert": { - source: "iana" - }, - "application/x-xfig": { - source: "apache", - extensions: ["fig"] - }, - "application/x-xliff+xml": { - source: "apache", - compressible: true, - extensions: ["xlf"] - }, - "application/x-xpinstall": { - source: "apache", - compressible: false, - extensions: ["xpi"] - }, - "application/x-xz": { - source: "apache", - extensions: ["xz"] - }, - "application/x-zmachine": { - source: "apache", - extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"] - }, - "application/x400-bp": { - source: "iana" - }, - "application/xacml+xml": { - source: "iana", - compressible: true - }, - "application/xaml+xml": { - source: "apache", - compressible: true, - extensions: ["xaml"] - }, - "application/xcap-att+xml": { - source: "iana", - compressible: true, - extensions: ["xav"] - }, - "application/xcap-caps+xml": { - source: "iana", - compressible: true, - extensions: ["xca"] - }, - "application/xcap-diff+xml": { - source: "iana", - compressible: true, - extensions: ["xdf"] - }, - "application/xcap-el+xml": { - source: "iana", - compressible: true, - extensions: ["xel"] - }, - "application/xcap-error+xml": { - source: "iana", - compressible: true - }, - "application/xcap-ns+xml": { - source: "iana", - compressible: true, - extensions: ["xns"] - }, - "application/xcon-conference-info+xml": { - source: "iana", - compressible: true - }, - "application/xcon-conference-info-diff+xml": { - source: "iana", - compressible: true - }, - "application/xenc+xml": { - source: "iana", - compressible: true, - extensions: ["xenc"] - }, - "application/xhtml+xml": { - source: "iana", - compressible: true, - extensions: ["xhtml", "xht"] - }, - "application/xhtml-voice+xml": { - source: "apache", - compressible: true - }, - "application/xliff+xml": { - source: "iana", - compressible: true, - extensions: ["xlf"] - }, - "application/xml": { - source: "iana", - compressible: true, - extensions: ["xml", "xsl", "xsd", "rng"] - }, - "application/xml-dtd": { - source: "iana", - compressible: true, - extensions: ["dtd"] - }, - "application/xml-external-parsed-entity": { - source: "iana" - }, - "application/xml-patch+xml": { - source: "iana", - compressible: true - }, - "application/xmpp+xml": { - source: "iana", - compressible: true - }, - "application/xop+xml": { - source: "iana", - compressible: true, - extensions: ["xop"] - }, - "application/xproc+xml": { - source: "apache", - compressible: true, - extensions: ["xpl"] - }, - "application/xslt+xml": { - source: "iana", - compressible: true, - extensions: ["xsl", "xslt"] - }, - "application/xspf+xml": { - source: "apache", - compressible: true, - extensions: ["xspf"] - }, - "application/xv+xml": { - source: "iana", - compressible: true, - extensions: ["mxml", "xhvml", "xvml", "xvm"] - }, - "application/yang": { - source: "iana", - extensions: ["yang"] - }, - "application/yang-data+json": { - source: "iana", - compressible: true - }, - "application/yang-data+xml": { - source: "iana", - compressible: true - }, - "application/yang-patch+json": { - source: "iana", - compressible: true - }, - "application/yang-patch+xml": { - source: "iana", - compressible: true - }, - "application/yin+xml": { - source: "iana", - compressible: true, - extensions: ["yin"] - }, - "application/zip": { - source: "iana", - compressible: false, - extensions: ["zip"] - }, - "application/zlib": { - source: "iana" - }, - "application/zstd": { - source: "iana" - }, - "audio/1d-interleaved-parityfec": { - source: "iana" - }, - "audio/32kadpcm": { - source: "iana" - }, - "audio/3gpp": { - source: "iana", - compressible: false, - extensions: ["3gpp"] - }, - "audio/3gpp2": { - source: "iana" - }, - "audio/aac": { - source: "iana" - }, - "audio/ac3": { - source: "iana" - }, - "audio/adpcm": { - source: "apache", - extensions: ["adp"] - }, - "audio/amr": { - source: "iana", - extensions: ["amr"] - }, - "audio/amr-wb": { - source: "iana" - }, - "audio/amr-wb+": { - source: "iana" - }, - "audio/aptx": { - source: "iana" - }, - "audio/asc": { - source: "iana" - }, - "audio/atrac-advanced-lossless": { - source: "iana" - }, - "audio/atrac-x": { - source: "iana" - }, - "audio/atrac3": { - source: "iana" - }, - "audio/basic": { - source: "iana", - compressible: false, - extensions: ["au", "snd"] - }, - "audio/bv16": { - source: "iana" - }, - "audio/bv32": { - source: "iana" - }, - "audio/clearmode": { - source: "iana" - }, - "audio/cn": { - source: "iana" - }, - "audio/dat12": { - source: "iana" - }, - "audio/dls": { - source: "iana" - }, - "audio/dsr-es201108": { - source: "iana" - }, - "audio/dsr-es202050": { - source: "iana" - }, - "audio/dsr-es202211": { - source: "iana" - }, - "audio/dsr-es202212": { - source: "iana" - }, - "audio/dv": { - source: "iana" - }, - "audio/dvi4": { - source: "iana" - }, - "audio/eac3": { - source: "iana" - }, - "audio/encaprtp": { - source: "iana" - }, - "audio/evrc": { - source: "iana" - }, - "audio/evrc-qcp": { - source: "iana" - }, - "audio/evrc0": { - source: "iana" - }, - "audio/evrc1": { - source: "iana" - }, - "audio/evrcb": { - source: "iana" - }, - "audio/evrcb0": { - source: "iana" - }, - "audio/evrcb1": { - source: "iana" - }, - "audio/evrcnw": { - source: "iana" - }, - "audio/evrcnw0": { - source: "iana" - }, - "audio/evrcnw1": { - source: "iana" - }, - "audio/evrcwb": { - source: "iana" - }, - "audio/evrcwb0": { - source: "iana" - }, - "audio/evrcwb1": { - source: "iana" - }, - "audio/evs": { - source: "iana" - }, - "audio/flexfec": { - source: "iana" - }, - "audio/fwdred": { - source: "iana" - }, - "audio/g711-0": { - source: "iana" - }, - "audio/g719": { - source: "iana" - }, - "audio/g722": { - source: "iana" - }, - "audio/g7221": { - source: "iana" - }, - "audio/g723": { - source: "iana" - }, - "audio/g726-16": { - source: "iana" - }, - "audio/g726-24": { - source: "iana" - }, - "audio/g726-32": { - source: "iana" - }, - "audio/g726-40": { - source: "iana" - }, - "audio/g728": { - source: "iana" - }, - "audio/g729": { - source: "iana" - }, - "audio/g7291": { - source: "iana" - }, - "audio/g729d": { - source: "iana" - }, - "audio/g729e": { - source: "iana" - }, - "audio/gsm": { - source: "iana" - }, - "audio/gsm-efr": { - source: "iana" - }, - "audio/gsm-hr-08": { - source: "iana" - }, - "audio/ilbc": { - source: "iana" - }, - "audio/ip-mr_v2.5": { - source: "iana" - }, - "audio/isac": { - source: "apache" - }, - "audio/l16": { - source: "iana" - }, - "audio/l20": { - source: "iana" - }, - "audio/l24": { - source: "iana", - compressible: false - }, - "audio/l8": { - source: "iana" - }, - "audio/lpc": { - source: "iana" - }, - "audio/melp": { - source: "iana" - }, - "audio/melp1200": { - source: "iana" - }, - "audio/melp2400": { - source: "iana" - }, - "audio/melp600": { - source: "iana" - }, - "audio/mhas": { - source: "iana" - }, - "audio/midi": { - source: "apache", - extensions: ["mid", "midi", "kar", "rmi"] - }, - "audio/mobile-xmf": { - source: "iana", - extensions: ["mxmf"] - }, - "audio/mp3": { - compressible: false, - extensions: ["mp3"] - }, - "audio/mp4": { - source: "iana", - compressible: false, - extensions: ["m4a", "mp4a"] - }, - "audio/mp4a-latm": { - source: "iana" - }, - "audio/mpa": { - source: "iana" - }, - "audio/mpa-robust": { - source: "iana" - }, - "audio/mpeg": { - source: "iana", - compressible: false, - extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"] - }, - "audio/mpeg4-generic": { - source: "iana" - }, - "audio/musepack": { - source: "apache" - }, - "audio/ogg": { - source: "iana", - compressible: false, - extensions: ["oga", "ogg", "spx", "opus"] - }, - "audio/opus": { - source: "iana" - }, - "audio/parityfec": { - source: "iana" - }, - "audio/pcma": { - source: "iana" - }, - "audio/pcma-wb": { - source: "iana" - }, - "audio/pcmu": { - source: "iana" - }, - "audio/pcmu-wb": { - source: "iana" - }, - "audio/prs.sid": { - source: "iana" - }, - "audio/qcelp": { - source: "iana" - }, - "audio/raptorfec": { - source: "iana" - }, - "audio/red": { - source: "iana" - }, - "audio/rtp-enc-aescm128": { - source: "iana" - }, - "audio/rtp-midi": { - source: "iana" - }, - "audio/rtploopback": { - source: "iana" - }, - "audio/rtx": { - source: "iana" - }, - "audio/s3m": { - source: "apache", - extensions: ["s3m"] - }, - "audio/scip": { - source: "iana" - }, - "audio/silk": { - source: "apache", - extensions: ["sil"] - }, - "audio/smv": { - source: "iana" - }, - "audio/smv-qcp": { - source: "iana" - }, - "audio/smv0": { - source: "iana" - }, - "audio/sofa": { - source: "iana" - }, - "audio/sp-midi": { - source: "iana" - }, - "audio/speex": { - source: "iana" - }, - "audio/t140c": { - source: "iana" - }, - "audio/t38": { - source: "iana" - }, - "audio/telephone-event": { - source: "iana" - }, - "audio/tetra_acelp": { - source: "iana" - }, - "audio/tetra_acelp_bb": { - source: "iana" - }, - "audio/tone": { - source: "iana" - }, - "audio/tsvcis": { - source: "iana" - }, - "audio/uemclip": { - source: "iana" - }, - "audio/ulpfec": { - source: "iana" - }, - "audio/usac": { - source: "iana" - }, - "audio/vdvi": { - source: "iana" - }, - "audio/vmr-wb": { - source: "iana" - }, - "audio/vnd.3gpp.iufp": { - source: "iana" - }, - "audio/vnd.4sb": { - source: "iana" - }, - "audio/vnd.audiokoz": { - source: "iana" - }, - "audio/vnd.celp": { - source: "iana" - }, - "audio/vnd.cisco.nse": { - source: "iana" - }, - "audio/vnd.cmles.radio-events": { - source: "iana" - }, - "audio/vnd.cns.anp1": { - source: "iana" - }, - "audio/vnd.cns.inf1": { - source: "iana" - }, - "audio/vnd.dece.audio": { - source: "iana", - extensions: ["uva", "uvva"] - }, - "audio/vnd.digital-winds": { - source: "iana", - extensions: ["eol"] - }, - "audio/vnd.dlna.adts": { - source: "iana" - }, - "audio/vnd.dolby.heaac.1": { - source: "iana" - }, - "audio/vnd.dolby.heaac.2": { - source: "iana" - }, - "audio/vnd.dolby.mlp": { - source: "iana" - }, - "audio/vnd.dolby.mps": { - source: "iana" - }, - "audio/vnd.dolby.pl2": { - source: "iana" - }, - "audio/vnd.dolby.pl2x": { - source: "iana" - }, - "audio/vnd.dolby.pl2z": { - source: "iana" - }, - "audio/vnd.dolby.pulse.1": { - source: "iana" - }, - "audio/vnd.dra": { - source: "iana", - extensions: ["dra"] - }, - "audio/vnd.dts": { - source: "iana", - extensions: ["dts"] - }, - "audio/vnd.dts.hd": { - source: "iana", - extensions: ["dtshd"] - }, - "audio/vnd.dts.uhd": { - source: "iana" - }, - "audio/vnd.dvb.file": { - source: "iana" - }, - "audio/vnd.everad.plj": { - source: "iana" - }, - "audio/vnd.hns.audio": { - source: "iana" - }, - "audio/vnd.lucent.voice": { - source: "iana", - extensions: ["lvp"] - }, - "audio/vnd.ms-playready.media.pya": { - source: "iana", - extensions: ["pya"] - }, - "audio/vnd.nokia.mobile-xmf": { - source: "iana" - }, - "audio/vnd.nortel.vbk": { - source: "iana" - }, - "audio/vnd.nuera.ecelp4800": { - source: "iana", - extensions: ["ecelp4800"] - }, - "audio/vnd.nuera.ecelp7470": { - source: "iana", - extensions: ["ecelp7470"] - }, - "audio/vnd.nuera.ecelp9600": { - source: "iana", - extensions: ["ecelp9600"] - }, - "audio/vnd.octel.sbc": { - source: "iana" - }, - "audio/vnd.presonus.multitrack": { - source: "iana" - }, - "audio/vnd.qcelp": { - source: "iana" - }, - "audio/vnd.rhetorex.32kadpcm": { - source: "iana" - }, - "audio/vnd.rip": { - source: "iana", - extensions: ["rip"] - }, - "audio/vnd.rn-realaudio": { - compressible: false - }, - "audio/vnd.sealedmedia.softseal.mpeg": { - source: "iana" - }, - "audio/vnd.vmx.cvsd": { - source: "iana" - }, - "audio/vnd.wave": { - compressible: false - }, - "audio/vorbis": { - source: "iana", - compressible: false - }, - "audio/vorbis-config": { - source: "iana" - }, - "audio/wav": { - compressible: false, - extensions: ["wav"] - }, - "audio/wave": { - compressible: false, - extensions: ["wav"] - }, - "audio/webm": { - source: "apache", - compressible: false, - extensions: ["weba"] - }, - "audio/x-aac": { - source: "apache", - compressible: false, - extensions: ["aac"] - }, - "audio/x-aiff": { - source: "apache", - extensions: ["aif", "aiff", "aifc"] - }, - "audio/x-caf": { - source: "apache", - compressible: false, - extensions: ["caf"] - }, - "audio/x-flac": { - source: "apache", - extensions: ["flac"] - }, - "audio/x-m4a": { - source: "nginx", - extensions: ["m4a"] - }, - "audio/x-matroska": { - source: "apache", - extensions: ["mka"] - }, - "audio/x-mpegurl": { - source: "apache", - extensions: ["m3u"] - }, - "audio/x-ms-wax": { - source: "apache", - extensions: ["wax"] - }, - "audio/x-ms-wma": { - source: "apache", - extensions: ["wma"] - }, - "audio/x-pn-realaudio": { - source: "apache", - extensions: ["ram", "ra"] - }, - "audio/x-pn-realaudio-plugin": { - source: "apache", - extensions: ["rmp"] - }, - "audio/x-realaudio": { - source: "nginx", - extensions: ["ra"] - }, - "audio/x-tta": { - source: "apache" - }, - "audio/x-wav": { - source: "apache", - extensions: ["wav"] - }, - "audio/xm": { - source: "apache", - extensions: ["xm"] - }, - "chemical/x-cdx": { - source: "apache", - extensions: ["cdx"] - }, - "chemical/x-cif": { - source: "apache", - extensions: ["cif"] - }, - "chemical/x-cmdf": { - source: "apache", - extensions: ["cmdf"] - }, - "chemical/x-cml": { - source: "apache", - extensions: ["cml"] - }, - "chemical/x-csml": { - source: "apache", - extensions: ["csml"] - }, - "chemical/x-pdb": { - source: "apache" - }, - "chemical/x-xyz": { - source: "apache", - extensions: ["xyz"] - }, - "font/collection": { - source: "iana", - extensions: ["ttc"] - }, - "font/otf": { - source: "iana", - compressible: true, - extensions: ["otf"] - }, - "font/sfnt": { - source: "iana" - }, - "font/ttf": { - source: "iana", - compressible: true, - extensions: ["ttf"] - }, - "font/woff": { - source: "iana", - extensions: ["woff"] - }, - "font/woff2": { - source: "iana", - extensions: ["woff2"] - }, - "image/aces": { - source: "iana", - extensions: ["exr"] - }, - "image/apng": { - compressible: false, - extensions: ["apng"] - }, - "image/avci": { - source: "iana", - extensions: ["avci"] - }, - "image/avcs": { - source: "iana", - extensions: ["avcs"] - }, - "image/avif": { - source: "iana", - compressible: false, - extensions: ["avif"] - }, - "image/bmp": { - source: "iana", - compressible: true, - extensions: ["bmp"] - }, - "image/cgm": { - source: "iana", - extensions: ["cgm"] - }, - "image/dicom-rle": { - source: "iana", - extensions: ["drle"] - }, - "image/emf": { - source: "iana", - extensions: ["emf"] - }, - "image/fits": { - source: "iana", - extensions: ["fits"] - }, - "image/g3fax": { - source: "iana", - extensions: ["g3"] - }, - "image/gif": { - source: "iana", - compressible: false, - extensions: ["gif"] - }, - "image/heic": { - source: "iana", - extensions: ["heic"] - }, - "image/heic-sequence": { - source: "iana", - extensions: ["heics"] - }, - "image/heif": { - source: "iana", - extensions: ["heif"] - }, - "image/heif-sequence": { - source: "iana", - extensions: ["heifs"] - }, - "image/hej2k": { - source: "iana", - extensions: ["hej2"] - }, - "image/hsj2": { - source: "iana", - extensions: ["hsj2"] - }, - "image/ief": { - source: "iana", - extensions: ["ief"] - }, - "image/jls": { - source: "iana", - extensions: ["jls"] - }, - "image/jp2": { - source: "iana", - compressible: false, - extensions: ["jp2", "jpg2"] - }, - "image/jpeg": { - source: "iana", - compressible: false, - extensions: ["jpeg", "jpg", "jpe"] - }, - "image/jph": { - source: "iana", - extensions: ["jph"] - }, - "image/jphc": { - source: "iana", - extensions: ["jhc"] - }, - "image/jpm": { - source: "iana", - compressible: false, - extensions: ["jpm"] - }, - "image/jpx": { - source: "iana", - compressible: false, - extensions: ["jpx", "jpf"] - }, - "image/jxr": { - source: "iana", - extensions: ["jxr"] - }, - "image/jxra": { - source: "iana", - extensions: ["jxra"] - }, - "image/jxrs": { - source: "iana", - extensions: ["jxrs"] - }, - "image/jxs": { - source: "iana", - extensions: ["jxs"] - }, - "image/jxsc": { - source: "iana", - extensions: ["jxsc"] - }, - "image/jxsi": { - source: "iana", - extensions: ["jxsi"] - }, - "image/jxss": { - source: "iana", - extensions: ["jxss"] - }, - "image/ktx": { - source: "iana", - extensions: ["ktx"] - }, - "image/ktx2": { - source: "iana", - extensions: ["ktx2"] - }, - "image/naplps": { - source: "iana" - }, - "image/pjpeg": { - compressible: false - }, - "image/png": { - source: "iana", - compressible: false, - extensions: ["png"] - }, - "image/prs.btif": { - source: "iana", - extensions: ["btif"] - }, - "image/prs.pti": { - source: "iana", - extensions: ["pti"] - }, - "image/pwg-raster": { - source: "iana" - }, - "image/sgi": { - source: "apache", - extensions: ["sgi"] - }, - "image/svg+xml": { - source: "iana", - compressible: true, - extensions: ["svg", "svgz"] - }, - "image/t38": { - source: "iana", - extensions: ["t38"] - }, - "image/tiff": { - source: "iana", - compressible: false, - extensions: ["tif", "tiff"] - }, - "image/tiff-fx": { - source: "iana", - extensions: ["tfx"] - }, - "image/vnd.adobe.photoshop": { - source: "iana", - compressible: true, - extensions: ["psd"] - }, - "image/vnd.airzip.accelerator.azv": { - source: "iana", - extensions: ["azv"] - }, - "image/vnd.cns.inf2": { - source: "iana" - }, - "image/vnd.dece.graphic": { - source: "iana", - extensions: ["uvi", "uvvi", "uvg", "uvvg"] - }, - "image/vnd.djvu": { - source: "iana", - extensions: ["djvu", "djv"] - }, - "image/vnd.dvb.subtitle": { - source: "iana", - extensions: ["sub"] - }, - "image/vnd.dwg": { - source: "iana", - extensions: ["dwg"] - }, - "image/vnd.dxf": { - source: "iana", - extensions: ["dxf"] - }, - "image/vnd.fastbidsheet": { - source: "iana", - extensions: ["fbs"] - }, - "image/vnd.fpx": { - source: "iana", - extensions: ["fpx"] - }, - "image/vnd.fst": { - source: "iana", - extensions: ["fst"] - }, - "image/vnd.fujixerox.edmics-mmr": { - source: "iana", - extensions: ["mmr"] - }, - "image/vnd.fujixerox.edmics-rlc": { - source: "iana", - extensions: ["rlc"] - }, - "image/vnd.globalgraphics.pgb": { - source: "iana" - }, - "image/vnd.microsoft.icon": { - source: "iana", - compressible: true, - extensions: ["ico"] - }, - "image/vnd.mix": { - source: "iana" - }, - "image/vnd.mozilla.apng": { - source: "iana" - }, - "image/vnd.ms-dds": { - compressible: true, - extensions: ["dds"] - }, - "image/vnd.ms-modi": { - source: "iana", - extensions: ["mdi"] - }, - "image/vnd.ms-photo": { - source: "apache", - extensions: ["wdp"] - }, - "image/vnd.net-fpx": { - source: "iana", - extensions: ["npx"] - }, - "image/vnd.pco.b16": { - source: "iana", - extensions: ["b16"] - }, - "image/vnd.radiance": { - source: "iana" - }, - "image/vnd.sealed.png": { - source: "iana" - }, - "image/vnd.sealedmedia.softseal.gif": { - source: "iana" - }, - "image/vnd.sealedmedia.softseal.jpg": { - source: "iana" - }, - "image/vnd.svf": { - source: "iana" - }, - "image/vnd.tencent.tap": { - source: "iana", - extensions: ["tap"] - }, - "image/vnd.valve.source.texture": { - source: "iana", - extensions: ["vtf"] - }, - "image/vnd.wap.wbmp": { - source: "iana", - extensions: ["wbmp"] - }, - "image/vnd.xiff": { - source: "iana", - extensions: ["xif"] - }, - "image/vnd.zbrush.pcx": { - source: "iana", - extensions: ["pcx"] - }, - "image/webp": { - source: "apache", - extensions: ["webp"] - }, - "image/wmf": { - source: "iana", - extensions: ["wmf"] - }, - "image/x-3ds": { - source: "apache", - extensions: ["3ds"] - }, - "image/x-cmu-raster": { - source: "apache", - extensions: ["ras"] - }, - "image/x-cmx": { - source: "apache", - extensions: ["cmx"] - }, - "image/x-freehand": { - source: "apache", - extensions: ["fh", "fhc", "fh4", "fh5", "fh7"] - }, - "image/x-icon": { - source: "apache", - compressible: true, - extensions: ["ico"] - }, - "image/x-jng": { - source: "nginx", - extensions: ["jng"] - }, - "image/x-mrsid-image": { - source: "apache", - extensions: ["sid"] - }, - "image/x-ms-bmp": { - source: "nginx", - compressible: true, - extensions: ["bmp"] - }, - "image/x-pcx": { - source: "apache", - extensions: ["pcx"] - }, - "image/x-pict": { - source: "apache", - extensions: ["pic", "pct"] - }, - "image/x-portable-anymap": { - source: "apache", - extensions: ["pnm"] - }, - "image/x-portable-bitmap": { - source: "apache", - extensions: ["pbm"] - }, - "image/x-portable-graymap": { - source: "apache", - extensions: ["pgm"] - }, - "image/x-portable-pixmap": { - source: "apache", - extensions: ["ppm"] - }, - "image/x-rgb": { - source: "apache", - extensions: ["rgb"] - }, - "image/x-tga": { - source: "apache", - extensions: ["tga"] - }, - "image/x-xbitmap": { - source: "apache", - extensions: ["xbm"] - }, - "image/x-xcf": { - compressible: false - }, - "image/x-xpixmap": { - source: "apache", - extensions: ["xpm"] - }, - "image/x-xwindowdump": { - source: "apache", - extensions: ["xwd"] - }, - "message/cpim": { - source: "iana" - }, - "message/delivery-status": { - source: "iana" - }, - "message/disposition-notification": { - source: "iana", - extensions: [ - "disposition-notification" - ] - }, - "message/external-body": { - source: "iana" - }, - "message/feedback-report": { - source: "iana" - }, - "message/global": { - source: "iana", - extensions: ["u8msg"] - }, - "message/global-delivery-status": { - source: "iana", - extensions: ["u8dsn"] - }, - "message/global-disposition-notification": { - source: "iana", - extensions: ["u8mdn"] - }, - "message/global-headers": { - source: "iana", - extensions: ["u8hdr"] - }, - "message/http": { - source: "iana", - compressible: false - }, - "message/imdn+xml": { - source: "iana", - compressible: true - }, - "message/news": { - source: "iana" - }, - "message/partial": { - source: "iana", - compressible: false - }, - "message/rfc822": { - source: "iana", - compressible: true, - extensions: ["eml", "mime"] - }, - "message/s-http": { - source: "iana" - }, - "message/sip": { - source: "iana" - }, - "message/sipfrag": { - source: "iana" - }, - "message/tracking-status": { - source: "iana" - }, - "message/vnd.si.simp": { - source: "iana" - }, - "message/vnd.wfa.wsc": { - source: "iana", - extensions: ["wsc"] - }, - "model/3mf": { - source: "iana", - extensions: ["3mf"] - }, - "model/e57": { - source: "iana" - }, - "model/gltf+json": { - source: "iana", - compressible: true, - extensions: ["gltf"] - }, - "model/gltf-binary": { - source: "iana", - compressible: true, - extensions: ["glb"] - }, - "model/iges": { - source: "iana", - compressible: false, - extensions: ["igs", "iges"] - }, - "model/mesh": { - source: "iana", - compressible: false, - extensions: ["msh", "mesh", "silo"] - }, - "model/mtl": { - source: "iana", - extensions: ["mtl"] - }, - "model/obj": { - source: "iana", - extensions: ["obj"] - }, - "model/step": { - source: "iana" - }, - "model/step+xml": { - source: "iana", - compressible: true, - extensions: ["stpx"] - }, - "model/step+zip": { - source: "iana", - compressible: false, - extensions: ["stpz"] - }, - "model/step-xml+zip": { - source: "iana", - compressible: false, - extensions: ["stpxz"] - }, - "model/stl": { - source: "iana", - extensions: ["stl"] - }, - "model/vnd.collada+xml": { - source: "iana", - compressible: true, - extensions: ["dae"] - }, - "model/vnd.dwf": { - source: "iana", - extensions: ["dwf"] - }, - "model/vnd.flatland.3dml": { - source: "iana" - }, - "model/vnd.gdl": { - source: "iana", - extensions: ["gdl"] - }, - "model/vnd.gs-gdl": { - source: "apache" - }, - "model/vnd.gs.gdl": { - source: "iana" - }, - "model/vnd.gtw": { - source: "iana", - extensions: ["gtw"] - }, - "model/vnd.moml+xml": { - source: "iana", - compressible: true - }, - "model/vnd.mts": { - source: "iana", - extensions: ["mts"] - }, - "model/vnd.opengex": { - source: "iana", - extensions: ["ogex"] - }, - "model/vnd.parasolid.transmit.binary": { - source: "iana", - extensions: ["x_b"] - }, - "model/vnd.parasolid.transmit.text": { - source: "iana", - extensions: ["x_t"] - }, - "model/vnd.pytha.pyox": { - source: "iana" - }, - "model/vnd.rosette.annotated-data-model": { - source: "iana" - }, - "model/vnd.sap.vds": { - source: "iana", - extensions: ["vds"] - }, - "model/vnd.usdz+zip": { - source: "iana", - compressible: false, - extensions: ["usdz"] - }, - "model/vnd.valve.source.compiled-map": { - source: "iana", - extensions: ["bsp"] - }, - "model/vnd.vtu": { - source: "iana", - extensions: ["vtu"] - }, - "model/vrml": { - source: "iana", - compressible: false, - extensions: ["wrl", "vrml"] - }, - "model/x3d+binary": { - source: "apache", - compressible: false, - extensions: ["x3db", "x3dbz"] - }, - "model/x3d+fastinfoset": { - source: "iana", - extensions: ["x3db"] - }, - "model/x3d+vrml": { - source: "apache", - compressible: false, - extensions: ["x3dv", "x3dvz"] - }, - "model/x3d+xml": { - source: "iana", - compressible: true, - extensions: ["x3d", "x3dz"] - }, - "model/x3d-vrml": { - source: "iana", - extensions: ["x3dv"] - }, - "multipart/alternative": { - source: "iana", - compressible: false - }, - "multipart/appledouble": { - source: "iana" - }, - "multipart/byteranges": { - source: "iana" - }, - "multipart/digest": { - source: "iana" - }, - "multipart/encrypted": { - source: "iana", - compressible: false - }, - "multipart/form-data": { - source: "iana", - compressible: false - }, - "multipart/header-set": { - source: "iana" - }, - "multipart/mixed": { - source: "iana" - }, - "multipart/multilingual": { - source: "iana" - }, - "multipart/parallel": { - source: "iana" - }, - "multipart/related": { - source: "iana", - compressible: false - }, - "multipart/report": { - source: "iana" - }, - "multipart/signed": { - source: "iana", - compressible: false - }, - "multipart/vnd.bint.med-plus": { - source: "iana" - }, - "multipart/voice-message": { - source: "iana" - }, - "multipart/x-mixed-replace": { - source: "iana" - }, - "text/1d-interleaved-parityfec": { - source: "iana" - }, - "text/cache-manifest": { - source: "iana", - compressible: true, - extensions: ["appcache", "manifest"] - }, - "text/calendar": { - source: "iana", - extensions: ["ics", "ifb"] - }, - "text/calender": { - compressible: true - }, - "text/cmd": { - compressible: true - }, - "text/coffeescript": { - extensions: ["coffee", "litcoffee"] - }, - "text/cql": { - source: "iana" - }, - "text/cql-expression": { - source: "iana" - }, - "text/cql-identifier": { - source: "iana" - }, - "text/css": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["css"] - }, - "text/csv": { - source: "iana", - compressible: true, - extensions: ["csv"] - }, - "text/csv-schema": { - source: "iana" - }, - "text/directory": { - source: "iana" - }, - "text/dns": { - source: "iana" - }, - "text/ecmascript": { - source: "iana" - }, - "text/encaprtp": { - source: "iana" - }, - "text/enriched": { - source: "iana" - }, - "text/fhirpath": { - source: "iana" - }, - "text/flexfec": { - source: "iana" - }, - "text/fwdred": { - source: "iana" - }, - "text/gff3": { - source: "iana" - }, - "text/grammar-ref-list": { - source: "iana" - }, - "text/html": { - source: "iana", - compressible: true, - extensions: ["html", "htm", "shtml"] - }, - "text/jade": { - extensions: ["jade"] - }, - "text/javascript": { - source: "iana", - compressible: true - }, - "text/jcr-cnd": { - source: "iana" - }, - "text/jsx": { - compressible: true, - extensions: ["jsx"] - }, - "text/less": { - compressible: true, - extensions: ["less"] - }, - "text/markdown": { - source: "iana", - compressible: true, - extensions: ["markdown", "md"] - }, - "text/mathml": { - source: "nginx", - extensions: ["mml"] - }, - "text/mdx": { - compressible: true, - extensions: ["mdx"] - }, - "text/mizar": { - source: "iana" - }, - "text/n3": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["n3"] - }, - "text/parameters": { - source: "iana", - charset: "UTF-8" - }, - "text/parityfec": { - source: "iana" - }, - "text/plain": { - source: "iana", - compressible: true, - extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"] - }, - "text/provenance-notation": { - source: "iana", - charset: "UTF-8" - }, - "text/prs.fallenstein.rst": { - source: "iana" - }, - "text/prs.lines.tag": { - source: "iana", - extensions: ["dsc"] - }, - "text/prs.prop.logic": { - source: "iana" - }, - "text/raptorfec": { - source: "iana" - }, - "text/red": { - source: "iana" - }, - "text/rfc822-headers": { - source: "iana" - }, - "text/richtext": { - source: "iana", - compressible: true, - extensions: ["rtx"] - }, - "text/rtf": { - source: "iana", - compressible: true, - extensions: ["rtf"] - }, - "text/rtp-enc-aescm128": { - source: "iana" - }, - "text/rtploopback": { - source: "iana" - }, - "text/rtx": { - source: "iana" - }, - "text/sgml": { - source: "iana", - extensions: ["sgml", "sgm"] - }, - "text/shaclc": { - source: "iana" - }, - "text/shex": { - source: "iana", - extensions: ["shex"] - }, - "text/slim": { - extensions: ["slim", "slm"] - }, - "text/spdx": { - source: "iana", - extensions: ["spdx"] - }, - "text/strings": { - source: "iana" - }, - "text/stylus": { - extensions: ["stylus", "styl"] - }, - "text/t140": { - source: "iana" - }, - "text/tab-separated-values": { - source: "iana", - compressible: true, - extensions: ["tsv"] - }, - "text/troff": { - source: "iana", - extensions: ["t", "tr", "roff", "man", "me", "ms"] - }, - "text/turtle": { - source: "iana", - charset: "UTF-8", - extensions: ["ttl"] - }, - "text/ulpfec": { - source: "iana" - }, - "text/uri-list": { - source: "iana", - compressible: true, - extensions: ["uri", "uris", "urls"] - }, - "text/vcard": { - source: "iana", - compressible: true, - extensions: ["vcard"] - }, - "text/vnd.a": { - source: "iana" - }, - "text/vnd.abc": { - source: "iana" - }, - "text/vnd.ascii-art": { - source: "iana" - }, - "text/vnd.curl": { - source: "iana", - extensions: ["curl"] - }, - "text/vnd.curl.dcurl": { - source: "apache", - extensions: ["dcurl"] - }, - "text/vnd.curl.mcurl": { - source: "apache", - extensions: ["mcurl"] - }, - "text/vnd.curl.scurl": { - source: "apache", - extensions: ["scurl"] - }, - "text/vnd.debian.copyright": { - source: "iana", - charset: "UTF-8" - }, - "text/vnd.dmclientscript": { - source: "iana" - }, - "text/vnd.dvb.subtitle": { - source: "iana", - extensions: ["sub"] - }, - "text/vnd.esmertec.theme-descriptor": { - source: "iana", - charset: "UTF-8" - }, - "text/vnd.familysearch.gedcom": { - source: "iana", - extensions: ["ged"] - }, - "text/vnd.ficlab.flt": { - source: "iana" - }, - "text/vnd.fly": { - source: "iana", - extensions: ["fly"] - }, - "text/vnd.fmi.flexstor": { - source: "iana", - extensions: ["flx"] - }, - "text/vnd.gml": { - source: "iana" - }, - "text/vnd.graphviz": { - source: "iana", - extensions: ["gv"] - }, - "text/vnd.hans": { - source: "iana" - }, - "text/vnd.hgl": { - source: "iana" - }, - "text/vnd.in3d.3dml": { - source: "iana", - extensions: ["3dml"] - }, - "text/vnd.in3d.spot": { - source: "iana", - extensions: ["spot"] - }, - "text/vnd.iptc.newsml": { - source: "iana" - }, - "text/vnd.iptc.nitf": { - source: "iana" - }, - "text/vnd.latex-z": { - source: "iana" - }, - "text/vnd.motorola.reflex": { - source: "iana" - }, - "text/vnd.ms-mediapackage": { - source: "iana" - }, - "text/vnd.net2phone.commcenter.command": { - source: "iana" - }, - "text/vnd.radisys.msml-basic-layout": { - source: "iana" - }, - "text/vnd.senx.warpscript": { - source: "iana" - }, - "text/vnd.si.uricatalogue": { - source: "iana" - }, - "text/vnd.sosi": { - source: "iana" - }, - "text/vnd.sun.j2me.app-descriptor": { - source: "iana", - charset: "UTF-8", - extensions: ["jad"] - }, - "text/vnd.trolltech.linguist": { - source: "iana", - charset: "UTF-8" - }, - "text/vnd.wap.si": { - source: "iana" - }, - "text/vnd.wap.sl": { - source: "iana" - }, - "text/vnd.wap.wml": { - source: "iana", - extensions: ["wml"] - }, - "text/vnd.wap.wmlscript": { - source: "iana", - extensions: ["wmls"] - }, - "text/vtt": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["vtt"] - }, - "text/x-asm": { - source: "apache", - extensions: ["s", "asm"] - }, - "text/x-c": { - source: "apache", - extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"] - }, - "text/x-component": { - source: "nginx", - extensions: ["htc"] - }, - "text/x-fortran": { - source: "apache", - extensions: ["f", "for", "f77", "f90"] - }, - "text/x-gwt-rpc": { - compressible: true - }, - "text/x-handlebars-template": { - extensions: ["hbs"] - }, - "text/x-java-source": { - source: "apache", - extensions: ["java"] - }, - "text/x-jquery-tmpl": { - compressible: true - }, - "text/x-lua": { - extensions: ["lua"] - }, - "text/x-markdown": { - compressible: true, - extensions: ["mkd"] - }, - "text/x-nfo": { - source: "apache", - extensions: ["nfo"] - }, - "text/x-opml": { - source: "apache", - extensions: ["opml"] - }, - "text/x-org": { - compressible: true, - extensions: ["org"] - }, - "text/x-pascal": { - source: "apache", - extensions: ["p", "pas"] - }, - "text/x-processing": { - compressible: true, - extensions: ["pde"] - }, - "text/x-sass": { - extensions: ["sass"] - }, - "text/x-scss": { - extensions: ["scss"] - }, - "text/x-setext": { - source: "apache", - extensions: ["etx"] - }, - "text/x-sfv": { - source: "apache", - extensions: ["sfv"] - }, - "text/x-suse-ymp": { - compressible: true, - extensions: ["ymp"] - }, - "text/x-uuencode": { - source: "apache", - extensions: ["uu"] - }, - "text/x-vcalendar": { - source: "apache", - extensions: ["vcs"] - }, - "text/x-vcard": { - source: "apache", - extensions: ["vcf"] - }, - "text/xml": { - source: "iana", - compressible: true, - extensions: ["xml"] - }, - "text/xml-external-parsed-entity": { - source: "iana" - }, - "text/yaml": { - compressible: true, - extensions: ["yaml", "yml"] - }, - "video/1d-interleaved-parityfec": { - source: "iana" - }, - "video/3gpp": { - source: "iana", - extensions: ["3gp", "3gpp"] - }, - "video/3gpp-tt": { - source: "iana" - }, - "video/3gpp2": { - source: "iana", - extensions: ["3g2"] - }, - "video/av1": { - source: "iana" - }, - "video/bmpeg": { - source: "iana" - }, - "video/bt656": { - source: "iana" - }, - "video/celb": { - source: "iana" - }, - "video/dv": { - source: "iana" - }, - "video/encaprtp": { - source: "iana" - }, - "video/ffv1": { - source: "iana" - }, - "video/flexfec": { - source: "iana" - }, - "video/h261": { - source: "iana", - extensions: ["h261"] - }, - "video/h263": { - source: "iana", - extensions: ["h263"] - }, - "video/h263-1998": { - source: "iana" - }, - "video/h263-2000": { - source: "iana" - }, - "video/h264": { - source: "iana", - extensions: ["h264"] - }, - "video/h264-rcdo": { - source: "iana" - }, - "video/h264-svc": { - source: "iana" - }, - "video/h265": { - source: "iana" - }, - "video/iso.segment": { - source: "iana", - extensions: ["m4s"] - }, - "video/jpeg": { - source: "iana", - extensions: ["jpgv"] - }, - "video/jpeg2000": { - source: "iana" - }, - "video/jpm": { - source: "apache", - extensions: ["jpm", "jpgm"] - }, - "video/jxsv": { - source: "iana" - }, - "video/mj2": { - source: "iana", - extensions: ["mj2", "mjp2"] - }, - "video/mp1s": { - source: "iana" - }, - "video/mp2p": { - source: "iana" - }, - "video/mp2t": { - source: "iana", - extensions: ["ts"] - }, - "video/mp4": { - source: "iana", - compressible: false, - extensions: ["mp4", "mp4v", "mpg4"] - }, - "video/mp4v-es": { - source: "iana" - }, - "video/mpeg": { - source: "iana", - compressible: false, - extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"] - }, - "video/mpeg4-generic": { - source: "iana" - }, - "video/mpv": { - source: "iana" - }, - "video/nv": { - source: "iana" - }, - "video/ogg": { - source: "iana", - compressible: false, - extensions: ["ogv"] - }, - "video/parityfec": { - source: "iana" - }, - "video/pointer": { - source: "iana" - }, - "video/quicktime": { - source: "iana", - compressible: false, - extensions: ["qt", "mov"] - }, - "video/raptorfec": { - source: "iana" - }, - "video/raw": { - source: "iana" - }, - "video/rtp-enc-aescm128": { - source: "iana" - }, - "video/rtploopback": { - source: "iana" - }, - "video/rtx": { - source: "iana" - }, - "video/scip": { - source: "iana" - }, - "video/smpte291": { - source: "iana" - }, - "video/smpte292m": { - source: "iana" - }, - "video/ulpfec": { - source: "iana" - }, - "video/vc1": { - source: "iana" - }, - "video/vc2": { - source: "iana" - }, - "video/vnd.cctv": { - source: "iana" - }, - "video/vnd.dece.hd": { - source: "iana", - extensions: ["uvh", "uvvh"] - }, - "video/vnd.dece.mobile": { - source: "iana", - extensions: ["uvm", "uvvm"] - }, - "video/vnd.dece.mp4": { - source: "iana" - }, - "video/vnd.dece.pd": { - source: "iana", - extensions: ["uvp", "uvvp"] - }, - "video/vnd.dece.sd": { - source: "iana", - extensions: ["uvs", "uvvs"] - }, - "video/vnd.dece.video": { - source: "iana", - extensions: ["uvv", "uvvv"] - }, - "video/vnd.directv.mpeg": { - source: "iana" - }, - "video/vnd.directv.mpeg-tts": { - source: "iana" - }, - "video/vnd.dlna.mpeg-tts": { - source: "iana" - }, - "video/vnd.dvb.file": { - source: "iana", - extensions: ["dvb"] - }, - "video/vnd.fvt": { - source: "iana", - extensions: ["fvt"] - }, - "video/vnd.hns.video": { - source: "iana" - }, - "video/vnd.iptvforum.1dparityfec-1010": { - source: "iana" - }, - "video/vnd.iptvforum.1dparityfec-2005": { - source: "iana" - }, - "video/vnd.iptvforum.2dparityfec-1010": { - source: "iana" - }, - "video/vnd.iptvforum.2dparityfec-2005": { - source: "iana" - }, - "video/vnd.iptvforum.ttsavc": { - source: "iana" - }, - "video/vnd.iptvforum.ttsmpeg2": { - source: "iana" - }, - "video/vnd.motorola.video": { - source: "iana" - }, - "video/vnd.motorola.videop": { - source: "iana" - }, - "video/vnd.mpegurl": { - source: "iana", - extensions: ["mxu", "m4u"] - }, - "video/vnd.ms-playready.media.pyv": { - source: "iana", - extensions: ["pyv"] - }, - "video/vnd.nokia.interleaved-multimedia": { - source: "iana" - }, - "video/vnd.nokia.mp4vr": { - source: "iana" - }, - "video/vnd.nokia.videovoip": { - source: "iana" - }, - "video/vnd.objectvideo": { - source: "iana" - }, - "video/vnd.radgamettools.bink": { - source: "iana" - }, - "video/vnd.radgamettools.smacker": { - source: "iana" - }, - "video/vnd.sealed.mpeg1": { - source: "iana" - }, - "video/vnd.sealed.mpeg4": { - source: "iana" - }, - "video/vnd.sealed.swf": { - source: "iana" - }, - "video/vnd.sealedmedia.softseal.mov": { - source: "iana" - }, - "video/vnd.uvvu.mp4": { - source: "iana", - extensions: ["uvu", "uvvu"] - }, - "video/vnd.vivo": { - source: "iana", - extensions: ["viv"] - }, - "video/vnd.youtube.yt": { - source: "iana" - }, - "video/vp8": { - source: "iana" - }, - "video/vp9": { - source: "iana" - }, - "video/webm": { - source: "apache", - compressible: false, - extensions: ["webm"] - }, - "video/x-f4v": { - source: "apache", - extensions: ["f4v"] - }, - "video/x-fli": { - source: "apache", - extensions: ["fli"] - }, - "video/x-flv": { - source: "apache", - compressible: false, - extensions: ["flv"] - }, - "video/x-m4v": { - source: "apache", - extensions: ["m4v"] - }, - "video/x-matroska": { - source: "apache", - compressible: false, - extensions: ["mkv", "mk3d", "mks"] - }, - "video/x-mng": { - source: "apache", - extensions: ["mng"] - }, - "video/x-ms-asf": { - source: "apache", - extensions: ["asf", "asx"] - }, - "video/x-ms-vob": { - source: "apache", - extensions: ["vob"] - }, - "video/x-ms-wm": { - source: "apache", - extensions: ["wm"] - }, - "video/x-ms-wmv": { - source: "apache", - compressible: false, - extensions: ["wmv"] - }, - "video/x-ms-wmx": { - source: "apache", - extensions: ["wmx"] - }, - "video/x-ms-wvx": { - source: "apache", - extensions: ["wvx"] - }, - "video/x-msvideo": { - source: "apache", - extensions: ["avi"] - }, - "video/x-sgi-movie": { - source: "apache", - extensions: ["movie"] - }, - "video/x-smv": { - source: "apache", - extensions: ["smv"] - }, - "x-conference/x-cooltalk": { - source: "apache", - extensions: ["ice"] - }, - "x-shader/x-fragment": { - compressible: true - }, - "x-shader/x-vertex": { - compressible: true - } - }; - } -}); - -// node_modules/mime-db/index.js -var require_mime_db = __commonJS({ - "node_modules/mime-db/index.js"(exports2, module2) { - module2.exports = require_db(); - } -}); - -// node_modules/mime-types/index.js -var require_mime_types = __commonJS({ - "node_modules/mime-types/index.js"(exports2) { - "use strict"; - var db = require_mime_db(); - var extname = __require("path").extname; - var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; - var TEXT_TYPE_REGEXP = /^text\//i; - exports2.charset = charset; - exports2.charsets = { lookup: charset }; - exports2.contentType = contentType; - exports2.extension = extension; - exports2.extensions = /* @__PURE__ */ Object.create(null); - exports2.lookup = lookup; - exports2.types = /* @__PURE__ */ Object.create(null); - populateMaps(exports2.extensions, exports2.types); - function charset(type) { - if (!type || typeof type !== "string") { - return false; - } - var match = EXTRACT_TYPE_REGEXP.exec(type); - var mime = match && db[match[1].toLowerCase()]; - if (mime && mime.charset) { - return mime.charset; - } - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return "UTF-8"; - } - return false; - } - function contentType(str) { - if (!str || typeof str !== "string") { - return false; - } - var mime = str.indexOf("/") === -1 ? exports2.lookup(str) : str; - if (!mime) { - return false; - } - if (mime.indexOf("charset") === -1) { - var charset2 = exports2.charset(mime); - if (charset2) mime += "; charset=" + charset2.toLowerCase(); - } - return mime; - } - function extension(type) { - if (!type || typeof type !== "string") { - return false; - } - var match = EXTRACT_TYPE_REGEXP.exec(type); - var exts = match && exports2.extensions[match[1].toLowerCase()]; - if (!exts || !exts.length) { - return false; - } - return exts[0]; - } - function lookup(path) { - if (!path || typeof path !== "string") { - return false; - } - var extension2 = extname("x." + path).toLowerCase().substr(1); - if (!extension2) { - return false; - } - return exports2.types[extension2] || false; - } - function populateMaps(extensions, types) { - var preference = ["nginx", "apache", void 0, "iana"]; - Object.keys(db).forEach(function forEachMimeType(type) { - var mime = db[type]; - var exts = mime.extensions; - if (!exts || !exts.length) { - return; - } - extensions[type] = exts; - for (var i = 0; i < exts.length; i++) { - var extension2 = exts[i]; - if (types[extension2]) { - var from5 = preference.indexOf(db[types[extension2]].source); - var to2 = preference.indexOf(mime.source); - if (types[extension2] !== "application/octet-stream" && (from5 > to2 || from5 === to2 && types[extension2].substr(0, 12) === "application/")) { - continue; - } - } - types[extension2] = type; - } - }); - } - } -}); - -// node_modules/asynckit/lib/defer.js -var require_defer = __commonJS({ - "node_modules/asynckit/lib/defer.js"(exports2, module2) { - module2.exports = defer; - function defer(fn2) { - var nextTick = typeof setImmediate == "function" ? setImmediate : typeof process == "object" && typeof process.nextTick == "function" ? process.nextTick : null; - if (nextTick) { - nextTick(fn2); - } else { - setTimeout(fn2, 0); - } - } - } -}); - -// node_modules/asynckit/lib/async.js -var require_async = __commonJS({ - "node_modules/asynckit/lib/async.js"(exports2, module2) { - var defer = require_defer(); - module2.exports = async; - function async(callback) { - var isAsync = false; - defer(function() { - isAsync = true; - }); - return function async_callback(err, result) { - if (isAsync) { - callback(err, result); - } else { - defer(function nextTick_callback() { - callback(err, result); - }); - } - }; - } - } -}); - -// node_modules/asynckit/lib/abort.js -var require_abort = __commonJS({ - "node_modules/asynckit/lib/abort.js"(exports2, module2) { - module2.exports = abort; - function abort(state) { - Object.keys(state.jobs).forEach(clean.bind(state)); - state.jobs = {}; - } - function clean(key) { - if (typeof this.jobs[key] == "function") { - this.jobs[key](); - } - } - } -}); - -// node_modules/asynckit/lib/iterate.js -var require_iterate = __commonJS({ - "node_modules/asynckit/lib/iterate.js"(exports2, module2) { - var async = require_async(); - var abort = require_abort(); - module2.exports = iterate; - function iterate(list, iterator2, state, callback) { - var key = state["keyedList"] ? state["keyedList"][state.index] : state.index; - state.jobs[key] = runJob(iterator2, key, list[key], function(error, output) { - if (!(key in state.jobs)) { - return; - } - delete state.jobs[key]; - if (error) { - abort(state); - } else { - state.results[key] = output; - } - callback(error, state.results); - }); - } - function runJob(iterator2, key, item, callback) { - var aborter; - if (iterator2.length == 2) { - aborter = iterator2(item, async(callback)); - } else { - aborter = iterator2(item, key, async(callback)); - } - return aborter; - } - } -}); - -// node_modules/asynckit/lib/state.js -var require_state = __commonJS({ - "node_modules/asynckit/lib/state.js"(exports2, module2) { - module2.exports = state; - function state(list, sortMethod) { - var isNamedList = !Array.isArray(list), initState = { - index: 0, - keyedList: isNamedList || sortMethod ? Object.keys(list) : null, - jobs: {}, - results: isNamedList ? {} : [], - size: isNamedList ? Object.keys(list).length : list.length - }; - if (sortMethod) { - initState.keyedList.sort(isNamedList ? sortMethod : function(a, b2) { - return sortMethod(list[a], list[b2]); - }); - } - return initState; - } - } -}); - -// node_modules/asynckit/lib/terminator.js -var require_terminator = __commonJS({ - "node_modules/asynckit/lib/terminator.js"(exports2, module2) { - var abort = require_abort(); - var async = require_async(); - module2.exports = terminator; - function terminator(callback) { - if (!Object.keys(this.jobs).length) { - return; - } - this.index = this.size; - abort(this); - async(callback)(null, this.results); - } - } -}); - -// node_modules/asynckit/parallel.js -var require_parallel = __commonJS({ - "node_modules/asynckit/parallel.js"(exports2, module2) { - var iterate = require_iterate(); - var initState = require_state(); - var terminator = require_terminator(); - module2.exports = parallel; - function parallel(list, iterator2, callback) { - var state = initState(list); - while (state.index < (state["keyedList"] || list).length) { - iterate(list, iterator2, state, function(error, result) { - if (error) { - callback(error, result); - return; - } - if (Object.keys(state.jobs).length === 0) { - callback(null, state.results); - return; - } - }); - state.index++; - } - return terminator.bind(state, callback); - } - } -}); - -// node_modules/asynckit/serialOrdered.js -var require_serialOrdered = __commonJS({ - "node_modules/asynckit/serialOrdered.js"(exports2, module2) { - var iterate = require_iterate(); - var initState = require_state(); - var terminator = require_terminator(); - module2.exports = serialOrdered; - module2.exports.ascending = ascending; - module2.exports.descending = descending; - function serialOrdered(list, iterator2, sortMethod, callback) { - var state = initState(list, sortMethod); - iterate(list, iterator2, state, function iteratorHandler(error, result) { - if (error) { - callback(error, result); - return; - } - state.index++; - if (state.index < (state["keyedList"] || list).length) { - iterate(list, iterator2, state, iteratorHandler); - return; - } - callback(null, state.results); - }); - return terminator.bind(state, callback); - } - function ascending(a, b2) { - return a < b2 ? -1 : a > b2 ? 1 : 0; - } - function descending(a, b2) { - return -1 * ascending(a, b2); - } - } -}); - -// node_modules/asynckit/serial.js -var require_serial = __commonJS({ - "node_modules/asynckit/serial.js"(exports2, module2) { - var serialOrdered = require_serialOrdered(); - module2.exports = serial; - function serial(list, iterator2, callback) { - return serialOrdered(list, iterator2, null, callback); - } - } -}); - -// node_modules/asynckit/index.js -var require_asynckit = __commonJS({ - "node_modules/asynckit/index.js"(exports2, module2) { - module2.exports = { - parallel: require_parallel(), - serial: require_serial(), - serialOrdered: require_serialOrdered() - }; - } -}); - -// node_modules/es-object-atoms/index.js -var require_es_object_atoms = __commonJS({ - "node_modules/es-object-atoms/index.js"(exports2, module2) { - "use strict"; - module2.exports = Object; - } -}); - -// node_modules/es-errors/index.js -var require_es_errors = __commonJS({ - "node_modules/es-errors/index.js"(exports2, module2) { - "use strict"; - module2.exports = Error; - } -}); - -// node_modules/es-errors/eval.js -var require_eval = __commonJS({ - "node_modules/es-errors/eval.js"(exports2, module2) { - "use strict"; - module2.exports = EvalError; - } -}); - -// node_modules/es-errors/range.js -var require_range = __commonJS({ - "node_modules/es-errors/range.js"(exports2, module2) { - "use strict"; - module2.exports = RangeError; - } -}); - -// node_modules/es-errors/ref.js -var require_ref = __commonJS({ - "node_modules/es-errors/ref.js"(exports2, module2) { - "use strict"; - module2.exports = ReferenceError; - } -}); - -// node_modules/es-errors/syntax.js -var require_syntax = __commonJS({ - "node_modules/es-errors/syntax.js"(exports2, module2) { - "use strict"; - module2.exports = SyntaxError; - } -}); - -// node_modules/es-errors/type.js -var require_type = __commonJS({ - "node_modules/es-errors/type.js"(exports2, module2) { - "use strict"; - module2.exports = TypeError; - } -}); - -// node_modules/es-errors/uri.js -var require_uri = __commonJS({ - "node_modules/es-errors/uri.js"(exports2, module2) { - "use strict"; - module2.exports = URIError; - } -}); - -// node_modules/math-intrinsics/abs.js -var require_abs = __commonJS({ - "node_modules/math-intrinsics/abs.js"(exports2, module2) { - "use strict"; - module2.exports = Math.abs; - } -}); - -// node_modules/math-intrinsics/floor.js -var require_floor = __commonJS({ - "node_modules/math-intrinsics/floor.js"(exports2, module2) { - "use strict"; - module2.exports = Math.floor; - } -}); - -// node_modules/math-intrinsics/max.js -var require_max = __commonJS({ - "node_modules/math-intrinsics/max.js"(exports2, module2) { - "use strict"; - module2.exports = Math.max; - } -}); - -// node_modules/math-intrinsics/min.js -var require_min = __commonJS({ - "node_modules/math-intrinsics/min.js"(exports2, module2) { - "use strict"; - module2.exports = Math.min; - } -}); - -// node_modules/math-intrinsics/pow.js -var require_pow = __commonJS({ - "node_modules/math-intrinsics/pow.js"(exports2, module2) { - "use strict"; - module2.exports = Math.pow; - } -}); - -// node_modules/math-intrinsics/round.js -var require_round = __commonJS({ - "node_modules/math-intrinsics/round.js"(exports2, module2) { - "use strict"; - module2.exports = Math.round; - } -}); - -// node_modules/math-intrinsics/isNaN.js -var require_isNaN = __commonJS({ - "node_modules/math-intrinsics/isNaN.js"(exports2, module2) { - "use strict"; - module2.exports = Number.isNaN || function isNaN2(a) { - return a !== a; - }; - } -}); - -// node_modules/math-intrinsics/sign.js -var require_sign = __commonJS({ - "node_modules/math-intrinsics/sign.js"(exports2, module2) { - "use strict"; - var $isNaN = require_isNaN(); - module2.exports = function sign2(number) { - if ($isNaN(number) || number === 0) { - return number; - } - return number < 0 ? -1 : 1; - }; - } -}); - -// node_modules/gopd/gOPD.js -var require_gOPD = __commonJS({ - "node_modules/gopd/gOPD.js"(exports2, module2) { - "use strict"; - module2.exports = Object.getOwnPropertyDescriptor; - } -}); - -// node_modules/gopd/index.js -var require_gopd = __commonJS({ - "node_modules/gopd/index.js"(exports2, module2) { - "use strict"; - var $gOPD = require_gOPD(); - if ($gOPD) { - try { - $gOPD([], "length"); - } catch (e) { - $gOPD = null; - } - } - module2.exports = $gOPD; - } -}); - -// node_modules/es-define-property/index.js -var require_es_define_property = __commonJS({ - "node_modules/es-define-property/index.js"(exports2, module2) { - "use strict"; - var $defineProperty = Object.defineProperty || false; - if ($defineProperty) { - try { - $defineProperty({}, "a", { value: 1 }); - } catch (e) { - $defineProperty = false; - } - } - module2.exports = $defineProperty; - } -}); - -// node_modules/has-symbols/shams.js -var require_shams = __commonJS({ - "node_modules/has-symbols/shams.js"(exports2, module2) { - "use strict"; - module2.exports = function hasSymbols() { - if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { - return false; - } - if (typeof Symbol.iterator === "symbol") { - return true; - } - var obj = {}; - var sym = Symbol("test"); - var symObj = Object(sym); - if (typeof sym === "string") { - return false; - } - if (Object.prototype.toString.call(sym) !== "[object Symbol]") { - return false; - } - if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { - return false; - } - var symVal = 42; - obj[sym] = symVal; - for (var _ in obj) { - return false; - } - if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { - return false; - } - if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { - return false; - } - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { - return false; - } - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { - return false; - } - if (typeof Object.getOwnPropertyDescriptor === "function") { - var descriptor = ( - /** @type {PropertyDescriptor} */ - Object.getOwnPropertyDescriptor(obj, sym) - ); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { - return false; - } - } - return true; - }; - } -}); - -// node_modules/has-symbols/index.js -var require_has_symbols = __commonJS({ - "node_modules/has-symbols/index.js"(exports2, module2) { - "use strict"; - var origSymbol = typeof Symbol !== "undefined" && Symbol; - var hasSymbolSham = require_shams(); - module2.exports = function hasNativeSymbols() { - if (typeof origSymbol !== "function") { - return false; - } - if (typeof Symbol !== "function") { - return false; - } - if (typeof origSymbol("foo") !== "symbol") { - return false; - } - if (typeof Symbol("bar") !== "symbol") { - return false; - } - return hasSymbolSham(); - }; - } -}); - -// node_modules/get-proto/Reflect.getPrototypeOf.js -var require_Reflect_getPrototypeOf = __commonJS({ - "node_modules/get-proto/Reflect.getPrototypeOf.js"(exports2, module2) { - "use strict"; - module2.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null; - } -}); - -// node_modules/get-proto/Object.getPrototypeOf.js -var require_Object_getPrototypeOf = __commonJS({ - "node_modules/get-proto/Object.getPrototypeOf.js"(exports2, module2) { - "use strict"; - var $Object = require_es_object_atoms(); - module2.exports = $Object.getPrototypeOf || null; - } -}); - -// node_modules/function-bind/implementation.js -var require_implementation = __commonJS({ - "node_modules/function-bind/implementation.js"(exports2, module2) { - "use strict"; - var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; - var toStr = Object.prototype.toString; - var max = Math.max; - var funcType = "[object Function]"; - var concatty = function concatty2(a, b2) { - var arr = []; - for (var i = 0; i < a.length; i += 1) { - arr[i] = a[i]; - } - for (var j2 = 0; j2 < b2.length; j2 += 1) { - arr[j2 + a.length] = b2[j2]; - } - return arr; - }; - var slicy = function slicy2(arrLike, offset) { - var arr = []; - for (var i = offset || 0, j2 = 0; i < arrLike.length; i += 1, j2 += 1) { - arr[j2] = arrLike[i]; - } - return arr; - }; - var joiny = function(arr, joiner) { - var str = ""; - for (var i = 0; i < arr.length; i += 1) { - str += arr[i]; - if (i + 1 < arr.length) { - str += joiner; - } - } - return str; - }; - module2.exports = function bind2(that) { - var target = this; - if (typeof target !== "function" || toStr.apply(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slicy(arguments, 1); - var bound; - var binder = function() { - if (this instanceof bound) { - var result = target.apply( - this, - concatty(args, arguments) - ); - if (Object(result) === result) { - return result; - } - return this; - } - return target.apply( - that, - concatty(args, arguments) - ); - }; - var boundLength = max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs[i] = "$" + i; - } - bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); - if (target.prototype) { - var Empty = function Empty2() { - }; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - return bound; - }; - } -}); - -// node_modules/function-bind/index.js -var require_function_bind = __commonJS({ - "node_modules/function-bind/index.js"(exports2, module2) { - "use strict"; - var implementation = require_implementation(); - module2.exports = Function.prototype.bind || implementation; - } -}); - -// node_modules/call-bind-apply-helpers/functionCall.js -var require_functionCall = __commonJS({ - "node_modules/call-bind-apply-helpers/functionCall.js"(exports2, module2) { - "use strict"; - module2.exports = Function.prototype.call; - } -}); - -// node_modules/call-bind-apply-helpers/functionApply.js -var require_functionApply = __commonJS({ - "node_modules/call-bind-apply-helpers/functionApply.js"(exports2, module2) { - "use strict"; - module2.exports = Function.prototype.apply; - } -}); - -// node_modules/call-bind-apply-helpers/reflectApply.js -var require_reflectApply = __commonJS({ - "node_modules/call-bind-apply-helpers/reflectApply.js"(exports2, module2) { - "use strict"; - module2.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply; - } -}); - -// node_modules/call-bind-apply-helpers/actualApply.js -var require_actualApply = __commonJS({ - "node_modules/call-bind-apply-helpers/actualApply.js"(exports2, module2) { - "use strict"; - var bind2 = require_function_bind(); - var $apply = require_functionApply(); - var $call = require_functionCall(); - var $reflectApply = require_reflectApply(); - module2.exports = $reflectApply || bind2.call($call, $apply); - } -}); - -// node_modules/call-bind-apply-helpers/index.js -var require_call_bind_apply_helpers = __commonJS({ - "node_modules/call-bind-apply-helpers/index.js"(exports2, module2) { - "use strict"; - var bind2 = require_function_bind(); - var $TypeError = require_type(); - var $call = require_functionCall(); - var $actualApply = require_actualApply(); - module2.exports = function callBindBasic(args) { - if (args.length < 1 || typeof args[0] !== "function") { - throw new $TypeError("a function is required"); - } - return $actualApply(bind2, $call, args); - }; - } -}); - -// node_modules/dunder-proto/get.js -var require_get = __commonJS({ - "node_modules/dunder-proto/get.js"(exports2, module2) { - "use strict"; - var callBind = require_call_bind_apply_helpers(); - var gOPD = require_gopd(); - var hasProtoAccessor; - try { - hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ - [].__proto__ === Array.prototype; - } catch (e) { - if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") { - throw e; - } - } - var desc = !!hasProtoAccessor && gOPD && gOPD( - Object.prototype, - /** @type {keyof typeof Object.prototype} */ - "__proto__" - ); - var $Object = Object; - var $getPrototypeOf = $Object.getPrototypeOf; - module2.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? ( - /** @type {import('./get')} */ - function getDunder(value) { - return $getPrototypeOf(value == null ? value : $Object(value)); - } - ) : false; - } -}); - -// node_modules/get-proto/index.js -var require_get_proto = __commonJS({ - "node_modules/get-proto/index.js"(exports2, module2) { - "use strict"; - var reflectGetProto = require_Reflect_getPrototypeOf(); - var originalGetProto = require_Object_getPrototypeOf(); - var getDunderProto = require_get(); - module2.exports = reflectGetProto ? function getProto(O) { - return reflectGetProto(O); - } : originalGetProto ? function getProto(O) { - if (!O || typeof O !== "object" && typeof O !== "function") { - throw new TypeError("getProto: not an object"); - } - return originalGetProto(O); - } : getDunderProto ? function getProto(O) { - return getDunderProto(O); - } : null; - } -}); - -// node_modules/hasown/index.js -var require_hasown = __commonJS({ - "node_modules/hasown/index.js"(exports2, module2) { - "use strict"; - var call2 = Function.prototype.call; - var $hasOwn = Object.prototype.hasOwnProperty; - var bind2 = require_function_bind(); - module2.exports = bind2.call(call2, $hasOwn); - } -}); - -// node_modules/get-intrinsic/index.js -var require_get_intrinsic = __commonJS({ - "node_modules/get-intrinsic/index.js"(exports2, module2) { - "use strict"; - var undefined2; - var $Object = require_es_object_atoms(); - var $Error = require_es_errors(); - var $EvalError = require_eval(); - var $RangeError = require_range(); - var $ReferenceError = require_ref(); - var $SyntaxError = require_syntax(); - var $TypeError = require_type(); - var $URIError = require_uri(); - var abs = require_abs(); - var floor = require_floor(); - var max = require_max(); - var min = require_min(); - var pow3 = require_pow(); - var round = require_round(); - var sign2 = require_sign(); - var $Function = Function; - var getEvalledConstructor = function(expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); - } catch (e) { - } - }; - var $gOPD = require_gopd(); - var $defineProperty = require_es_define_property(); - var throwTypeError = function() { - throw new $TypeError(); - }; - var ThrowTypeError = $gOPD ? function() { - try { - arguments.callee; - return throwTypeError; - } catch (calleeThrows) { - try { - return $gOPD(arguments, "callee").get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }() : throwTypeError; - var hasSymbols = require_has_symbols()(); - var getProto = require_get_proto(); - var $ObjectGPO = require_Object_getPrototypeOf(); - var $ReflectGPO = require_Reflect_getPrototypeOf(); - var $apply = require_functionApply(); - var $call = require_functionCall(); - var needsEval = {}; - var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array); - var INTRINSICS = { - __proto__: null, - "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError, - "%Array%": Array, - "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer, - "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, - "%AsyncFromSyncIteratorPrototype%": undefined2, - "%AsyncFunction%": needsEval, - "%AsyncGenerator%": needsEval, - "%AsyncGeneratorFunction%": needsEval, - "%AsyncIteratorPrototype%": needsEval, - "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics, - "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt, - "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array, - "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array, - "%Boolean%": Boolean, - "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView, - "%Date%": Date, - "%decodeURI%": decodeURI, - "%decodeURIComponent%": decodeURIComponent, - "%encodeURI%": encodeURI, - "%encodeURIComponent%": encodeURIComponent, - "%Error%": $Error, - "%eval%": eval, - // eslint-disable-line no-eval - "%EvalError%": $EvalError, - "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array, - "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array, - "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array, - "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry, - "%Function%": $Function, - "%GeneratorFunction%": needsEval, - "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array, - "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array, - "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array, - "%isFinite%": isFinite, - "%isNaN%": isNaN, - "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, - "%JSON%": typeof JSON === "object" ? JSON : undefined2, - "%Map%": typeof Map === "undefined" ? undefined2 : Map, - "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()), - "%Math%": Math, - "%Number%": Number, - "%Object%": $Object, - "%Object.getOwnPropertyDescriptor%": $gOPD, - "%parseFloat%": parseFloat, - "%parseInt%": parseInt, - "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise, - "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy, - "%RangeError%": $RangeError, - "%ReferenceError%": $ReferenceError, - "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect, - "%RegExp%": RegExp, - "%Set%": typeof Set === "undefined" ? undefined2 : Set, - "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()), - "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer, - "%String%": String, - "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, - "%Symbol%": hasSymbols ? Symbol : undefined2, - "%SyntaxError%": $SyntaxError, - "%ThrowTypeError%": ThrowTypeError, - "%TypedArray%": TypedArray, - "%TypeError%": $TypeError, - "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array, - "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray, - "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array, - "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array, - "%URIError%": $URIError, - "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap, - "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef, - "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet, - "%Function.prototype.call%": $call, - "%Function.prototype.apply%": $apply, - "%Object.defineProperty%": $defineProperty, - "%Object.getPrototypeOf%": $ObjectGPO, - "%Math.abs%": abs, - "%Math.floor%": floor, - "%Math.max%": max, - "%Math.min%": min, - "%Math.pow%": pow3, - "%Math.round%": round, - "%Math.sign%": sign2, - "%Reflect.getPrototypeOf%": $ReflectGPO - }; - if (getProto) { - try { - null.error; - } catch (e) { - errorProto = getProto(getProto(e)); - INTRINSICS["%Error.prototype%"] = errorProto; - } - } - var errorProto; - var doEval = function doEval2(name) { - var value; - if (name === "%AsyncFunction%") { - value = getEvalledConstructor("async function () {}"); - } else if (name === "%GeneratorFunction%") { - value = getEvalledConstructor("function* () {}"); - } else if (name === "%AsyncGeneratorFunction%") { - value = getEvalledConstructor("async function* () {}"); - } else if (name === "%AsyncGenerator%") { - var fn2 = doEval2("%AsyncGeneratorFunction%"); - if (fn2) { - value = fn2.prototype; - } - } else if (name === "%AsyncIteratorPrototype%") { - var gen3 = doEval2("%AsyncGenerator%"); - if (gen3 && getProto) { - value = getProto(gen3.prototype); - } - } - INTRINSICS[name] = value; - return value; - }; - var LEGACY_ALIASES = { - __proto__: null, - "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], - "%ArrayPrototype%": ["Array", "prototype"], - "%ArrayProto_entries%": ["Array", "prototype", "entries"], - "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], - "%ArrayProto_keys%": ["Array", "prototype", "keys"], - "%ArrayProto_values%": ["Array", "prototype", "values"], - "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], - "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], - "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], - "%BooleanPrototype%": ["Boolean", "prototype"], - "%DataViewPrototype%": ["DataView", "prototype"], - "%DatePrototype%": ["Date", "prototype"], - "%ErrorPrototype%": ["Error", "prototype"], - "%EvalErrorPrototype%": ["EvalError", "prototype"], - "%Float32ArrayPrototype%": ["Float32Array", "prototype"], - "%Float64ArrayPrototype%": ["Float64Array", "prototype"], - "%FunctionPrototype%": ["Function", "prototype"], - "%Generator%": ["GeneratorFunction", "prototype"], - "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], - "%Int8ArrayPrototype%": ["Int8Array", "prototype"], - "%Int16ArrayPrototype%": ["Int16Array", "prototype"], - "%Int32ArrayPrototype%": ["Int32Array", "prototype"], - "%JSONParse%": ["JSON", "parse"], - "%JSONStringify%": ["JSON", "stringify"], - "%MapPrototype%": ["Map", "prototype"], - "%NumberPrototype%": ["Number", "prototype"], - "%ObjectPrototype%": ["Object", "prototype"], - "%ObjProto_toString%": ["Object", "prototype", "toString"], - "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], - "%PromisePrototype%": ["Promise", "prototype"], - "%PromiseProto_then%": ["Promise", "prototype", "then"], - "%Promise_all%": ["Promise", "all"], - "%Promise_reject%": ["Promise", "reject"], - "%Promise_resolve%": ["Promise", "resolve"], - "%RangeErrorPrototype%": ["RangeError", "prototype"], - "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], - "%RegExpPrototype%": ["RegExp", "prototype"], - "%SetPrototype%": ["Set", "prototype"], - "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], - "%StringPrototype%": ["String", "prototype"], - "%SymbolPrototype%": ["Symbol", "prototype"], - "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], - "%TypedArrayPrototype%": ["TypedArray", "prototype"], - "%TypeErrorPrototype%": ["TypeError", "prototype"], - "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], - "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], - "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], - "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], - "%URIErrorPrototype%": ["URIError", "prototype"], - "%WeakMapPrototype%": ["WeakMap", "prototype"], - "%WeakSetPrototype%": ["WeakSet", "prototype"] - }; - var bind2 = require_function_bind(); - var hasOwn = require_hasown(); - var $concat = bind2.call($call, Array.prototype.concat); - var $spliceApply = bind2.call($apply, Array.prototype.splice); - var $replace = bind2.call($call, String.prototype.replace); - var $strSlice = bind2.call($call, String.prototype.slice); - var $exec = bind2.call($call, RegExp.prototype.exec); - var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; - var reEscapeChar = /\\(\\)?/g; - var stringToPath = function stringToPath2(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === "%" && last !== "%") { - throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); - } else if (last === "%" && first !== "%") { - throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); - } - var result = []; - $replace(string, rePropName, function(match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match; - }); - return result; - }; - var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = "%" + alias[0] + "%"; - } - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === "undefined" && !allowMissing) { - throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!"); - } - return { - alias, - name: intrinsicName, - value - }; - } - throw new $SyntaxError("intrinsic " + name + " does not exist!"); - }; - module2.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== "string" || name.length === 0) { - throw new $TypeError("intrinsic name must be a non-empty string"); - } - if (arguments.length > 1 && typeof allowMissing !== "boolean") { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - if ($exec(/^%?[^%]*%?$/, name) === null) { - throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); - } - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; - var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { - throw new $SyntaxError("property names with quotes must have matching quotes"); - } - if (part === "constructor" || !isOwn) { - skipFurtherCaching = true; - } - intrinsicBaseName += "." + part; - intrinsicRealName = "%" + intrinsicBaseName + "%"; - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available."); - } - return void undefined2; - } - if ($gOPD && i + 1 >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - if (isOwn && "get" in desc && !("originalValue" in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; - }; - } -}); - -// node_modules/has-tostringtag/shams.js -var require_shams2 = __commonJS({ - "node_modules/has-tostringtag/shams.js"(exports2, module2) { - "use strict"; - var hasSymbols = require_shams(); - module2.exports = function hasToStringTagShams() { - return hasSymbols() && !!Symbol.toStringTag; - }; - } -}); - -// node_modules/es-set-tostringtag/index.js -var require_es_set_tostringtag = __commonJS({ - "node_modules/es-set-tostringtag/index.js"(exports2, module2) { - "use strict"; - var GetIntrinsic = require_get_intrinsic(); - var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); - var hasToStringTag = require_shams2()(); - var hasOwn = require_hasown(); - var $TypeError = require_type(); - var toStringTag2 = hasToStringTag ? Symbol.toStringTag : null; - module2.exports = function setToStringTag(object, value) { - var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; - var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; - if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") { - throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans"); - } - if (toStringTag2 && (overrideIfSet || !hasOwn(object, toStringTag2))) { - if ($defineProperty) { - $defineProperty(object, toStringTag2, { - configurable: !nonConfigurable, - enumerable: false, - value, - writable: false - }); - } else { - object[toStringTag2] = value; - } - } - }; - } -}); - -// node_modules/form-data/lib/populate.js -var require_populate = __commonJS({ - "node_modules/form-data/lib/populate.js"(exports2, module2) { - module2.exports = function(dst, src) { - Object.keys(src).forEach(function(prop) { - dst[prop] = dst[prop] || src[prop]; - }); - return dst; - }; - } -}); - -// node_modules/form-data/lib/form_data.js -var require_form_data = __commonJS({ - "node_modules/form-data/lib/form_data.js"(exports2, module2) { - var CombinedStream = require_combined_stream(); - var util3 = __require("util"); - var path = __require("path"); - var http3 = __require("http"); - var https2 = __require("https"); - var parseUrl = __require("url").parse; - var fs2 = __require("fs"); - var Stream = __require("stream").Stream; - var mime = require_mime_types(); - var asynckit = require_asynckit(); - var setToStringTag = require_es_set_tostringtag(); - var populate = require_populate(); - module2.exports = FormData3; - util3.inherits(FormData3, CombinedStream); - function FormData3(options) { - if (!(this instanceof FormData3)) { - return new FormData3(options); - } - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - CombinedStream.call(this); - options = options || {}; - for (var option in options) { - this[option] = options[option]; - } - } - FormData3.LINE_BREAK = "\r\n"; - FormData3.DEFAULT_CONTENT_TYPE = "application/octet-stream"; - FormData3.prototype.append = function(field, value, options) { - options = options || {}; - if (typeof options == "string") { - options = { filename: options }; - } - var append2 = CombinedStream.prototype.append.bind(this); - if (typeof value == "number") { - value = "" + value; - } - if (Array.isArray(value)) { - this._error(new Error("Arrays are not supported.")); - return; - } - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); - append2(header); - append2(value); - append2(footer); - this._trackLength(header, value, options); - }; - FormData3.prototype._trackLength = function(header, value, options) { - var valueLength = 0; - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === "string") { - valueLength = Buffer.byteLength(value); - } - this._valueLength += valueLength; - this._overheadLength += Buffer.byteLength(header) + FormData3.LINE_BREAK.length; - if (!value || !value.path && !(value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) && !(value instanceof Stream)) { - return; - } - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } - }; - FormData3.prototype._lengthRetriever = function(value, callback) { - if (Object.prototype.hasOwnProperty.call(value, "fd")) { - if (value.end != void 0 && value.end != Infinity && value.start != void 0) { - callback(null, value.end + 1 - (value.start ? value.start : 0)); - } else { - fs2.stat(value.path, function(err, stat) { - var fileSize; - if (err) { - callback(err); - return; - } - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } - } else if (Object.prototype.hasOwnProperty.call(value, "httpVersion")) { - callback(null, +value.headers["content-length"]); - } else if (Object.prototype.hasOwnProperty.call(value, "httpModule")) { - value.on("response", function(response) { - value.pause(); - callback(null, +response.headers["content-length"]); - }); - value.resume(); - } else { - callback("Unknown stream"); - } - }; - FormData3.prototype._multiPartHeader = function(field, value, options) { - if (typeof options.header == "string") { - return options.header; - } - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - var contents = ""; - var headers = { - // add custom disposition as third element or keep it two elements if not - "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - "Content-Type": [].concat(contentType || []) - }; - if (typeof options.header == "object") { - populate(headers, options.header); - } - var header; - for (var prop in headers) { - if (Object.prototype.hasOwnProperty.call(headers, prop)) { - header = headers[prop]; - if (header == null) { - continue; - } - if (!Array.isArray(header)) { - header = [header]; - } - if (header.length) { - contents += prop + ": " + header.join("; ") + FormData3.LINE_BREAK; - } - } - } - return "--" + this.getBoundary() + FormData3.LINE_BREAK + contents + FormData3.LINE_BREAK; - }; - FormData3.prototype._getContentDisposition = function(value, options) { - var filename, contentDisposition; - if (typeof options.filepath === "string") { - filename = path.normalize(options.filepath).replace(/\\/g, "/"); - } else if (options.filename || value.name || value.path) { - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) { - filename = path.basename(value.client._httpMessage.path || ""); - } - if (filename) { - contentDisposition = 'filename="' + filename + '"'; - } - return contentDisposition; - }; - FormData3.prototype._getContentType = function(value, options) { - var contentType = options.contentType; - if (!contentType && value.name) { - contentType = mime.lookup(value.name); - } - if (!contentType && value.path) { - contentType = mime.lookup(value.path); - } - if (!contentType && value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) { - contentType = value.headers["content-type"]; - } - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } - if (!contentType && typeof value == "object") { - contentType = FormData3.DEFAULT_CONTENT_TYPE; - } - return contentType; - }; - FormData3.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData3.LINE_BREAK; - var lastPart = this._streams.length === 0; - if (lastPart) { - footer += this._lastBoundary(); - } - next(footer); - }.bind(this); - }; - FormData3.prototype._lastBoundary = function() { - return "--" + this.getBoundary() + "--" + FormData3.LINE_BREAK; - }; - FormData3.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - "content-type": "multipart/form-data; boundary=" + this.getBoundary() - }; - for (header in userHeaders) { - if (Object.prototype.hasOwnProperty.call(userHeaders, header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } - } - return formHeaders; - }; - FormData3.prototype.setBoundary = function(boundary) { - this._boundary = boundary; - }; - FormData3.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); - } - return this._boundary; - }; - FormData3.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc(0); - var boundary = this.getBoundary(); - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== "function") { - if (Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); - } else { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); - } - if (typeof this._streams[i] !== "string" || this._streams[i].substring(2, boundary.length + 2) !== boundary) { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData3.LINE_BREAK)]); - } - } - } - return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); - }; - FormData3.prototype._generateBoundary = function() { - var boundary = "--------------------------"; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); - } - this._boundary = boundary; - }; - FormData3.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - if (!this.hasKnownLength()) { - this._error(new Error("Cannot calculate proper length in synchronous way.")); - } - return knownLength; - }; - FormData3.prototype.hasKnownLength = function() { - var hasKnownLength = true; - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } - return hasKnownLength; - }; - FormData3.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; - } - values.forEach(function(length) { - knownLength += length; - }); - cb(null, knownLength); - }); - }; - FormData3.prototype.submit = function(params, cb) { - var request, options, defaults2 = { method: "post" }; - if (typeof params == "string") { - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults2); - } else { - options = populate(params, defaults2); - if (!options.port) { - options.port = options.protocol == "https:" ? 443 : 80; - } - } - options.headers = this.getHeaders(params.headers); - if (options.protocol == "https:") { - request = https2.request(options); - } else { - request = http3.request(options); - } - this.getLength(function(err, length) { - if (err && err !== "Unknown stream") { - this._error(err); - return; - } - if (length) { - request.setHeader("Content-Length", length); - } - this.pipe(request); - if (cb) { - var onResponse; - var callback = function(error, responce) { - request.removeListener("error", callback); - request.removeListener("response", onResponse); - return cb.call(this, error, responce); - }; - onResponse = callback.bind(this, null); - request.on("error", callback); - request.on("response", onResponse); - } - }.bind(this)); - return request; - }; - FormData3.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit("error", err); - } - }; - FormData3.prototype.toString = function() { - return "[object FormData]"; - }; - setToStringTag(FormData3, "FormData"); - } -}); - -// node_modules/proxy-from-env/index.js -var require_proxy_from_env = __commonJS({ - "node_modules/proxy-from-env/index.js"(exports2) { - "use strict"; - var parseUrl = __require("url").parse; - var DEFAULT_PORTS = { - ftp: 21, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443 - }; - var stringEndsWith = String.prototype.endsWith || function(s) { - return s.length <= this.length && this.indexOf(s, this.length - s.length) !== -1; - }; - function getProxyForUrl(url2) { - var parsedUrl = typeof url2 === "string" ? parseUrl(url2) : url2 || {}; - var proto = parsedUrl.protocol; - var hostname = parsedUrl.host; - var port = parsedUrl.port; - if (typeof hostname !== "string" || !hostname || typeof proto !== "string") { - return ""; - } - proto = proto.split(":", 1)[0]; - hostname = hostname.replace(/:\d*$/, ""); - port = parseInt(port) || DEFAULT_PORTS[proto] || 0; - if (!shouldProxy(hostname, port)) { - return ""; - } - var proxy = getEnv("npm_config_" + proto + "_proxy") || getEnv(proto + "_proxy") || getEnv("npm_config_proxy") || getEnv("all_proxy"); - if (proxy && proxy.indexOf("://") === -1) { - proxy = proto + "://" + proxy; - } - return proxy; - } - function shouldProxy(hostname, port) { - var NO_PROXY = (getEnv("npm_config_no_proxy") || getEnv("no_proxy")).toLowerCase(); - if (!NO_PROXY) { - return true; - } - if (NO_PROXY === "*") { - return false; - } - return NO_PROXY.split(/[,\s]/).every(function(proxy) { - if (!proxy) { - return true; - } - var parsedProxy = proxy.match(/^(.+):(\d+)$/); - var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; - var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; - if (parsedProxyPort && parsedProxyPort !== port) { - return true; - } - if (!/^[.*]/.test(parsedProxyHostname)) { - return hostname !== parsedProxyHostname; - } - if (parsedProxyHostname.charAt(0) === "*") { - parsedProxyHostname = parsedProxyHostname.slice(1); - } - return !stringEndsWith.call(hostname, parsedProxyHostname); - }); - } - function getEnv(key) { - return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ""; - } - exports2.getProxyForUrl = getProxyForUrl; - } -}); - -// node_modules/ms/index.js -var require_ms = __commonJS({ - "node_modules/ms/index.js"(exports2, module2) { - var s = 1e3; - var m2 = s * 60; - var h = m2 * 60; - var d = h * 24; - var w2 = d * 7; - var y2 = d * 365.25; - module2.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === "string" && val.length > 0) { - return parse(val); - } else if (type === "number" && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) - ); - }; - function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || "ms").toLowerCase(); - switch (type) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y2; - case "weeks": - case "week": - case "w": - return n * w2; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m2; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return void 0; - } - } - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + "d"; - } - if (msAbs >= h) { - return Math.round(ms / h) + "h"; - } - if (msAbs >= m2) { - return Math.round(ms / m2) + "m"; - } - if (msAbs >= s) { - return Math.round(ms / s) + "s"; - } - return ms + "ms"; - } - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, "day"); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, "hour"); - } - if (msAbs >= m2) { - return plural(ms, msAbs, m2, "minute"); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, "second"); - } - return ms + " ms"; - } - function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); - } - } -}); - -// node_modules/debug/src/common.js -var require_common = __commonJS({ - "node_modules/debug/src/common.js"(exports2, module2) { - function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require_ms(); - createDebug.destroy = destroy; - Object.keys(env).forEach((key) => { - createDebug[key] = env[key]; - }); - createDebug.names = []; - createDebug.skips = []; - createDebug.formatters = {}; - function selectColor(namespace) { - let hash2 = 0; - for (let i = 0; i < namespace.length; i++) { - hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); - hash2 |= 0; - } - return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug(...args) { - if (!debug.enabled) { - return; - } - const self2 = debug; - const curr = Number(/* @__PURE__ */ new Date()); - const ms = curr - (prevTime || curr); - self2.diff = ms; - self2.prev = prevTime; - self2.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== "string") { - args.unshift("%O"); - } - let index2 = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - if (match === "%%") { - return "%"; - } - index2++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === "function") { - const val = args[index2]; - match = formatter.call(self2, val); - args.splice(index2, 1); - index2--; - } - return match; - }); - createDebug.formatArgs.call(self2, args); - const logFn = self2.log || createDebug.log; - logFn.apply(self2, args); - } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend2; - debug.destroy = createDebug.destroy; - Object.defineProperty(debug, "enabled", { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - return enabledCache; - }, - set: (v) => { - enableOverride = v; - } - }); - if (typeof createDebug.init === "function") { - createDebug.init(debug); - } - return debug; - } - function extend2(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - const split3 = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); - for (const ns2 of split3) { - if (ns2[0] === "-") { - createDebug.skips.push(ns2.slice(1)); - } else { - createDebug.names.push(ns2); - } - } - } - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { - if (template[templateIndex] === "*") { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; - } - } - while (templateIndex < template.length && template[templateIndex] === "*") { - templateIndex++; - } - return templateIndex === template.length; - } - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map((namespace) => "-" + namespace) - ].join(","); - createDebug.enable(""); - return namespaces; - } - function enabled(name) { - for (const skip2 of createDebug.skips) { - if (matchesTemplate(name, skip2)) { - return false; - } - } - for (const ns2 of createDebug.names) { - if (matchesTemplate(name, ns2)) { - return true; - } - } - return false; - } - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - function destroy() { - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - createDebug.enable(createDebug.load()); - return createDebug; - } - module2.exports = setup; - } -}); - -// node_modules/debug/src/browser.js -var require_browser = __commonJS({ - "node_modules/debug/src/browser.js"(exports2, module2) { - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load; - exports2.useColors = useColors; - exports2.storage = localstorage(); - exports2.destroy = /* @__PURE__ */ (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - }; - })(); - exports2.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33" - ]; - function useColors() { - if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { - return true; - } - if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - let m2; - return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 - typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - typeof navigator !== "undefined" && navigator.userAgent && (m2 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m2[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker - typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); - } - function formatArgs(args) { - args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); - if (!this.useColors) { - return; - } - const c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); - let index2 = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match) => { - if (match === "%%") { - return; - } - index2++; - if (match === "%c") { - lastC = index2; - } - }); - args.splice(lastC, 0, c); - } - exports2.log = console.debug || console.log || (() => { - }); - function save(namespaces) { - try { - if (namespaces) { - exports2.storage.setItem("debug", namespaces); - } else { - exports2.storage.removeItem("debug"); - } - } catch (error) { - } - } - function load() { - let r; - try { - r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); - } catch (error) { - } - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; - } - return r; - } - function localstorage() { - try { - return localStorage; - } catch (error) { - } - } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (error) { - return "[UnexpectedJSONParseError]: " + error.message; - } - }; - } -}); - -// node_modules/has-flag/index.js -var require_has_flag = __commonJS({ - "node_modules/has-flag/index.js"(exports2, module2) { - "use strict"; - module2.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf("--"); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); - }; - } -}); - -// node_modules/supports-color/index.js -var require_supports_color = __commonJS({ - "node_modules/supports-color/index.js"(exports2, module2) { - "use strict"; - var os2 = __require("os"); - var tty = __require("tty"); - var hasFlag = require_has_flag(); - var { env } = process; - var forceColor; - if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { - forceColor = 0; - } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { - forceColor = 1; - } - if ("FORCE_COLOR" in env) { - if (env.FORCE_COLOR === "true") { - forceColor = 1; - } else if (env.FORCE_COLOR === "false") { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } - } - function translateLevel(level) { - if (level === 0) { - return false; - } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; - } - function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } - if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { - return 3; - } - if (hasFlag("color=256")) { - return 2; - } - if (haveStream && !streamIsTTY && forceColor === void 0) { - return 0; - } - const min = forceColor || 0; - if (env.TERM === "dumb") { - return min; - } - if (process.platform === "win32") { - const osRelease = os2.release().split("."); - if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - return 1; - } - if ("CI" in env) { - if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign2) => sign2 in env) || env.CI_NAME === "codeship") { - return 1; - } - return min; - } - if ("TEAMCITY_VERSION" in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - if (env.COLORTERM === "truecolor") { - return 3; - } - if ("TERM_PROGRAM" in env) { - const version4 = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); - switch (env.TERM_PROGRAM) { - case "iTerm.app": - return version4 >= 3 ? 3 : 2; - case "Apple_Terminal": - return 2; - } - } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - if ("COLORTERM" in env) { - return 1; - } - return min; - } - function getSupportLevel(stream4) { - const level = supportsColor(stream4, stream4 && stream4.isTTY); - return translateLevel(level); - } - module2.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) - }; - } -}); - -// node_modules/debug/src/node.js -var require_node = __commonJS({ - "node_modules/debug/src/node.js"(exports2, module2) { - var tty = __require("tty"); - var util3 = __require("util"); - exports2.init = init; - exports2.log = log; - exports2.formatArgs = formatArgs; - exports2.save = save; - exports2.load = load; - exports2.useColors = useColors; - exports2.destroy = util3.deprecate( - () => { - }, - "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." - ); - exports2.colors = [6, 2, 3, 4, 5, 1]; - try { - const supportsColor = require_supports_color(); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports2.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } - } catch (error) { - } - exports2.inspectOpts = Object.keys(process.env).filter((key) => { - return /^debug_/i.test(key); - }).reduce((obj, key) => { - const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k2) => { - return k2.toUpperCase(); - }); - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === "null") { - val = null; - } else { - val = Number(val); - } - obj[prop] = val; - return obj; - }, {}); - function useColors() { - return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); - } - function formatArgs(args) { - const { namespace: name, useColors: useColors2 } = this; - if (useColors2) { - const c = this.color; - const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); - const prefix = ` ${colorCode};1m${name} \x1B[0m`; - args[0] = prefix + args[0].split("\n").join("\n" + prefix); - args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); - } else { - args[0] = getDate() + name + " " + args[0]; - } - } - function getDate() { - if (exports2.inspectOpts.hideDate) { - return ""; - } - return (/* @__PURE__ */ new Date()).toISOString() + " "; - } - function log(...args) { - return process.stderr.write(util3.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); - } - function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - delete process.env.DEBUG; - } - } - function load() { - return process.env.DEBUG; - } - function init(debug) { - debug.inspectOpts = {}; - const keys = Object.keys(exports2.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; - } - } - module2.exports = require_common()(exports2); - var { formatters } = module2.exports; - formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util3.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); - }; - formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util3.inspect(v, this.inspectOpts); - }; - } -}); - -// node_modules/debug/src/index.js -var require_src = __commonJS({ - "node_modules/debug/src/index.js"(exports2, module2) { - if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { - module2.exports = require_browser(); - } else { - module2.exports = require_node(); - } - } -}); - -// node_modules/follow-redirects/debug.js -var require_debug = __commonJS({ - "node_modules/follow-redirects/debug.js"(exports2, module2) { - var debug; - module2.exports = function() { - if (!debug) { - try { - debug = require_src()("follow-redirects"); - } catch (error) { - } - if (typeof debug !== "function") { - debug = function() { - }; - } - } - debug.apply(null, arguments); - }; - } -}); - -// node_modules/follow-redirects/index.js -var require_follow_redirects = __commonJS({ - "node_modules/follow-redirects/index.js"(exports2, module2) { - var url2 = __require("url"); - var URL2 = url2.URL; - var http3 = __require("http"); - var https2 = __require("https"); - var Writable = __require("stream").Writable; - var assert3 = __require("assert"); - var debug = require_debug(); - (function detectUnsupportedEnvironment() { - var looksLikeNode = typeof process !== "undefined"; - var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; - var looksLikeV8 = isFunction2(Error.captureStackTrace); - if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { - console.warn("The follow-redirects package should be excluded from browser builds."); - } - })(); - var useNativeURL = false; - try { - assert3(new URL2("")); - } catch (error) { - useNativeURL = error.code === "ERR_INVALID_URL"; - } - var preservedUrlFields = [ - "auth", - "host", - "hostname", - "href", - "path", - "pathname", - "port", - "protocol", - "query", - "search", - "hash" - ]; - var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; - var eventHandlers = /* @__PURE__ */ Object.create(null); - events.forEach(function(event) { - eventHandlers[event] = function(arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; - }); - var InvalidUrlError = createErrorType( - "ERR_INVALID_URL", - "Invalid URL", - TypeError - ); - var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "Redirected request failed" - ); - var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded", - RedirectionError - ); - var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" - ); - var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" - ); - var destroy = Writable.prototype.destroy || noop2; - function RedirectableRequest(options, responseCallback) { - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; - if (responseCallback) { - this.on("response", responseCallback); - } - var self2 = this; - this._onNativeResponse = function(response) { - try { - self2._processResponse(response); - } catch (cause) { - self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause })); - } - }; - this._performRequest(); - } - RedirectableRequest.prototype = Object.create(Writable.prototype); - RedirectableRequest.prototype.abort = function() { - destroyRequest(this._currentRequest); - this._currentRequest.abort(); - this.emit("abort"); - }; - RedirectableRequest.prototype.destroy = function(error) { - destroyRequest(this._currentRequest, error); - destroy.call(this, error); - return this; - }; - RedirectableRequest.prototype.write = function(data, encoding, callback) { - if (this._ending) { - throw new WriteAfterEndError(); - } - if (!isString2(data) && !isBuffer2(data)) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (isFunction2(encoding)) { - callback = encoding; - encoding = null; - } - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data, encoding }); - this._currentRequest.write(data, encoding, callback); - } else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } - }; - RedirectableRequest.prototype.end = function(data, encoding, callback) { - if (isFunction2(data)) { - callback = data; - data = encoding = null; - } else if (isFunction2(encoding)) { - callback = encoding; - encoding = null; - } - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } else { - var self2 = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function() { - self2._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } - }; - RedirectableRequest.prototype.setHeader = function(name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); - }; - RedirectableRequest.prototype.removeHeader = function(name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); - }; - RedirectableRequest.prototype.setTimeout = function(msecs, callback) { - var self2 = this; - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } - function startTimer(socket) { - if (self2._timeout) { - clearTimeout(self2._timeout); - } - self2._timeout = setTimeout(function() { - self2.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } - function clearTimer() { - if (self2._timeout) { - clearTimeout(self2._timeout); - self2._timeout = null; - } - self2.removeListener("abort", clearTimer); - self2.removeListener("error", clearTimer); - self2.removeListener("response", clearTimer); - self2.removeListener("close", clearTimer); - if (callback) { - self2.removeListener("timeout", callback); - } - if (!self2.socket) { - self2._currentRequest.removeListener("socket", startTimer); - } - } - if (callback) { - this.on("timeout", callback); - } - if (this.socket) { - startTimer(this.socket); - } else { - this._currentRequest.once("socket", startTimer); - } - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); - this.on("close", clearTimer); - return this; - }; - [ - "flushHeaders", - "getHeader", - "setNoDelay", - "setSocketKeepAlive" - ].forEach(function(method) { - RedirectableRequest.prototype[method] = function(a, b2) { - return this._currentRequest[method](a, b2); - }; - }); - ["aborted", "connection", "socket"].forEach(function(property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function() { - return this._currentRequest[property]; - } - }); - }); - RedirectableRequest.prototype._sanitizeOptions = function(options) { - if (!options.headers) { - options.headers = {}; - } - if (options.host) { - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } - }; - RedirectableRequest.prototype._performRequest = function() { - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - throw new TypeError("Unsupported protocol " + protocol); - } - if (this._options.agents) { - var scheme = protocol.slice(0, -1); - this._options.agent = this._options.agents[scheme]; - } - var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse); - request._redirectable = this; - for (var event of events) { - request.on(event, eventHandlers[event]); - } - this._currentUrl = /^\//.test(this._options.path) ? url2.format(this._options) : ( - // When making a request to a proxy, […] - // a client MUST send the target URI in absolute-form […]. - this._options.path - ); - if (this._isRedirect) { - var i = 0; - var self2 = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - if (request === self2._currentRequest) { - if (error) { - self2.emit("error", error); - } else if (i < buffers.length) { - var buffer2 = buffers[i++]; - if (!request.finished) { - request.write(buffer2.data, buffer2.encoding, writeNext); - } - } else if (self2._ended) { - request.end(); - } - } - })(); - } - }; - RedirectableRequest.prototype._processResponse = function(response) { - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode - }); - } - var location = response.headers.location; - if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - this._requestBodyBuffers = []; - return; - } - destroyRequest(this._currentRequest); - response.destroy(); - if (++this._redirectCount > this._options.maxRedirects) { - throw new TooManyRedirectsError(); - } - var requestHeaders; - var beforeRedirect = this._options.beforeRedirect; - if (beforeRedirect) { - requestHeaders = Object.assign({ - // The Host header was set by nativeProtocol.request - Host: response.req.getHeader("host") - }, this._options.headers); - } - var method = this._options.method; - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); - var currentUrlParts = parseUrl(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url2.format(Object.assign(currentUrlParts, { host: currentHost })); - var redirectUrl = resolveUrl(location, currentUrl); - debug("redirecting to", redirectUrl.href); - this._isRedirect = true; - spreadUrlObject(redirectUrl, this._options); - if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) { - removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); - } - if (isFunction2(beforeRedirect)) { - var responseDetails = { - headers: response.headers, - statusCode - }; - var requestDetails = { - url: currentUrl, - method, - headers: requestHeaders - }; - beforeRedirect(this._options, responseDetails, requestDetails); - this._sanitizeOptions(this._options); - } - this._performRequest(); - }; - function wrap(protocols) { - var exports3 = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024 - }; - var nativeProtocols = {}; - Object.keys(protocols).forEach(function(scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports3[scheme] = Object.create(nativeProtocol); - function request(input, options, callback) { - if (isURL(input)) { - input = spreadUrlObject(input); - } else if (isString2(input)) { - input = spreadUrlObject(parseUrl(input)); - } else { - callback = options; - options = validateUrl(input); - input = { protocol }; - } - if (isFunction2(options)) { - callback = options; - options = null; - } - options = Object.assign({ - maxRedirects: exports3.maxRedirects, - maxBodyLength: exports3.maxBodyLength - }, input, options); - options.nativeProtocols = nativeProtocols; - if (!isString2(options.host) && !isString2(options.hostname)) { - options.hostname = "::1"; - } - assert3.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true } - }); - }); - return exports3; - } - function noop2() { - } - function parseUrl(input) { - var parsed; - if (useNativeURL) { - parsed = new URL2(input); - } else { - parsed = validateUrl(url2.parse(input)); - if (!isString2(parsed.protocol)) { - throw new InvalidUrlError({ input }); - } - } - return parsed; - } - function resolveUrl(relative, base) { - return useNativeURL ? new URL2(relative, base) : parseUrl(url2.resolve(base, relative)); - } - function validateUrl(input) { - if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { - throw new InvalidUrlError({ input: input.href || input }); - } - if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { - throw new InvalidUrlError({ input: input.href || input }); - } - return input; - } - function spreadUrlObject(urlObject, target) { - var spread3 = target || {}; - for (var key of preservedUrlFields) { - spread3[key] = urlObject[key]; - } - if (spread3.hostname.startsWith("[")) { - spread3.hostname = spread3.hostname.slice(1, -1); - } - if (spread3.port !== "") { - spread3.port = Number(spread3.port); - } - spread3.path = spread3.search ? spread3.pathname + spread3.search : spread3.pathname; - return spread3; - } - function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } - } - return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim(); - } - function createErrorType(code, message, baseClass) { - function CustomError(properties) { - if (isFunction2(Error.captureStackTrace)) { - Error.captureStackTrace(this, this.constructor); - } - Object.assign(this, properties || {}); - this.code = code; - this.message = this.cause ? message + ": " + this.cause.message : message; - } - CustomError.prototype = new (baseClass || Error)(); - Object.defineProperties(CustomError.prototype, { - constructor: { - value: CustomError, - enumerable: false - }, - name: { - value: "Error [" + code + "]", - enumerable: false - } - }); - return CustomError; - } - function destroyRequest(request, error) { - for (var event of events) { - request.removeListener(event, eventHandlers[event]); - } - request.on("error", noop2); - request.destroy(error); - } - function isSubdomain(subdomain, domain) { - assert3(isString2(subdomain) && isString2(domain)); - var dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); - } - function isString2(value) { - return typeof value === "string" || value instanceof String; - } - function isFunction2(value) { - return typeof value === "function"; - } - function isBuffer2(value) { - return typeof value === "object" && "length" in value; - } - function isURL(value) { - return URL2 && value instanceof URL2; - } - module2.exports = wrap({ http: http3, https: https2 }); - module2.exports.wrap = wrap; - } -}); - -// node_modules/logform/format.js -var require_format = __commonJS({ - "node_modules/logform/format.js"(exports2, module2) { - "use strict"; - var InvalidFormatError = class _InvalidFormatError extends Error { - constructor(formatFn) { - super(`Format functions must be synchronous taking a two arguments: (info, opts) -Found: ${formatFn.toString().split("\n")[0]} -`); - Error.captureStackTrace(this, _InvalidFormatError); - } - }; - module2.exports = (formatFn) => { - if (formatFn.length > 2) { - throw new InvalidFormatError(formatFn); - } - function Format(options = {}) { - this.options = options; - } - Format.prototype.transform = formatFn; - function createFormatWrap(opts) { - return new Format(opts); - } - createFormatWrap.Format = Format; - return createFormatWrap; - }; - } -}); - -// node_modules/@colors/colors/lib/styles.js -var require_styles = __commonJS({ - "node_modules/@colors/colors/lib/styles.js"(exports2, module2) { - var styles = {}; - module2["exports"] = styles; - var codes = { - reset: [0, 0], - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - grey: [90, 39], - brightRed: [91, 39], - brightGreen: [92, 39], - brightYellow: [93, 39], - brightBlue: [94, 39], - brightMagenta: [95, 39], - brightCyan: [96, 39], - brightWhite: [97, 39], - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - bgGray: [100, 49], - bgGrey: [100, 49], - bgBrightRed: [101, 49], - bgBrightGreen: [102, 49], - bgBrightYellow: [103, 49], - bgBrightBlue: [104, 49], - bgBrightMagenta: [105, 49], - bgBrightCyan: [106, 49], - bgBrightWhite: [107, 49], - // legacy styles for colors pre v1.0.0 - blackBG: [40, 49], - redBG: [41, 49], - greenBG: [42, 49], - yellowBG: [43, 49], - blueBG: [44, 49], - magentaBG: [45, 49], - cyanBG: [46, 49], - whiteBG: [47, 49] - }; - Object.keys(codes).forEach(function(key) { - var val = codes[key]; - var style = styles[key] = []; - style.open = "\x1B[" + val[0] + "m"; - style.close = "\x1B[" + val[1] + "m"; - }); - } -}); - -// node_modules/@colors/colors/lib/system/has-flag.js -var require_has_flag2 = __commonJS({ - "node_modules/@colors/colors/lib/system/has-flag.js"(exports2, module2) { - "use strict"; - module2.exports = function(flag, argv) { - argv = argv || process.argv || []; - var terminatorPos = argv.indexOf("--"); - var prefix = /^-{1,2}/.test(flag) ? "" : "--"; - var pos = argv.indexOf(prefix + flag); - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); - }; - } -}); - -// node_modules/@colors/colors/lib/system/supports-colors.js -var require_supports_colors = __commonJS({ - "node_modules/@colors/colors/lib/system/supports-colors.js"(exports2, module2) { - "use strict"; - var os2 = __require("os"); - var hasFlag = require_has_flag2(); - var env = process.env; - var forceColor = void 0; - if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false")) { - forceColor = false; - } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { - forceColor = true; - } - if ("FORCE_COLOR" in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; - } - function translateLevel(level) { - if (level === 0) { - return false; - } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; - } - function supportsColor(stream4) { - if (forceColor === false) { - return 0; - } - if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { - return 3; - } - if (hasFlag("color=256")) { - return 2; - } - if (stream4 && !stream4.isTTY && forceColor !== true) { - return 0; - } - var min = forceColor ? 1 : 0; - if (process.platform === "win32") { - var osRelease = os2.release().split("."); - if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - return 1; - } - if ("CI" in env) { - if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign2) { - return sign2 in env; - }) || env.CI_NAME === "codeship") { - return 1; - } - return min; - } - if ("TEAMCITY_VERSION" in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - if ("TERM_PROGRAM" in env) { - var version4 = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); - switch (env.TERM_PROGRAM) { - case "iTerm.app": - return version4 >= 3 ? 3 : 2; - case "Hyper": - return 3; - case "Apple_Terminal": - return 2; - } - } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - if ("COLORTERM" in env) { - return 1; - } - if (env.TERM === "dumb") { - return min; - } - return min; - } - function getSupportLevel(stream4) { - var level = supportsColor(stream4); - return translateLevel(level); - } - module2.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) - }; - } -}); - -// node_modules/@colors/colors/lib/custom/trap.js -var require_trap = __commonJS({ - "node_modules/@colors/colors/lib/custom/trap.js"(exports2, module2) { - module2["exports"] = function runTheTrap(text, options) { - var result = ""; - text = text || "Run the trap, drop the bass"; - text = text.split(""); - var trap = { - a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"], - b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"], - c: ["\xA9", "\u023B", "\u03FE"], - d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"], - e: [ - "\xCB", - "\u0115", - "\u018E", - "\u0258", - "\u03A3", - "\u03BE", - "\u04BC", - "\u0A6C" - ], - f: ["\u04FA"], - g: ["\u0262"], - h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"], - i: ["\u0F0F"], - j: ["\u0134"], - k: ["\u0138", "\u04A0", "\u04C3", "\u051E"], - l: ["\u0139"], - m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"], - n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"], - o: [ - "\xD8", - "\xF5", - "\xF8", - "\u01FE", - "\u0298", - "\u047A", - "\u05DD", - "\u06DD", - "\u0E4F" - ], - p: ["\u01F7", "\u048E"], - q: ["\u09CD"], - r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"], - s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"], - t: ["\u0141", "\u0166", "\u0373"], - u: ["\u01B1", "\u054D"], - v: ["\u05D8"], - w: ["\u0428", "\u0460", "\u047C", "\u0D70"], - x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"], - y: ["\xA5", "\u04B0", "\u04CB"], - z: ["\u01B5", "\u0240"] - }; - text.forEach(function(c) { - c = c.toLowerCase(); - var chars = trap[c] || [" "]; - var rand = Math.floor(Math.random() * chars.length); - if (typeof trap[c] !== "undefined") { - result += trap[c][rand]; - } else { - result += c; - } - }); - return result; - }; - } -}); - -// node_modules/@colors/colors/lib/custom/zalgo.js -var require_zalgo = __commonJS({ - "node_modules/@colors/colors/lib/custom/zalgo.js"(exports2, module2) { - module2["exports"] = function zalgo(text, options) { - text = text || " he is here "; - var soul = { - "up": [ - "\u030D", - "\u030E", - "\u0304", - "\u0305", - "\u033F", - "\u0311", - "\u0306", - "\u0310", - "\u0352", - "\u0357", - "\u0351", - "\u0307", - "\u0308", - "\u030A", - "\u0342", - "\u0313", - "\u0308", - "\u034A", - "\u034B", - "\u034C", - "\u0303", - "\u0302", - "\u030C", - "\u0350", - "\u0300", - "\u0301", - "\u030B", - "\u030F", - "\u0312", - "\u0313", - "\u0314", - "\u033D", - "\u0309", - "\u0363", - "\u0364", - "\u0365", - "\u0366", - "\u0367", - "\u0368", - "\u0369", - "\u036A", - "\u036B", - "\u036C", - "\u036D", - "\u036E", - "\u036F", - "\u033E", - "\u035B", - "\u0346", - "\u031A" - ], - "down": [ - "\u0316", - "\u0317", - "\u0318", - "\u0319", - "\u031C", - "\u031D", - "\u031E", - "\u031F", - "\u0320", - "\u0324", - "\u0325", - "\u0326", - "\u0329", - "\u032A", - "\u032B", - "\u032C", - "\u032D", - "\u032E", - "\u032F", - "\u0330", - "\u0331", - "\u0332", - "\u0333", - "\u0339", - "\u033A", - "\u033B", - "\u033C", - "\u0345", - "\u0347", - "\u0348", - "\u0349", - "\u034D", - "\u034E", - "\u0353", - "\u0354", - "\u0355", - "\u0356", - "\u0359", - "\u035A", - "\u0323" - ], - "mid": [ - "\u0315", - "\u031B", - "\u0300", - "\u0301", - "\u0358", - "\u0321", - "\u0322", - "\u0327", - "\u0328", - "\u0334", - "\u0335", - "\u0336", - "\u035C", - "\u035D", - "\u035E", - "\u035F", - "\u0360", - "\u0362", - "\u0338", - "\u0337", - "\u0361", - " \u0489" - ] - }; - var all3 = [].concat(soul.up, soul.down, soul.mid); - function randomNumber(range) { - var r = Math.floor(Math.random() * range); - return r; - } - function isChar(character) { - var bool = false; - all3.filter(function(i) { - bool = i === character; - }); - return bool; - } - function heComes(text2, options2) { - var result = ""; - var counts; - var l; - options2 = options2 || {}; - options2["up"] = typeof options2["up"] !== "undefined" ? options2["up"] : true; - options2["mid"] = typeof options2["mid"] !== "undefined" ? options2["mid"] : true; - options2["down"] = typeof options2["down"] !== "undefined" ? options2["down"] : true; - options2["size"] = typeof options2["size"] !== "undefined" ? options2["size"] : "maxi"; - text2 = text2.split(""); - for (l in text2) { - if (isChar(l)) { - continue; - } - result = result + text2[l]; - counts = { "up": 0, "down": 0, "mid": 0 }; - switch (options2.size) { - case "mini": - counts.up = randomNumber(8); - counts.mid = randomNumber(2); - counts.down = randomNumber(8); - break; - case "maxi": - counts.up = randomNumber(16) + 3; - counts.mid = randomNumber(4) + 1; - counts.down = randomNumber(64) + 3; - break; - default: - counts.up = randomNumber(8) + 1; - counts.mid = randomNumber(6) / 2; - counts.down = randomNumber(8) + 1; - break; - } - var arr = ["up", "mid", "down"]; - for (var d in arr) { - var index2 = arr[d]; - for (var i = 0; i <= counts[index2]; i++) { - if (options2[index2]) { - result = result + soul[index2][randomNumber(soul[index2].length)]; - } - } - } - } - return result; - } - return heComes(text, options); - }; - } -}); - -// node_modules/@colors/colors/lib/maps/america.js -var require_america = __commonJS({ - "node_modules/@colors/colors/lib/maps/america.js"(exports2, module2) { - module2["exports"] = function(colors) { - return function(letter, i, exploded) { - if (letter === " ") return letter; - switch (i % 3) { - case 0: - return colors.red(letter); - case 1: - return colors.white(letter); - case 2: - return colors.blue(letter); - } - }; - }; - } -}); - -// node_modules/@colors/colors/lib/maps/zebra.js -var require_zebra = __commonJS({ - "node_modules/@colors/colors/lib/maps/zebra.js"(exports2, module2) { - module2["exports"] = function(colors) { - return function(letter, i, exploded) { - return i % 2 === 0 ? letter : colors.inverse(letter); - }; - }; - } -}); - -// node_modules/@colors/colors/lib/maps/rainbow.js -var require_rainbow = __commonJS({ - "node_modules/@colors/colors/lib/maps/rainbow.js"(exports2, module2) { - module2["exports"] = function(colors) { - var rainbowColors = ["red", "yellow", "green", "blue", "magenta"]; - return function(letter, i, exploded) { - if (letter === " ") { - return letter; - } else { - return colors[rainbowColors[i++ % rainbowColors.length]](letter); - } - }; - }; - } -}); - -// node_modules/@colors/colors/lib/maps/random.js -var require_random = __commonJS({ - "node_modules/@colors/colors/lib/maps/random.js"(exports2, module2) { - module2["exports"] = function(colors) { - var available = [ - "underline", - "inverse", - "grey", - "yellow", - "red", - "green", - "blue", - "white", - "cyan", - "magenta", - "brightYellow", - "brightRed", - "brightGreen", - "brightBlue", - "brightWhite", - "brightCyan", - "brightMagenta" - ]; - return function(letter, i, exploded) { - return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 2))]](letter); - }; - }; - } -}); - -// node_modules/@colors/colors/lib/colors.js -var require_colors = __commonJS({ - "node_modules/@colors/colors/lib/colors.js"(exports2, module2) { - var colors = {}; - module2["exports"] = colors; - colors.themes = {}; - var util3 = __require("util"); - var ansiStyles = colors.styles = require_styles(); - var defineProps = Object.defineProperties; - var newLineRegex = new RegExp(/[\r\n]+/g); - colors.supportsColor = require_supports_colors().supportsColor; - if (typeof colors.enabled === "undefined") { - colors.enabled = colors.supportsColor() !== false; - } - colors.enable = function() { - colors.enabled = true; - }; - colors.disable = function() { - colors.enabled = false; - }; - colors.stripColors = colors.strip = function(str) { - return ("" + str).replace(/\x1B\[\d+m/g, ""); - }; - var stylize = colors.stylize = function stylize2(str, style) { - if (!colors.enabled) { - return str + ""; - } - var styleMap = ansiStyles[style]; - if (!styleMap && style in colors) { - return colors[style](str); - } - return styleMap.open + str + styleMap.close; - }; - var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; - var escapeStringRegexp = function(str) { - if (typeof str !== "string") { - throw new TypeError("Expected a string"); - } - return str.replace(matchOperatorsRe, "\\$&"); - }; - function build(_styles) { - var builder = function builder2() { - return applyStyle.apply(builder2, arguments); - }; - builder._styles = _styles; - builder.__proto__ = proto; - return builder; - } - var styles = function() { - var ret = {}; - ansiStyles.grey = ansiStyles.gray; - Object.keys(ansiStyles).forEach(function(key) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), "g"); - ret[key] = { - get: function() { - return build(this._styles.concat(key)); - } - }; - }); - return ret; - }(); - var proto = defineProps(function colors2() { - }, styles); - function applyStyle() { - var args = Array.prototype.slice.call(arguments); - var str = args.map(function(arg) { - if (arg != null && arg.constructor === String) { - return arg; - } else { - return util3.inspect(arg); - } - }).join(" "); - if (!colors.enabled || !str) { - return str; - } - var newLinesPresent = str.indexOf("\n") != -1; - var nestedStyles = this._styles; - var i = nestedStyles.length; - while (i--) { - var code = ansiStyles[nestedStyles[i]]; - str = code.open + str.replace(code.closeRe, code.open) + code.close; - if (newLinesPresent) { - str = str.replace(newLineRegex, function(match) { - return code.close + match + code.open; - }); - } - } - return str; - } - colors.setTheme = function(theme) { - if (typeof theme === "string") { - console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));"); - return; - } - for (var style in theme) { - (function(style2) { - colors[style2] = function(str) { - if (typeof theme[style2] === "object") { - var out = str; - for (var i in theme[style2]) { - out = colors[theme[style2][i]](out); - } - return out; - } - return colors[theme[style2]](str); - }; - })(style); - } - }; - function init() { - var ret = {}; - Object.keys(styles).forEach(function(name) { - ret[name] = { - get: function() { - return build([name]); - } - }; - }); - return ret; - } - var sequencer = function sequencer2(map2, str) { - var exploded = str.split(""); - exploded = exploded.map(map2); - return exploded.join(""); - }; - colors.trap = require_trap(); - colors.zalgo = require_zalgo(); - colors.maps = {}; - colors.maps.america = require_america()(colors); - colors.maps.zebra = require_zebra()(colors); - colors.maps.rainbow = require_rainbow()(colors); - colors.maps.random = require_random()(colors); - for (map in colors.maps) { - (function(map2) { - colors[map2] = function(str) { - return sequencer(colors.maps[map2], str); - }; - })(map); - } - var map; - defineProps(colors, init()); - } -}); - -// node_modules/@colors/colors/safe.js -var require_safe = __commonJS({ - "node_modules/@colors/colors/safe.js"(exports2, module2) { - var colors = require_colors(); - module2["exports"] = colors; - } -}); - -// node_modules/triple-beam/config/cli.js -var require_cli = __commonJS({ - "node_modules/triple-beam/config/cli.js"(exports2) { - "use strict"; - exports2.levels = { - error: 0, - warn: 1, - help: 2, - data: 3, - info: 4, - debug: 5, - prompt: 6, - verbose: 7, - input: 8, - silly: 9 - }; - exports2.colors = { - error: "red", - warn: "yellow", - help: "cyan", - data: "grey", - info: "green", - debug: "blue", - prompt: "grey", - verbose: "cyan", - input: "grey", - silly: "magenta" - }; - } -}); - -// node_modules/triple-beam/config/npm.js -var require_npm = __commonJS({ - "node_modules/triple-beam/config/npm.js"(exports2) { - "use strict"; - exports2.levels = { - error: 0, - warn: 1, - info: 2, - http: 3, - verbose: 4, - debug: 5, - silly: 6 - }; - exports2.colors = { - error: "red", - warn: "yellow", - info: "green", - http: "green", - verbose: "cyan", - debug: "blue", - silly: "magenta" - }; - } -}); - -// node_modules/triple-beam/config/syslog.js -var require_syslog = __commonJS({ - "node_modules/triple-beam/config/syslog.js"(exports2) { - "use strict"; - exports2.levels = { - emerg: 0, - alert: 1, - crit: 2, - error: 3, - warning: 4, - notice: 5, - info: 6, - debug: 7 - }; - exports2.colors = { - emerg: "red", - alert: "yellow", - crit: "red", - error: "red", - warning: "red", - notice: "yellow", - info: "green", - debug: "blue" - }; - } -}); - -// node_modules/triple-beam/config/index.js -var require_config = __commonJS({ - "node_modules/triple-beam/config/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "cli", { - value: require_cli() - }); - Object.defineProperty(exports2, "npm", { - value: require_npm() - }); - Object.defineProperty(exports2, "syslog", { - value: require_syslog() - }); - } -}); - -// node_modules/triple-beam/index.js -var require_triple_beam = __commonJS({ - "node_modules/triple-beam/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "LEVEL", { - value: Symbol.for("level") - }); - Object.defineProperty(exports2, "MESSAGE", { - value: Symbol.for("message") - }); - Object.defineProperty(exports2, "SPLAT", { - value: Symbol.for("splat") - }); - Object.defineProperty(exports2, "configs", { - value: require_config() - }); - } -}); - -// node_modules/logform/colorize.js -var require_colorize = __commonJS({ - "node_modules/logform/colorize.js"(exports2, module2) { - "use strict"; - var colors = require_safe(); - var { LEVEL, MESSAGE } = require_triple_beam(); - colors.enabled = true; - var hasSpace = /\s+/; - var Colorizer = class _Colorizer { - constructor(opts = {}) { - if (opts.colors) { - this.addColors(opts.colors); - } - this.options = opts; - } - /* - * Adds the colors Object to the set of allColors - * known by the Colorizer - * - * @param {Object} colors Set of color mappings to add. - */ - static addColors(clrs) { - const nextColors = Object.keys(clrs).reduce((acc, level) => { - acc[level] = hasSpace.test(clrs[level]) ? clrs[level].split(hasSpace) : clrs[level]; - return acc; - }, {}); - _Colorizer.allColors = Object.assign({}, _Colorizer.allColors || {}, nextColors); - return _Colorizer.allColors; - } - /* - * Adds the colors Object to the set of allColors - * known by the Colorizer - * - * @param {Object} colors Set of color mappings to add. - */ - addColors(clrs) { - return _Colorizer.addColors(clrs); - } - /* - * function colorize (lookup, level, message) - * Performs multi-step colorization using @colors/colors/safe - */ - colorize(lookup, level, message) { - if (typeof message === "undefined") { - message = level; - } - if (!Array.isArray(_Colorizer.allColors[lookup])) { - return colors[_Colorizer.allColors[lookup]](message); - } - for (let i = 0, len = _Colorizer.allColors[lookup].length; i < len; i++) { - message = colors[_Colorizer.allColors[lookup][i]](message); - } - return message; - } - /* - * function transform (info, opts) - * Attempts to colorize the { level, message } of the given - * `logform` info object. - */ - transform(info, opts) { - if (opts.all && typeof info[MESSAGE] === "string") { - info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]); - } - if (opts.level || opts.all || !opts.message) { - info.level = this.colorize(info[LEVEL], info.level); - } - if (opts.all || opts.message) { - info.message = this.colorize(info[LEVEL], info.level, info.message); - } - return info; - } - }; - module2.exports = (opts) => new Colorizer(opts); - module2.exports.Colorizer = module2.exports.Format = Colorizer; - } -}); - -// node_modules/logform/levels.js -var require_levels = __commonJS({ - "node_modules/logform/levels.js"(exports2, module2) { - "use strict"; - var { Colorizer } = require_colorize(); - module2.exports = (config3) => { - Colorizer.addColors(config3.colors || config3); - return config3; - }; - } -}); - -// node_modules/logform/align.js -var require_align = __commonJS({ - "node_modules/logform/align.js"(exports2, module2) { - "use strict"; - var format = require_format(); - module2.exports = format((info) => { - info.message = ` ${info.message}`; - return info; - }); - } -}); - -// node_modules/logform/errors.js -var require_errors = __commonJS({ - "node_modules/logform/errors.js"(exports2, module2) { - "use strict"; - var format = require_format(); - var { LEVEL, MESSAGE } = require_triple_beam(); - module2.exports = format((einfo, { stack, cause }) => { - if (einfo instanceof Error) { - const info = Object.assign({}, einfo, { - level: einfo.level, - [LEVEL]: einfo[LEVEL] || einfo.level, - message: einfo.message, - [MESSAGE]: einfo[MESSAGE] || einfo.message - }); - if (stack) info.stack = einfo.stack; - if (cause) info.cause = einfo.cause; - return info; - } - if (!(einfo.message instanceof Error)) return einfo; - const err = einfo.message; - Object.assign(einfo, err); - einfo.message = err.message; - einfo[MESSAGE] = err.message; - if (stack) einfo.stack = err.stack; - if (cause) einfo.cause = err.cause; - return einfo; - }); - } -}); - -// node_modules/logform/pad-levels.js -var require_pad_levels = __commonJS({ - "node_modules/logform/pad-levels.js"(exports2, module2) { - "use strict"; - var { configs, LEVEL, MESSAGE } = require_triple_beam(); - var Padder = class _Padder { - constructor(opts = { levels: configs.npm.levels }) { - this.paddings = _Padder.paddingForLevels(opts.levels, opts.filler); - this.options = opts; - } - /** - * Returns the maximum length of keys in the specified `levels` Object. - * @param {Object} levels Set of all levels to calculate longest level against. - * @returns {Number} Maximum length of the longest level string. - */ - static getLongestLevel(levels) { - const lvls = Object.keys(levels).map((level) => level.length); - return Math.max(...lvls); - } - /** - * Returns the padding for the specified `level` assuming that the - * maximum length of all levels it's associated with is `maxLength`. - * @param {String} level Level to calculate padding for. - * @param {String} filler Repeatable text to use for padding. - * @param {Number} maxLength Length of the longest level - * @returns {String} Padding string for the `level` - */ - static paddingForLevel(level, filler, maxLength) { - const targetLen = maxLength + 1 - level.length; - const rep = Math.floor(targetLen / filler.length); - const padding = `${filler}${filler.repeat(rep)}`; - return padding.slice(0, targetLen); - } - /** - * Returns an object with the string paddings for the given `levels` - * using the specified `filler`. - * @param {Object} levels Set of all levels to calculate padding for. - * @param {String} filler Repeatable text to use for padding. - * @returns {Object} Mapping of level to desired padding. - */ - static paddingForLevels(levels, filler = " ") { - const maxLength = _Padder.getLongestLevel(levels); - return Object.keys(levels).reduce((acc, level) => { - acc[level] = _Padder.paddingForLevel(level, filler, maxLength); - return acc; - }, {}); - } - /** - * Prepends the padding onto the `message` based on the `LEVEL` of - * the `info`. This is based on the behavior of `winston@2` which also - * prepended the level onto the message. - * - * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201 - * - * @param {Info} info Logform info object - * @param {Object} opts Options passed along to this instance. - * @returns {Info} Modified logform info object. - */ - transform(info, opts) { - info.message = `${this.paddings[info[LEVEL]]}${info.message}`; - if (info[MESSAGE]) { - info[MESSAGE] = `${this.paddings[info[LEVEL]]}${info[MESSAGE]}`; - } - return info; - } - }; - module2.exports = (opts) => new Padder(opts); - module2.exports.Padder = module2.exports.Format = Padder; - } -}); - -// node_modules/logform/cli.js -var require_cli2 = __commonJS({ - "node_modules/logform/cli.js"(exports2, module2) { - "use strict"; - var { Colorizer } = require_colorize(); - var { Padder } = require_pad_levels(); - var { configs, MESSAGE } = require_triple_beam(); - var CliFormat = class { - constructor(opts = {}) { - if (!opts.levels) { - opts.levels = configs.cli.levels; - } - this.colorizer = new Colorizer(opts); - this.padder = new Padder(opts); - this.options = opts; - } - /* - * function transform (info, opts) - * Attempts to both: - * 1. Pad the { level } - * 2. Colorize the { level, message } - * of the given `logform` info object depending on the `opts`. - */ - transform(info, opts) { - this.colorizer.transform( - this.padder.transform(info, opts), - opts - ); - info[MESSAGE] = `${info.level}:${info.message}`; - return info; - } - }; - module2.exports = (opts) => new CliFormat(opts); - module2.exports.Format = CliFormat; - } -}); - -// node_modules/logform/combine.js -var require_combine = __commonJS({ - "node_modules/logform/combine.js"(exports2, module2) { - "use strict"; - var format = require_format(); - function cascade(formats) { - if (!formats.every(isValidFormat)) { - return; - } - return (info) => { - let obj = info; - for (let i = 0; i < formats.length; i++) { - obj = formats[i].transform(obj, formats[i].options); - if (!obj) { - return false; - } - } - return obj; - }; - } - function isValidFormat(fmt) { - if (typeof fmt.transform !== "function") { - throw new Error([ - "No transform function found on format. Did you create a format instance?", - "const myFormat = format(formatFn);", - "const instance = myFormat();" - ].join("\n")); - } - return true; - } - module2.exports = (...formats) => { - const combinedFormat = format(cascade(formats)); - const instance = combinedFormat(); - instance.Format = combinedFormat.Format; - return instance; - }; - module2.exports.cascade = cascade; - } -}); - -// node_modules/safe-stable-stringify/index.js -var require_safe_stable_stringify = __commonJS({ - "node_modules/safe-stable-stringify/index.js"(exports2, module2) { - "use strict"; - var { hasOwnProperty: hasOwnProperty2 } = Object.prototype; - var stringify3 = configure(); - stringify3.configure = configure; - stringify3.stringify = stringify3; - stringify3.default = stringify3; - exports2.stringify = stringify3; - exports2.configure = configure; - module2.exports = stringify3; - var strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/; - function strEscape(str) { - if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) { - return `"${str}"`; - } - return JSON.stringify(str); - } - function sort(array, comparator) { - if (array.length > 200 || comparator) { - return array.sort(comparator); - } - for (let i = 1; i < array.length; i++) { - const currentValue = array[i]; - let position = i; - while (position !== 0 && array[position - 1] > currentValue) { - array[position] = array[position - 1]; - position--; - } - array[position] = currentValue; - } - return array; - } - var typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor( - Object.getPrototypeOf( - Object.getPrototypeOf( - new Int8Array() - ) - ), - Symbol.toStringTag - ).get; - function isTypedArrayWithEntries(value) { - return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0; - } - function stringifyTypedArray(array, separator, maximumBreadth) { - if (array.length < maximumBreadth) { - maximumBreadth = array.length; - } - const whitespace = separator === "," ? "" : " "; - let res = `"0":${whitespace}${array[0]}`; - for (let i = 1; i < maximumBreadth; i++) { - res += `${separator}"${i}":${whitespace}${array[i]}`; - } - return res; - } - function getCircularValueOption(options) { - if (hasOwnProperty2.call(options, "circularValue")) { - const circularValue = options.circularValue; - if (typeof circularValue === "string") { - return `"${circularValue}"`; - } - if (circularValue == null) { - return circularValue; - } - if (circularValue === Error || circularValue === TypeError) { - return { - toString() { - throw new TypeError("Converting circular structure to JSON"); - } - }; - } - throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined'); - } - return '"[Circular]"'; - } - function getDeterministicOption(options) { - let value; - if (hasOwnProperty2.call(options, "deterministic")) { - value = options.deterministic; - if (typeof value !== "boolean" && typeof value !== "function") { - throw new TypeError('The "deterministic" argument must be of type boolean or comparator function'); - } - } - return value === void 0 ? true : value; - } - function getBooleanOption(options, key) { - let value; - if (hasOwnProperty2.call(options, key)) { - value = options[key]; - if (typeof value !== "boolean") { - throw new TypeError(`The "${key}" argument must be of type boolean`); - } - } - return value === void 0 ? true : value; - } - function getPositiveIntegerOption(options, key) { - let value; - if (hasOwnProperty2.call(options, key)) { - value = options[key]; - if (typeof value !== "number") { - throw new TypeError(`The "${key}" argument must be of type number`); - } - if (!Number.isInteger(value)) { - throw new TypeError(`The "${key}" argument must be an integer`); - } - if (value < 1) { - throw new RangeError(`The "${key}" argument must be >= 1`); - } - } - return value === void 0 ? Infinity : value; - } - function getItemCount(number) { - if (number === 1) { - return "1 item"; - } - return `${number} items`; - } - function getUniqueReplacerSet(replacerArray) { - const replacerSet = /* @__PURE__ */ new Set(); - for (const value of replacerArray) { - if (typeof value === "string" || typeof value === "number") { - replacerSet.add(String(value)); - } - } - return replacerSet; - } - function getStrictOption(options) { - if (hasOwnProperty2.call(options, "strict")) { - const value = options.strict; - if (typeof value !== "boolean") { - throw new TypeError('The "strict" argument must be of type boolean'); - } - if (value) { - return (value2) => { - let message = `Object can not safely be stringified. Received type ${typeof value2}`; - if (typeof value2 !== "function") message += ` (${value2.toString()})`; - throw new Error(message); - }; - } - } - } - function configure(options) { - options = { ...options }; - const fail = getStrictOption(options); - if (fail) { - if (options.bigint === void 0) { - options.bigint = false; - } - if (!("circularValue" in options)) { - options.circularValue = Error; - } - } - const circularValue = getCircularValueOption(options); - const bigint = getBooleanOption(options, "bigint"); - const deterministic = getDeterministicOption(options); - const comparator = typeof deterministic === "function" ? deterministic : void 0; - const maximumDepth = getPositiveIntegerOption(options, "maximumDepth"); - const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth"); - function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) { - let value = parent[key]; - if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { - value = value.toJSON(key); - } - value = replacer.call(parent, key, value); - switch (typeof value) { - case "string": - return strEscape(value); - case "object": { - if (value === null) { - return "null"; - } - if (stack.indexOf(value) !== -1) { - return circularValue; - } - let res = ""; - let join2 = ","; - const originalIndentation = indentation; - if (Array.isArray(value)) { - if (value.length === 0) { - return "[]"; - } - if (maximumDepth < stack.length + 1) { - return '"[Array]"'; - } - stack.push(value); - if (spacer !== "") { - indentation += spacer; - res += ` -${indentation}`; - join2 = `, -${indentation}`; - } - const maximumValuesToStringify = Math.min(value.length, maximumBreadth); - let i = 0; - for (; i < maximumValuesToStringify - 1; i++) { - const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); - res += tmp2 !== void 0 ? tmp2 : "null"; - res += join2; - } - const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); - res += tmp !== void 0 ? tmp : "null"; - if (value.length - 1 > maximumBreadth) { - const removedKeys = value.length - maximumBreadth - 1; - res += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; - } - if (spacer !== "") { - res += ` -${originalIndentation}`; - } - stack.pop(); - return `[${res}]`; - } - let keys = Object.keys(value); - const keyLength = keys.length; - if (keyLength === 0) { - return "{}"; - } - if (maximumDepth < stack.length + 1) { - return '"[Object]"'; - } - let whitespace = ""; - let separator = ""; - if (spacer !== "") { - indentation += spacer; - join2 = `, -${indentation}`; - whitespace = " "; - } - const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); - if (deterministic && !isTypedArrayWithEntries(value)) { - keys = sort(keys, comparator); - } - stack.push(value); - for (let i = 0; i < maximumPropertiesToStringify; i++) { - const key2 = keys[i]; - const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation); - if (tmp !== void 0) { - res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; - separator = join2; - } - } - if (keyLength > maximumBreadth) { - const removedKeys = keyLength - maximumBreadth; - res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`; - separator = join2; - } - if (spacer !== "" && separator.length > 1) { - res = ` -${indentation}${res} -${originalIndentation}`; - } - stack.pop(); - return `{${res}}`; - } - case "number": - return isFinite(value) ? String(value) : fail ? fail(value) : "null"; - case "boolean": - return value === true ? "true" : "false"; - case "undefined": - return void 0; - case "bigint": - if (bigint) { - return String(value); - } - // fallthrough - default: - return fail ? fail(value) : void 0; - } - } - function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) { - if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { - value = value.toJSON(key); - } - switch (typeof value) { - case "string": - return strEscape(value); - case "object": { - if (value === null) { - return "null"; - } - if (stack.indexOf(value) !== -1) { - return circularValue; - } - const originalIndentation = indentation; - let res = ""; - let join2 = ","; - if (Array.isArray(value)) { - if (value.length === 0) { - return "[]"; - } - if (maximumDepth < stack.length + 1) { - return '"[Array]"'; - } - stack.push(value); - if (spacer !== "") { - indentation += spacer; - res += ` -${indentation}`; - join2 = `, -${indentation}`; - } - const maximumValuesToStringify = Math.min(value.length, maximumBreadth); - let i = 0; - for (; i < maximumValuesToStringify - 1; i++) { - const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); - res += tmp2 !== void 0 ? tmp2 : "null"; - res += join2; - } - const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); - res += tmp !== void 0 ? tmp : "null"; - if (value.length - 1 > maximumBreadth) { - const removedKeys = value.length - maximumBreadth - 1; - res += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; - } - if (spacer !== "") { - res += ` -${originalIndentation}`; - } - stack.pop(); - return `[${res}]`; - } - stack.push(value); - let whitespace = ""; - if (spacer !== "") { - indentation += spacer; - join2 = `, -${indentation}`; - whitespace = " "; - } - let separator = ""; - for (const key2 of replacer) { - const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation); - if (tmp !== void 0) { - res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; - separator = join2; - } - } - if (spacer !== "" && separator.length > 1) { - res = ` -${indentation}${res} -${originalIndentation}`; - } - stack.pop(); - return `{${res}}`; - } - case "number": - return isFinite(value) ? String(value) : fail ? fail(value) : "null"; - case "boolean": - return value === true ? "true" : "false"; - case "undefined": - return void 0; - case "bigint": - if (bigint) { - return String(value); - } - // fallthrough - default: - return fail ? fail(value) : void 0; - } - } - function stringifyIndent(key, value, stack, spacer, indentation) { - switch (typeof value) { - case "string": - return strEscape(value); - case "object": { - if (value === null) { - return "null"; - } - if (typeof value.toJSON === "function") { - value = value.toJSON(key); - if (typeof value !== "object") { - return stringifyIndent(key, value, stack, spacer, indentation); - } - if (value === null) { - return "null"; - } - } - if (stack.indexOf(value) !== -1) { - return circularValue; - } - const originalIndentation = indentation; - if (Array.isArray(value)) { - if (value.length === 0) { - return "[]"; - } - if (maximumDepth < stack.length + 1) { - return '"[Array]"'; - } - stack.push(value); - indentation += spacer; - let res2 = ` -${indentation}`; - const join3 = `, -${indentation}`; - const maximumValuesToStringify = Math.min(value.length, maximumBreadth); - let i = 0; - for (; i < maximumValuesToStringify - 1; i++) { - const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation); - res2 += tmp2 !== void 0 ? tmp2 : "null"; - res2 += join3; - } - const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation); - res2 += tmp !== void 0 ? tmp : "null"; - if (value.length - 1 > maximumBreadth) { - const removedKeys = value.length - maximumBreadth - 1; - res2 += `${join3}"... ${getItemCount(removedKeys)} not stringified"`; - } - res2 += ` -${originalIndentation}`; - stack.pop(); - return `[${res2}]`; - } - let keys = Object.keys(value); - const keyLength = keys.length; - if (keyLength === 0) { - return "{}"; - } - if (maximumDepth < stack.length + 1) { - return '"[Object]"'; - } - indentation += spacer; - const join2 = `, -${indentation}`; - let res = ""; - let separator = ""; - let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); - if (isTypedArrayWithEntries(value)) { - res += stringifyTypedArray(value, join2, maximumBreadth); - keys = keys.slice(value.length); - maximumPropertiesToStringify -= value.length; - separator = join2; - } - if (deterministic) { - keys = sort(keys, comparator); - } - stack.push(value); - for (let i = 0; i < maximumPropertiesToStringify; i++) { - const key2 = keys[i]; - const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation); - if (tmp !== void 0) { - res += `${separator}${strEscape(key2)}: ${tmp}`; - separator = join2; - } - } - if (keyLength > maximumBreadth) { - const removedKeys = keyLength - maximumBreadth; - res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`; - separator = join2; - } - if (separator !== "") { - res = ` -${indentation}${res} -${originalIndentation}`; - } - stack.pop(); - return `{${res}}`; - } - case "number": - return isFinite(value) ? String(value) : fail ? fail(value) : "null"; - case "boolean": - return value === true ? "true" : "false"; - case "undefined": - return void 0; - case "bigint": - if (bigint) { - return String(value); - } - // fallthrough - default: - return fail ? fail(value) : void 0; - } - } - function stringifySimple(key, value, stack) { - switch (typeof value) { - case "string": - return strEscape(value); - case "object": { - if (value === null) { - return "null"; - } - if (typeof value.toJSON === "function") { - value = value.toJSON(key); - if (typeof value !== "object") { - return stringifySimple(key, value, stack); - } - if (value === null) { - return "null"; - } - } - if (stack.indexOf(value) !== -1) { - return circularValue; - } - let res = ""; - const hasLength = value.length !== void 0; - if (hasLength && Array.isArray(value)) { - if (value.length === 0) { - return "[]"; - } - if (maximumDepth < stack.length + 1) { - return '"[Array]"'; - } - stack.push(value); - const maximumValuesToStringify = Math.min(value.length, maximumBreadth); - let i = 0; - for (; i < maximumValuesToStringify - 1; i++) { - const tmp2 = stringifySimple(String(i), value[i], stack); - res += tmp2 !== void 0 ? tmp2 : "null"; - res += ","; - } - const tmp = stringifySimple(String(i), value[i], stack); - res += tmp !== void 0 ? tmp : "null"; - if (value.length - 1 > maximumBreadth) { - const removedKeys = value.length - maximumBreadth - 1; - res += `,"... ${getItemCount(removedKeys)} not stringified"`; - } - stack.pop(); - return `[${res}]`; - } - let keys = Object.keys(value); - const keyLength = keys.length; - if (keyLength === 0) { - return "{}"; - } - if (maximumDepth < stack.length + 1) { - return '"[Object]"'; - } - let separator = ""; - let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); - if (hasLength && isTypedArrayWithEntries(value)) { - res += stringifyTypedArray(value, ",", maximumBreadth); - keys = keys.slice(value.length); - maximumPropertiesToStringify -= value.length; - separator = ","; - } - if (deterministic) { - keys = sort(keys, comparator); - } - stack.push(value); - for (let i = 0; i < maximumPropertiesToStringify; i++) { - const key2 = keys[i]; - const tmp = stringifySimple(key2, value[key2], stack); - if (tmp !== void 0) { - res += `${separator}${strEscape(key2)}:${tmp}`; - separator = ","; - } - } - if (keyLength > maximumBreadth) { - const removedKeys = keyLength - maximumBreadth; - res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`; - } - stack.pop(); - return `{${res}}`; - } - case "number": - return isFinite(value) ? String(value) : fail ? fail(value) : "null"; - case "boolean": - return value === true ? "true" : "false"; - case "undefined": - return void 0; - case "bigint": - if (bigint) { - return String(value); - } - // fallthrough - default: - return fail ? fail(value) : void 0; - } - } - function stringify4(value, replacer, space) { - if (arguments.length > 1) { - let spacer = ""; - if (typeof space === "number") { - spacer = " ".repeat(Math.min(space, 10)); - } else if (typeof space === "string") { - spacer = space.slice(0, 10); - } - if (replacer != null) { - if (typeof replacer === "function") { - return stringifyFnReplacer("", { "": value }, [], replacer, spacer, ""); - } - if (Array.isArray(replacer)) { - return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, ""); - } - } - if (spacer.length !== 0) { - return stringifyIndent("", value, [], spacer, ""); - } - } - return stringifySimple("", value, []); - } - return stringify4; - } - } -}); - -// node_modules/logform/json.js -var require_json = __commonJS({ - "node_modules/logform/json.js"(exports2, module2) { - "use strict"; - var format = require_format(); - var { MESSAGE } = require_triple_beam(); - var stringify3 = require_safe_stable_stringify(); - function replacer(key, value) { - if (typeof value === "bigint") - return value.toString(); - return value; - } - module2.exports = format((info, opts) => { - const jsonStringify = stringify3.configure(opts); - info[MESSAGE] = jsonStringify(info, opts.replacer || replacer, opts.space); - return info; - }); - } -}); - -// node_modules/logform/label.js -var require_label = __commonJS({ - "node_modules/logform/label.js"(exports2, module2) { - "use strict"; - var format = require_format(); - module2.exports = format((info, opts) => { - if (opts.message) { - info.message = `[${opts.label}] ${info.message}`; - return info; - } - info.label = opts.label; - return info; - }); - } -}); - -// node_modules/logform/logstash.js -var require_logstash = __commonJS({ - "node_modules/logform/logstash.js"(exports2, module2) { - "use strict"; - var format = require_format(); - var { MESSAGE } = require_triple_beam(); - var jsonStringify = require_safe_stable_stringify(); - module2.exports = format((info) => { - const logstash = {}; - if (info.message) { - logstash["@message"] = info.message; - delete info.message; - } - if (info.timestamp) { - logstash["@timestamp"] = info.timestamp; - delete info.timestamp; - } - logstash["@fields"] = info; - info[MESSAGE] = jsonStringify(logstash); - return info; - }); - } -}); - -// node_modules/logform/metadata.js -var require_metadata = __commonJS({ - "node_modules/logform/metadata.js"(exports2, module2) { - "use strict"; - var format = require_format(); - function fillExcept(info, fillExceptKeys, metadataKey) { - const savedKeys = fillExceptKeys.reduce((acc, key) => { - acc[key] = info[key]; - delete info[key]; - return acc; - }, {}); - const metadata = Object.keys(info).reduce((acc, key) => { - acc[key] = info[key]; - delete info[key]; - return acc; - }, {}); - Object.assign(info, savedKeys, { - [metadataKey]: metadata - }); - return info; - } - function fillWith(info, fillWithKeys, metadataKey) { - info[metadataKey] = fillWithKeys.reduce((acc, key) => { - acc[key] = info[key]; - delete info[key]; - return acc; - }, {}); - return info; - } - module2.exports = format((info, opts = {}) => { - let metadataKey = "metadata"; - if (opts.key) { - metadataKey = opts.key; - } - let fillExceptKeys = []; - if (!opts.fillExcept && !opts.fillWith) { - fillExceptKeys.push("level"); - fillExceptKeys.push("message"); - } - if (opts.fillExcept) { - fillExceptKeys = opts.fillExcept; - } - if (fillExceptKeys.length > 0) { - return fillExcept(info, fillExceptKeys, metadataKey); - } - if (opts.fillWith) { - return fillWith(info, opts.fillWith, metadataKey); - } - return info; - }); - } -}); - -// node_modules/logform/ms.js -var require_ms2 = __commonJS({ - "node_modules/logform/ms.js"(exports2, module2) { - "use strict"; - var format = require_format(); - var ms = require_ms(); - module2.exports = format((info) => { - const curr = +/* @__PURE__ */ new Date(); - exports2.diff = curr - (exports2.prevTime || curr); - exports2.prevTime = curr; - info.ms = `+${ms(exports2.diff)}`; - return info; - }); - } -}); - -// node_modules/logform/pretty-print.js -var require_pretty_print = __commonJS({ - "node_modules/logform/pretty-print.js"(exports2, module2) { - "use strict"; - var inspect = __require("util").inspect; - var format = require_format(); - var { LEVEL, MESSAGE, SPLAT } = require_triple_beam(); - module2.exports = format((info, opts = {}) => { - const stripped = Object.assign({}, info); - delete stripped[LEVEL]; - delete stripped[MESSAGE]; - delete stripped[SPLAT]; - info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize); - return info; - }); - } -}); - -// node_modules/logform/printf.js -var require_printf = __commonJS({ - "node_modules/logform/printf.js"(exports2, module2) { - "use strict"; - var { MESSAGE } = require_triple_beam(); - var Printf = class { - constructor(templateFn) { - this.template = templateFn; - } - transform(info) { - info[MESSAGE] = this.template(info); - return info; - } - }; - module2.exports = (opts) => new Printf(opts); - module2.exports.Printf = module2.exports.Format = Printf; - } -}); - -// node_modules/logform/simple.js -var require_simple = __commonJS({ - "node_modules/logform/simple.js"(exports2, module2) { - "use strict"; - var format = require_format(); - var { MESSAGE } = require_triple_beam(); - var jsonStringify = require_safe_stable_stringify(); - module2.exports = format((info) => { - const stringifiedRest = jsonStringify(Object.assign({}, info, { - level: void 0, - message: void 0, - splat: void 0 - })); - const padding = info.padding && info.padding[info.level] || ""; - if (stringifiedRest !== "{}") { - info[MESSAGE] = `${info.level}:${padding} ${info.message} ${stringifiedRest}`; - } else { - info[MESSAGE] = `${info.level}:${padding} ${info.message}`; - } - return info; - }); - } -}); - -// node_modules/logform/splat.js -var require_splat = __commonJS({ - "node_modules/logform/splat.js"(exports2, module2) { - "use strict"; - var util3 = __require("util"); - var { SPLAT } = require_triple_beam(); - var formatRegExp = /%[scdjifoO%]/g; - var escapedPercent = /%%/g; - var Splatter = class { - constructor(opts) { - this.options = opts; - } - /** - * Check to see if tokens <= splat.length, assign { splat, meta } into the - * `info` accordingly, and write to this instance. - * - * @param {Info} info Logform info message. - * @param {String[]} tokens Set of string interpolation tokens. - * @returns {Info} Modified info message - * @private - */ - _splat(info, tokens) { - const msg = info.message; - const splat = info[SPLAT] || info.splat || []; - const percents = msg.match(escapedPercent); - const escapes = percents && percents.length || 0; - const expectedSplat = tokens.length - escapes; - const extraSplat = expectedSplat - splat.length; - const metas = extraSplat < 0 ? splat.splice(extraSplat, -1 * extraSplat) : []; - const metalen = metas.length; - if (metalen) { - for (let i = 0; i < metalen; i++) { - Object.assign(info, metas[i]); - } - } - info.message = util3.format(msg, ...splat); - return info; - } - /** - * Transforms the `info` message by using `util.format` to complete - * any `info.message` provided it has string interpolation tokens. - * If no tokens exist then `info` is immutable. - * - * @param {Info} info Logform info message. - * @param {Object} opts Options for this instance. - * @returns {Info} Modified info message - */ - transform(info) { - const msg = info.message; - const splat = info[SPLAT] || info.splat; - if (!splat || !splat.length) { - return info; - } - const tokens = msg && msg.match && msg.match(formatRegExp); - if (!tokens && (splat || splat.length)) { - const metas = splat.length > 1 ? splat.splice(0) : splat; - const metalen = metas.length; - if (metalen) { - for (let i = 0; i < metalen; i++) { - Object.assign(info, metas[i]); - } - } - return info; - } - if (tokens) { - return this._splat(info, tokens); - } - return info; - } - }; - module2.exports = (opts) => new Splatter(opts); - } -}); - -// node_modules/fecha/lib/fecha.umd.js -var require_fecha_umd = __commonJS({ - "node_modules/fecha/lib/fecha.umd.js"(exports2, module2) { - (function(global2, factory) { - typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : factory(global2.fecha = {}); - })(exports2, function(exports3) { - "use strict"; - var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; - var twoDigitsOptional = "\\d\\d?"; - var twoDigits = "\\d\\d"; - var threeDigits = "\\d{3}"; - var fourDigits = "\\d{4}"; - var word = "[^\\s]+"; - var literal = /\[([^]*?)\]/gm; - function shorten2(arr, sLen) { - var newArr = []; - for (var i = 0, len = arr.length; i < len; i++) { - newArr.push(arr[i].substr(0, sLen)); - } - return newArr; - } - var monthUpdate = function(arrName) { - return function(v, i18n) { - var lowerCaseArr = i18n[arrName].map(function(v2) { - return v2.toLowerCase(); - }); - var index2 = lowerCaseArr.indexOf(v.toLowerCase()); - if (index2 > -1) { - return index2; - } - return null; - }; - }; - function assign(origObj) { - var args = []; - for (var _i2 = 1; _i2 < arguments.length; _i2++) { - args[_i2 - 1] = arguments[_i2]; - } - for (var _a2 = 0, args_1 = args; _a2 < args_1.length; _a2++) { - var obj = args_1[_a2]; - for (var key in obj) { - origObj[key] = obj[key]; - } - } - return origObj; - } - var dayNames = [ - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday" - ]; - var monthNames = [ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December" - ]; - var monthNamesShort = shorten2(monthNames, 3); - var dayNamesShort = shorten2(dayNames, 3); - var defaultI18n = { - dayNamesShort, - dayNames, - monthNamesShort, - monthNames, - amPm: ["am", "pm"], - DoFn: function(dayOfMonth) { - return dayOfMonth + ["th", "st", "nd", "rd"][dayOfMonth % 10 > 3 ? 0 : (dayOfMonth - dayOfMonth % 10 !== 10 ? 1 : 0) * dayOfMonth % 10]; - } - }; - var globalI18n = assign({}, defaultI18n); - var setGlobalDateI18n = function(i18n) { - return globalI18n = assign(globalI18n, i18n); - }; - var regexEscape = function(str) { - return str.replace(/[|\\{()[^$+*?.-]/g, "\\$&"); - }; - var pad4 = function(val, len) { - if (len === void 0) { - len = 2; - } - val = String(val); - while (val.length < len) { - val = "0" + val; - } - return val; - }; - var formatFlags = { - D: function(dateObj) { - return String(dateObj.getDate()); - }, - DD: function(dateObj) { - return pad4(dateObj.getDate()); - }, - Do: function(dateObj, i18n) { - return i18n.DoFn(dateObj.getDate()); - }, - d: function(dateObj) { - return String(dateObj.getDay()); - }, - dd: function(dateObj) { - return pad4(dateObj.getDay()); - }, - ddd: function(dateObj, i18n) { - return i18n.dayNamesShort[dateObj.getDay()]; - }, - dddd: function(dateObj, i18n) { - return i18n.dayNames[dateObj.getDay()]; - }, - M: function(dateObj) { - return String(dateObj.getMonth() + 1); - }, - MM: function(dateObj) { - return pad4(dateObj.getMonth() + 1); - }, - MMM: function(dateObj, i18n) { - return i18n.monthNamesShort[dateObj.getMonth()]; - }, - MMMM: function(dateObj, i18n) { - return i18n.monthNames[dateObj.getMonth()]; - }, - YY: function(dateObj) { - return pad4(String(dateObj.getFullYear()), 4).substr(2); - }, - YYYY: function(dateObj) { - return pad4(dateObj.getFullYear(), 4); - }, - h: function(dateObj) { - return String(dateObj.getHours() % 12 || 12); - }, - hh: function(dateObj) { - return pad4(dateObj.getHours() % 12 || 12); - }, - H: function(dateObj) { - return String(dateObj.getHours()); - }, - HH: function(dateObj) { - return pad4(dateObj.getHours()); - }, - m: function(dateObj) { - return String(dateObj.getMinutes()); - }, - mm: function(dateObj) { - return pad4(dateObj.getMinutes()); - }, - s: function(dateObj) { - return String(dateObj.getSeconds()); - }, - ss: function(dateObj) { - return pad4(dateObj.getSeconds()); - }, - S: function(dateObj) { - return String(Math.round(dateObj.getMilliseconds() / 100)); - }, - SS: function(dateObj) { - return pad4(Math.round(dateObj.getMilliseconds() / 10), 2); - }, - SSS: function(dateObj) { - return pad4(dateObj.getMilliseconds(), 3); - }, - a: function(dateObj, i18n) { - return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1]; - }, - A: function(dateObj, i18n) { - return dateObj.getHours() < 12 ? i18n.amPm[0].toUpperCase() : i18n.amPm[1].toUpperCase(); - }, - ZZ: function(dateObj) { - var offset = dateObj.getTimezoneOffset(); - return (offset > 0 ? "-" : "+") + pad4(Math.floor(Math.abs(offset) / 60) * 100 + Math.abs(offset) % 60, 4); - }, - Z: function(dateObj) { - var offset = dateObj.getTimezoneOffset(); - return (offset > 0 ? "-" : "+") + pad4(Math.floor(Math.abs(offset) / 60), 2) + ":" + pad4(Math.abs(offset) % 60, 2); - } - }; - var monthParse = function(v) { - return +v - 1; - }; - var emptyDigits = [null, twoDigitsOptional]; - var emptyWord = [null, word]; - var amPm = [ - "isPm", - word, - function(v, i18n) { - var val = v.toLowerCase(); - if (val === i18n.amPm[0]) { - return 0; - } else if (val === i18n.amPm[1]) { - return 1; - } - return null; - } - ]; - var timezoneOffset = [ - "timezoneOffset", - "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?", - function(v) { - var parts = (v + "").match(/([+-]|\d\d)/gi); - if (parts) { - var minutes = +parts[1] * 60 + parseInt(parts[2], 10); - return parts[0] === "+" ? minutes : -minutes; - } - return 0; - } - ]; - var parseFlags = { - D: ["day", twoDigitsOptional], - DD: ["day", twoDigits], - Do: ["day", twoDigitsOptional + word, function(v) { - return parseInt(v, 10); - }], - M: ["month", twoDigitsOptional, monthParse], - MM: ["month", twoDigits, monthParse], - YY: [ - "year", - twoDigits, - function(v) { - var now = /* @__PURE__ */ new Date(); - var cent = +("" + now.getFullYear()).substr(0, 2); - return +("" + (+v > 68 ? cent - 1 : cent) + v); - } - ], - h: ["hour", twoDigitsOptional, void 0, "isPm"], - hh: ["hour", twoDigits, void 0, "isPm"], - H: ["hour", twoDigitsOptional], - HH: ["hour", twoDigits], - m: ["minute", twoDigitsOptional], - mm: ["minute", twoDigits], - s: ["second", twoDigitsOptional], - ss: ["second", twoDigits], - YYYY: ["year", fourDigits], - S: ["millisecond", "\\d", function(v) { - return +v * 100; - }], - SS: ["millisecond", twoDigits, function(v) { - return +v * 10; - }], - SSS: ["millisecond", threeDigits], - d: emptyDigits, - dd: emptyDigits, - ddd: emptyWord, - dddd: emptyWord, - MMM: ["month", word, monthUpdate("monthNamesShort")], - MMMM: ["month", word, monthUpdate("monthNames")], - a: amPm, - A: amPm, - ZZ: timezoneOffset, - Z: timezoneOffset - }; - var globalMasks = { - default: "ddd MMM DD YYYY HH:mm:ss", - shortDate: "M/D/YY", - mediumDate: "MMM D, YYYY", - longDate: "MMMM D, YYYY", - fullDate: "dddd, MMMM D, YYYY", - isoDate: "YYYY-MM-DD", - isoDateTime: "YYYY-MM-DDTHH:mm:ssZ", - shortTime: "HH:mm", - mediumTime: "HH:mm:ss", - longTime: "HH:mm:ss.SSS" - }; - var setGlobalDateMasks = function(masks) { - return assign(globalMasks, masks); - }; - var format = function(dateObj, mask, i18n) { - if (mask === void 0) { - mask = globalMasks["default"]; - } - if (i18n === void 0) { - i18n = {}; - } - if (typeof dateObj === "number") { - dateObj = new Date(dateObj); - } - if (Object.prototype.toString.call(dateObj) !== "[object Date]" || isNaN(dateObj.getTime())) { - throw new Error("Invalid Date pass to format"); - } - mask = globalMasks[mask] || mask; - var literals = []; - mask = mask.replace(literal, function($0, $1) { - literals.push($1); - return "@@@"; - }); - var combinedI18nSettings = assign(assign({}, globalI18n), i18n); - mask = mask.replace(token, function($0) { - return formatFlags[$0](dateObj, combinedI18nSettings); - }); - return mask.replace(/@@@/g, function() { - return literals.shift(); - }); - }; - function parse(dateStr, format2, i18n) { - if (i18n === void 0) { - i18n = {}; - } - if (typeof format2 !== "string") { - throw new Error("Invalid format in fecha parse"); - } - format2 = globalMasks[format2] || format2; - if (dateStr.length > 1e3) { - return null; - } - var today = /* @__PURE__ */ new Date(); - var dateInfo = { - year: today.getFullYear(), - month: 0, - day: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0, - isPm: null, - timezoneOffset: null - }; - var parseInfo = []; - var literals = []; - var newFormat = format2.replace(literal, function($0, $1) { - literals.push(regexEscape($1)); - return "@@@"; - }); - var specifiedFields = {}; - var requiredFields = {}; - newFormat = regexEscape(newFormat).replace(token, function($0) { - var info = parseFlags[$0]; - var field2 = info[0], regex = info[1], requiredField = info[3]; - if (specifiedFields[field2]) { - throw new Error("Invalid format. " + field2 + " specified twice in format"); - } - specifiedFields[field2] = true; - if (requiredField) { - requiredFields[requiredField] = true; - } - parseInfo.push(info); - return "(" + regex + ")"; - }); - Object.keys(requiredFields).forEach(function(field2) { - if (!specifiedFields[field2]) { - throw new Error("Invalid format. " + field2 + " is required in specified format"); - } - }); - newFormat = newFormat.replace(/@@@/g, function() { - return literals.shift(); - }); - var matches = dateStr.match(new RegExp(newFormat, "i")); - if (!matches) { - return null; - } - var combinedI18nSettings = assign(assign({}, globalI18n), i18n); - for (var i = 1; i < matches.length; i++) { - var _a2 = parseInfo[i - 1], field = _a2[0], parser = _a2[2]; - var value = parser ? parser(matches[i], combinedI18nSettings) : +matches[i]; - if (value == null) { - return null; - } - dateInfo[field] = value; - } - if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) { - dateInfo.hour = +dateInfo.hour + 12; - } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) { - dateInfo.hour = 0; - } - var dateTZ; - if (dateInfo.timezoneOffset == null) { - dateTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond); - var validateFields = [ - ["month", "getMonth"], - ["day", "getDate"], - ["hour", "getHours"], - ["minute", "getMinutes"], - ["second", "getSeconds"] - ]; - for (var i = 0, len = validateFields.length; i < len; i++) { - if (specifiedFields[validateFields[i][0]] && dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]()) { - return null; - } - } - } else { - dateTZ = new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond)); - if (dateInfo.month > 11 || dateInfo.month < 0 || dateInfo.day > 31 || dateInfo.day < 1 || dateInfo.hour > 23 || dateInfo.hour < 0 || dateInfo.minute > 59 || dateInfo.minute < 0 || dateInfo.second > 59 || dateInfo.second < 0) { - return null; - } - } - return dateTZ; - } - var fecha = { - format, - parse, - defaultI18n, - setGlobalDateI18n, - setGlobalDateMasks - }; - exports3.assign = assign; - exports3.default = fecha; - exports3.format = format; - exports3.parse = parse; - exports3.defaultI18n = defaultI18n; - exports3.setGlobalDateI18n = setGlobalDateI18n; - exports3.setGlobalDateMasks = setGlobalDateMasks; - Object.defineProperty(exports3, "__esModule", { value: true }); - }); - } -}); - -// node_modules/logform/timestamp.js -var require_timestamp = __commonJS({ - "node_modules/logform/timestamp.js"(exports2, module2) { - "use strict"; - var fecha = require_fecha_umd(); - var format = require_format(); - module2.exports = format((info, opts = {}) => { - if (opts.format) { - info.timestamp = typeof opts.format === "function" ? opts.format() : fecha.format(/* @__PURE__ */ new Date(), opts.format); - } - if (!info.timestamp) { - info.timestamp = (/* @__PURE__ */ new Date()).toISOString(); - } - if (opts.alias) { - info[opts.alias] = info.timestamp; - } - return info; - }); - } -}); - -// node_modules/logform/uncolorize.js -var require_uncolorize = __commonJS({ - "node_modules/logform/uncolorize.js"(exports2, module2) { - "use strict"; - var colors = require_safe(); - var format = require_format(); - var { MESSAGE } = require_triple_beam(); - module2.exports = format((info, opts) => { - if (opts.level !== false) { - info.level = colors.strip(info.level); - } - if (opts.message !== false) { - info.message = colors.strip(String(info.message)); - } - if (opts.raw !== false && info[MESSAGE]) { - info[MESSAGE] = colors.strip(String(info[MESSAGE])); - } - return info; - }); - } -}); - -// node_modules/logform/index.js -var require_logform = __commonJS({ - "node_modules/logform/index.js"(exports2) { - "use strict"; - var format = exports2.format = require_format(); - exports2.levels = require_levels(); - function exposeFormat(name, requireFormat) { - Object.defineProperty(format, name, { - get() { - return requireFormat(); - }, - configurable: true - }); - } - exposeFormat("align", function() { - return require_align(); - }); - exposeFormat("errors", function() { - return require_errors(); - }); - exposeFormat("cli", function() { - return require_cli2(); - }); - exposeFormat("combine", function() { - return require_combine(); - }); - exposeFormat("colorize", function() { - return require_colorize(); - }); - exposeFormat("json", function() { - return require_json(); - }); - exposeFormat("label", function() { - return require_label(); - }); - exposeFormat("logstash", function() { - return require_logstash(); - }); - exposeFormat("metadata", function() { - return require_metadata(); - }); - exposeFormat("ms", function() { - return require_ms2(); - }); - exposeFormat("padLevels", function() { - return require_pad_levels(); - }); - exposeFormat("prettyPrint", function() { - return require_pretty_print(); - }); - exposeFormat("printf", function() { - return require_printf(); - }); - exposeFormat("simple", function() { - return require_simple(); - }); - exposeFormat("splat", function() { - return require_splat(); - }); - exposeFormat("timestamp", function() { - return require_timestamp(); - }); - exposeFormat("uncolorize", function() { - return require_uncolorize(); - }); - } -}); - -// node_modules/winston/lib/winston/common.js -var require_common2 = __commonJS({ - "node_modules/winston/lib/winston/common.js"(exports2) { - "use strict"; - var { format } = __require("util"); - exports2.warn = { - deprecated(prop) { - return () => { - throw new Error(format("{ %s } was removed in winston@3.0.0.", prop)); - }; - }, - useFormat(prop) { - return () => { - throw new Error([ - format("{ %s } was removed in winston@3.0.0.", prop), - "Use a custom winston.format = winston.format(function) instead." - ].join("\n")); - }; - }, - forFunctions(obj, type, props) { - props.forEach((prop) => { - obj[prop] = exports2.warn[type](prop); - }); - }, - forProperties(obj, type, props) { - props.forEach((prop) => { - const notice = exports2.warn[type](prop); - Object.defineProperty(obj, prop, { - get: notice, - set: notice - }); - }); - } - }; - } -}); - -// node_modules/winston/package.json -var require_package2 = __commonJS({ - "node_modules/winston/package.json"(exports2, module2) { - module2.exports = { - name: "winston", - description: "A logger for just about everything.", - version: "3.17.0", - author: "Charlie Robbins ", - maintainers: [ - "David Hyde " - ], - repository: { - type: "git", - url: "https://github.com/winstonjs/winston.git" - }, - keywords: [ - "winston", - "logger", - "logging", - "logs", - "sysadmin", - "bunyan", - "pino", - "loglevel", - "tools", - "json", - "stream" - ], - dependencies: { - "@dabh/diagnostics": "^2.0.2", - "@colors/colors": "^1.6.0", - async: "^3.2.3", - "is-stream": "^2.0.0", - logform: "^2.7.0", - "one-time": "^1.0.0", - "readable-stream": "^3.4.0", - "safe-stable-stringify": "^2.3.1", - "stack-trace": "0.0.x", - "triple-beam": "^1.3.0", - "winston-transport": "^4.9.0" - }, - devDependencies: { - "@babel/cli": "^7.23.9", - "@babel/core": "^7.24.0", - "@babel/preset-env": "^7.24.0", - "@dabh/eslint-config-populist": "^4.4.0", - "@types/node": "^20.11.24", - "abstract-winston-transport": "^0.5.1", - assume: "^2.2.0", - "cross-spawn-async": "^2.2.5", - eslint: "^8.57.0", - hock: "^1.4.1", - mocha: "^10.3.0", - nyc: "^17.1.0", - rimraf: "5.0.1", - split2: "^4.1.0", - "std-mocks": "^2.0.0", - through2: "^4.0.2", - "winston-compat": "^0.1.5" - }, - main: "./lib/winston.js", - browser: "./dist/winston", - types: "./index.d.ts", - scripts: { - lint: "eslint lib/*.js lib/winston/*.js lib/winston/**/*.js --resolve-plugins-relative-to ./node_modules/@dabh/eslint-config-populist", - test: "rimraf test/fixtures/logs/* && mocha", - "test:coverage": "nyc npm run test:unit", - "test:unit": "mocha test/unit", - "test:integration": "mocha test/integration", - build: "rimraf dist && babel lib -d dist", - prepublishOnly: "npm run build" - }, - engines: { - node: ">= 12.0.0" - }, - license: "MIT" - }; - } -}); - -// node_modules/util-deprecate/node.js -var require_node2 = __commonJS({ - "node_modules/util-deprecate/node.js"(exports2, module2) { - module2.exports = __require("util").deprecate; - } -}); - -// node_modules/readable-stream/lib/internal/streams/stream.js -var require_stream = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/stream.js"(exports2, module2) { - module2.exports = __require("stream"); - } -}); - -// node_modules/readable-stream/lib/internal/streams/destroy.js -var require_destroy = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports2, module2) { - "use strict"; - function destroy(err, cb) { - var _this = this; - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - return this; - } - if (this._readableState) { - this._readableState.destroyed = true; - } - if (this._writableState) { - this._writableState.destroyed = true; - } - this._destroy(err || null, function(err2) { - if (!cb && err2) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err2); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err2); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err2); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - return this; - } - function emitErrorAndCloseNT(self2, err) { - emitErrorNT(self2, err); - emitCloseNT(self2); - } - function emitCloseNT(self2) { - if (self2._writableState && !self2._writableState.emitClose) return; - if (self2._readableState && !self2._readableState.emitClose) return; - self2.emit("close"); - } - function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } - } - function emitErrorNT(self2, err) { - self2.emit("error", err); - } - function errorOrDestroy(stream4, err) { - var rState = stream4._readableState; - var wState = stream4._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream4.destroy(err); - else stream4.emit("error", err); - } - module2.exports = { - destroy, - undestroy, - errorOrDestroy - }; - } -}); - -// node_modules/readable-stream/errors.js -var require_errors2 = __commonJS({ - "node_modules/readable-stream/errors.js"(exports2, module2) { - "use strict"; - var codes = {}; - function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - function getMessage(arg1, arg2, arg3) { - if (typeof message === "string") { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - class NodeError extends Base { - constructor(arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } - } - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; - } - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(", ")}, or ` + expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; - } - } else { - return `of ${thing} ${String(expected)}`; - } - } - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } - function endsWith2(str, search, this_len) { - if (this_len === void 0 || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; - } - function includes(str, search, start) { - if (typeof start !== "number") { - start = 0; - } - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } - } - createErrorType("ERR_INVALID_OPT_VALUE", function(name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; - }, TypeError); - createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { - let determiner; - if (typeof expected === "string" && startsWith(expected, "not ")) { - determiner = "must not be"; - expected = expected.replace(/^not /, ""); - } else { - determiner = "must be"; - } - let msg; - if (endsWith2(name, " argument")) { - msg = `The ${name} ${determiner} ${oneOf(expected, "type")}`; - } else { - const type = includes(name, ".") ? "property" : "argument"; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, "type")}`; - } - msg += `. Received type ${typeof actual}`; - return msg; - }, TypeError); - createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); - createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name) { - return "The " + name + " method is not implemented"; - }); - createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); - createErrorType("ERR_STREAM_DESTROYED", function(name) { - return "Cannot call " + name + " after a stream was destroyed"; - }); - createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); - createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); - createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); - createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); - createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { - return "Unknown encoding: " + arg; - }, TypeError); - createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); - module2.exports.codes = codes; - } -}); - -// node_modules/readable-stream/lib/internal/streams/state.js -var require_state2 = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { - "use strict"; - var ERR_INVALID_OPT_VALUE = require_errors2().codes.ERR_INVALID_OPT_VALUE; - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; - } - function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : "highWaterMark"; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - return Math.floor(hwm); - } - return state.objectMode ? 16 : 16 * 1024; - } - module2.exports = { - getHighWaterMark - }; - } -}); - -// node_modules/inherits/inherits_browser.js -var require_inherits_browser = __commonJS({ - "node_modules/inherits/inherits_browser.js"(exports2, module2) { - if (typeof Object.create === "function") { - module2.exports = function inherits2(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - } - }; - } else { - module2.exports = function inherits2(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - var TempCtor = function() { - }; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - }; - } - } -}); - -// node_modules/inherits/inherits.js -var require_inherits = __commonJS({ - "node_modules/inherits/inherits.js"(exports2, module2) { - try { - util3 = __require("util"); - if (typeof util3.inherits !== "function") throw ""; - module2.exports = util3.inherits; - } catch (e) { - module2.exports = require_inherits_browser(); - } - var util3; - } -}); - -// node_modules/readable-stream/lib/internal/streams/buffer_list.js -var require_buffer_list = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports2, module2) { - "use strict"; - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - enumerableOnly && (symbols = symbols.filter(function(sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - })), keys.push.apply(keys, symbols); - } - return keys; - } - function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = null != arguments[i] ? arguments[i] : {}; - i % 2 ? ownKeys(Object(source), true).forEach(function(key) { - _defineProperty(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - return target; - } - function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); - } - } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - Object.defineProperty(Constructor, "prototype", { writable: false }); - return Constructor; - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - var _require = __require("buffer"); - var Buffer2 = _require.Buffer; - var _require2 = __require("util"); - var inspect = _require2.inspect; - var custom = inspect && inspect.custom || "inspect"; - function copyBuffer(src, target, offset) { - Buffer2.prototype.copy.call(src, target, offset); - } - module2.exports = /* @__PURE__ */ function() { - function BufferList() { - _classCallCheck(this, BufferList); - this.head = null; - this.tail = null; - this.length = 0; - } - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry; - else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null; - else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join2(s) { - if (this.length === 0) return ""; - var p = this.head; - var ret = "" + p.data; - while (p = p.next) ret += s + p.data; - return ret; - } - }, { - key: "concat", - value: function concat3(n) { - if (this.length === 0) return Buffer2.alloc(0); - var ret = Buffer2.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - } - // Consumes a specified amount of bytes or characters from the buffered data. - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - if (n < this.head.data.length) { - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - ret = this.shift(); - } else { - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } - // Consumes a specified amount of characters from the buffered data. - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str; - else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next; - else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - this.length -= c; - return ret; - } - // Consumes a specified amount of bytes from the buffered data. - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer2.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next; - else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - this.length -= c; - return ret; - } - // Make sure the linked list only shows the minimal necessary information. - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread(_objectSpread({}, options), {}, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - return BufferList; - }(); - } -}); - -// node_modules/safe-buffer/index.js -var require_safe_buffer = __commonJS({ - "node_modules/safe-buffer/index.js"(exports2, module2) { - var buffer2 = __require("buffer"); - var Buffer2 = buffer2.Buffer; - function copyProps(src, dst) { - for (var key in src) { - dst[key] = src[key]; - } - } - if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { - module2.exports = buffer2; - } else { - copyProps(buffer2, exports2); - exports2.Buffer = SafeBuffer; - } - function SafeBuffer(arg, encodingOrOffset, length) { - return Buffer2(arg, encodingOrOffset, length); - } - SafeBuffer.prototype = Object.create(Buffer2.prototype); - copyProps(Buffer2, SafeBuffer); - SafeBuffer.from = function(arg, encodingOrOffset, length) { - if (typeof arg === "number") { - throw new TypeError("Argument must not be a number"); - } - return Buffer2(arg, encodingOrOffset, length); - }; - SafeBuffer.alloc = function(size5, fill, encoding) { - if (typeof size5 !== "number") { - throw new TypeError("Argument must be a number"); - } - var buf = Buffer2(size5); - if (fill !== void 0) { - if (typeof encoding === "string") { - buf.fill(fill, encoding); - } else { - buf.fill(fill); - } - } else { - buf.fill(0); - } - return buf; - }; - SafeBuffer.allocUnsafe = function(size5) { - if (typeof size5 !== "number") { - throw new TypeError("Argument must be a number"); - } - return Buffer2(size5); - }; - SafeBuffer.allocUnsafeSlow = function(size5) { - if (typeof size5 !== "number") { - throw new TypeError("Argument must be a number"); - } - return buffer2.SlowBuffer(size5); - }; - } -}); - -// node_modules/string_decoder/lib/string_decoder.js -var require_string_decoder = __commonJS({ - "node_modules/string_decoder/lib/string_decoder.js"(exports2) { - "use strict"; - var Buffer2 = require_safe_buffer().Buffer; - var isEncoding = Buffer2.isEncoding || function(encoding) { - encoding = "" + encoding; - switch (encoding && encoding.toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - case "raw": - return true; - default: - return false; - } - }; - function _normalizeEncoding(enc) { - if (!enc) return "utf8"; - var retried; - while (true) { - switch (enc) { - case "utf8": - case "utf-8": - return "utf8"; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return "utf16le"; - case "latin1": - case "binary": - return "latin1"; - case "base64": - case "ascii": - case "hex": - return enc; - default: - if (retried) return; - enc = ("" + enc).toLowerCase(); - retried = true; - } - } - } - function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc); - return nenc || enc; - } - exports2.StringDecoder = StringDecoder; - function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case "utf16le": - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case "utf8": - this.fillLast = utf8FillLast; - nb = 4; - break; - case "base64": - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer2.allocUnsafe(nb); - } - StringDecoder.prototype.write = function(buf) { - if (buf.length === 0) return ""; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === void 0) return ""; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ""; - }; - StringDecoder.prototype.end = utf8End; - StringDecoder.prototype.text = utf8Text; - StringDecoder.prototype.fillLast = function(buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; - }; - function utf8CheckByte(byte) { - if (byte <= 127) return 0; - else if (byte >> 5 === 6) return 2; - else if (byte >> 4 === 14) return 3; - else if (byte >> 3 === 30) return 4; - return byte >> 6 === 2 ? -1 : -2; - } - function utf8CheckIncomplete(self2, buf, i) { - var j2 = buf.length - 1; - if (j2 < i) return 0; - var nb = utf8CheckByte(buf[j2]); - if (nb >= 0) { - if (nb > 0) self2.lastNeed = nb - 1; - return nb; - } - if (--j2 < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j2]); - if (nb >= 0) { - if (nb > 0) self2.lastNeed = nb - 2; - return nb; - } - if (--j2 < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j2]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0; - else self2.lastNeed = nb - 3; - } - return nb; - } - return 0; - } - function utf8CheckExtraBytes(self2, buf, p) { - if ((buf[0] & 192) !== 128) { - self2.lastNeed = 0; - return "\uFFFD"; - } - if (self2.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 192) !== 128) { - self2.lastNeed = 1; - return "\uFFFD"; - } - if (self2.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 192) !== 128) { - self2.lastNeed = 2; - return "\uFFFD"; - } - } - } - } - function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== void 0) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; - } - function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString("utf8", i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString("utf8", i, end); - } - function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) return r + "\uFFFD"; - return r; - } - function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString("utf16le", i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 55296 && c <= 56319) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString("utf16le", i, buf.length - 1); - } - function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString("utf16le", 0, end); - } - return r; - } - function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString("base64", i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString("base64", i, buf.length - n); - } - function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); - return r; - } - function simpleWrite(buf) { - return buf.toString(this.encoding); - } - function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ""; - } - } -}); - -// node_modules/readable-stream/lib/internal/streams/end-of-stream.js -var require_end_of_stream = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports2, module2) { - "use strict"; - var ERR_STREAM_PREMATURE_CLOSE = require_errors2().codes.ERR_STREAM_PREMATURE_CLOSE; - function once(callback) { - var called = false; - return function() { - if (called) return; - called = true; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - callback.apply(this, args); - }; - } - function noop2() { - } - function isRequest2(stream4) { - return stream4.setHeader && typeof stream4.abort === "function"; - } - function eos(stream4, opts, callback) { - if (typeof opts === "function") return eos(stream4, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop2); - var readable = opts.readable || opts.readable !== false && stream4.readable; - var writable = opts.writable || opts.writable !== false && stream4.writable; - var onlegacyfinish = function onlegacyfinish2() { - if (!stream4.writable) onfinish(); - }; - var writableEnded = stream4._writableState && stream4._writableState.finished; - var onfinish = function onfinish2() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream4); - }; - var readableEnded = stream4._readableState && stream4._readableState.endEmitted; - var onend = function onend2() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream4); - }; - var onerror = function onerror2(err) { - callback.call(stream4, err); - }; - var onclose = function onclose2() { - var err; - if (readable && !readableEnded) { - if (!stream4._readableState || !stream4._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream4, err); - } - if (writable && !writableEnded) { - if (!stream4._writableState || !stream4._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream4, err); - } - }; - var onrequest = function onrequest2() { - stream4.req.on("finish", onfinish); - }; - if (isRequest2(stream4)) { - stream4.on("complete", onfinish); - stream4.on("abort", onclose); - if (stream4.req) onrequest(); - else stream4.on("request", onrequest); - } else if (writable && !stream4._writableState) { - stream4.on("end", onlegacyfinish); - stream4.on("close", onlegacyfinish); - } - stream4.on("end", onend); - stream4.on("finish", onfinish); - if (opts.error !== false) stream4.on("error", onerror); - stream4.on("close", onclose); - return function() { - stream4.removeListener("complete", onfinish); - stream4.removeListener("abort", onclose); - stream4.removeListener("request", onrequest); - if (stream4.req) stream4.req.removeListener("finish", onfinish); - stream4.removeListener("end", onlegacyfinish); - stream4.removeListener("close", onlegacyfinish); - stream4.removeListener("finish", onfinish); - stream4.removeListener("end", onend); - stream4.removeListener("error", onerror); - stream4.removeListener("close", onclose); - }; - } - module2.exports = eos; - } -}); - -// node_modules/readable-stream/lib/internal/streams/async_iterator.js -var require_async_iterator = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/async_iterator.js"(exports2, module2) { - "use strict"; - var _Object$setPrototypeO; - function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - var finished = require_end_of_stream(); - var kLastResolve = Symbol("lastResolve"); - var kLastReject = Symbol("lastReject"); - var kError = Symbol("error"); - var kEnded = Symbol("ended"); - var kLastPromise = Symbol("lastPromise"); - var kHandlePromise = Symbol("handlePromise"); - var kStream = Symbol("stream"); - function createIterResult(value, done) { - return { - value, - done - }; - } - function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - if (resolve !== null) { - var data = iter[kStream].read(); - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } - } - function onReadable(iter) { - process.nextTick(readAndResolve, iter); - } - function wrapForNext(lastPromise, iter) { - return function(resolve, reject) { - lastPromise.then(function() { - if (iter[kEnded]) { - resolve(createIterResult(void 0, true)); - return; - } - iter[kHandlePromise](resolve, reject); - }, reject); +// node_modules/@colors/colors/lib/custom/zalgo.js +var require_zalgo = __commonJS({ + "node_modules/@colors/colors/lib/custom/zalgo.js"(exports2, module2) { + module2["exports"] = function zalgo(text, options) { + text = text || " he is here "; + var soul = { + "up": [ + "\u030D", + "\u030E", + "\u0304", + "\u0305", + "\u033F", + "\u0311", + "\u0306", + "\u0310", + "\u0352", + "\u0357", + "\u0351", + "\u0307", + "\u0308", + "\u030A", + "\u0342", + "\u0313", + "\u0308", + "\u034A", + "\u034B", + "\u034C", + "\u0303", + "\u0302", + "\u030C", + "\u0350", + "\u0300", + "\u0301", + "\u030B", + "\u030F", + "\u0312", + "\u0313", + "\u0314", + "\u033D", + "\u0309", + "\u0363", + "\u0364", + "\u0365", + "\u0366", + "\u0367", + "\u0368", + "\u0369", + "\u036A", + "\u036B", + "\u036C", + "\u036D", + "\u036E", + "\u036F", + "\u033E", + "\u035B", + "\u0346", + "\u031A" + ], + "down": [ + "\u0316", + "\u0317", + "\u0318", + "\u0319", + "\u031C", + "\u031D", + "\u031E", + "\u031F", + "\u0320", + "\u0324", + "\u0325", + "\u0326", + "\u0329", + "\u032A", + "\u032B", + "\u032C", + "\u032D", + "\u032E", + "\u032F", + "\u0330", + "\u0331", + "\u0332", + "\u0333", + "\u0339", + "\u033A", + "\u033B", + "\u033C", + "\u0345", + "\u0347", + "\u0348", + "\u0349", + "\u034D", + "\u034E", + "\u0353", + "\u0354", + "\u0355", + "\u0356", + "\u0359", + "\u035A", + "\u0323" + ], + "mid": [ + "\u0315", + "\u031B", + "\u0300", + "\u0301", + "\u0358", + "\u0321", + "\u0322", + "\u0327", + "\u0328", + "\u0334", + "\u0335", + "\u0336", + "\u035C", + "\u035D", + "\u035E", + "\u035F", + "\u0360", + "\u0362", + "\u0338", + "\u0337", + "\u0361", + " \u0489" + ] }; - } - var AsyncIteratorPrototype = Object.getPrototypeOf(function() { - }); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - next: function next() { - var _this = this; - var error = this[kError]; - if (error !== null) { - return Promise.reject(error); - } - if (this[kEnded]) { - return Promise.resolve(createIterResult(void 0, true)); - } - if (this[kStream].destroyed) { - return new Promise(function(resolve, reject) { - process.nextTick(function() { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(void 0, true)); - } - }); - }); - } - var lastPromise = this[kLastPromise]; - var promise; - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - var data = this[kStream].read(); - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - promise = new Promise(this[kHandlePromise]); - } - this[kLastPromise] = promise; - return promise; + var all3 = [].concat(soul.up, soul.down, soul.mid); + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; } - }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() { - return this; - }), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - return new Promise(function(resolve, reject) { - _this2[kStream].destroy(null, function(err) { - if (err) { - reject(err); - return; - } - resolve(createIterResult(void 0, true)); + function isChar(character) { + var bool = false; + all3.filter(function(i) { + bool = i === character; }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream4) { - var _Object$create; - var iterator2 = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream4, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream4._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator2[kStream].read(); - if (data) { - iterator2[kLastPromise] = null; - iterator2[kLastResolve] = null; - iterator2[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator2[kLastResolve] = resolve; - iterator2[kLastReject] = reject; + return bool; + } + function heComes(text2, options2) { + var result = ""; + var counts; + var l; + options2 = options2 || {}; + options2["up"] = typeof options2["up"] !== "undefined" ? options2["up"] : true; + options2["mid"] = typeof options2["mid"] !== "undefined" ? options2["mid"] : true; + options2["down"] = typeof options2["down"] !== "undefined" ? options2["down"] : true; + options2["size"] = typeof options2["size"] !== "undefined" ? options2["size"] : "maxi"; + text2 = text2.split(""); + for (l in text2) { + if (isChar(l)) { + continue; } - }, - writable: true - }), _Object$create)); - iterator2[kLastPromise] = null; - finished(stream4, function(err) { - if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { - var reject = iterator2[kLastReject]; - if (reject !== null) { - iterator2[kLastPromise] = null; - iterator2[kLastResolve] = null; - iterator2[kLastReject] = null; - reject(err); + result = result + text2[l]; + counts = { "up": 0, "down": 0, "mid": 0 }; + switch (options2.size) { + case "mini": + counts.up = randomNumber(8); + counts.mid = randomNumber(2); + counts.down = randomNumber(8); + break; + case "maxi": + counts.up = randomNumber(16) + 3; + counts.mid = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } + var arr = ["up", "mid", "down"]; + for (var d in arr) { + var index2 = arr[d]; + for (var i = 0; i <= counts[index2]; i++) { + if (options2[index2]) { + result = result + soul[index2][randomNumber(soul[index2].length)]; + } + } } - iterator2[kError] = err; - return; - } - var resolve = iterator2[kLastResolve]; - if (resolve !== null) { - iterator2[kLastPromise] = null; - iterator2[kLastResolve] = null; - iterator2[kLastReject] = null; - resolve(createIterResult(void 0, true)); } - iterator2[kEnded] = true; - }); - stream4.on("readable", onReadable.bind(null, iterator2)); - return iterator2; + return result; + } + return heComes(text, options); }; - module2.exports = createReadableStreamAsyncIterator; } }); -// node_modules/readable-stream/lib/internal/streams/from.js -var require_from = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/from.js"(exports2, module2) { - "use strict"; - function asyncGeneratorStep(gen3, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen3[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - function _asyncToGenerator(fn2) { - return function() { - var self2 = this, args = arguments; - return new Promise(function(resolve, reject) { - var gen3 = fn2.apply(self2, args); - function _next(value) { - asyncGeneratorStep(gen3, resolve, reject, _next, _throw, "next", value); - } - function _throw(err) { - asyncGeneratorStep(gen3, resolve, reject, _next, _throw, "throw", err); - } - _next(void 0); - }); - }; - } - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - enumerableOnly && (symbols = symbols.filter(function(sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - })), keys.push.apply(keys, symbols); - } - return keys; - } - function _objectSpread(target) { - for (var i = 1; i < arguments.length; i++) { - var source = null != arguments[i] ? arguments[i] : {}; - i % 2 ? ownKeys(Object(source), true).forEach(function(key) { - _defineProperty(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - return target; - } - function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - var ERR_INVALID_ARG_TYPE = require_errors2().codes.ERR_INVALID_ARG_TYPE; - function from5(Readable2, iterable, opts) { - var iterator2; - if (iterable && typeof iterable.next === "function") { - iterator2 = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator2 = iterable[Symbol.asyncIterator](); - else if (iterable && iterable[Symbol.iterator]) iterator2 = iterable[Symbol.iterator](); - else throw new ERR_INVALID_ARG_TYPE("iterable", ["Iterable"], iterable); - var readable = new Readable2(_objectSpread({ - objectMode: true - }, opts)); - var reading = false; - readable._read = function() { - if (!reading) { - reading = true; - next(); +// node_modules/@colors/colors/lib/maps/america.js +var require_america = __commonJS({ + "node_modules/@colors/colors/lib/maps/america.js"(exports2, module2) { + module2["exports"] = function(colors) { + return function(letter, i, exploded) { + if (letter === " ") return letter; + switch (i % 3) { + case 0: + return colors.red(letter); + case 1: + return colors.white(letter); + case 2: + return colors.blue(letter); } }; - function next() { - return _next2.apply(this, arguments); - } - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _yield$iterator$next = yield iterator2.next(), value = _yield$iterator$next.value, done = _yield$iterator$next.done; - if (done) { - readable.push(null); - } else if (readable.push(yield value)) { - next(); - } else { - reading = false; - } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); - } - return readable; - } - module2.exports = from5; + }; } }); -// node_modules/readable-stream/lib/_stream_readable.js -var require_stream_readable = __commonJS({ - "node_modules/readable-stream/lib/_stream_readable.js"(exports2, module2) { - "use strict"; - module2.exports = Readable2; - var Duplex; - Readable2.ReadableState = ReadableState; - var EE = __require("events").EventEmitter; - var EElistenerCount = function EElistenerCount2(emitter, type) { - return emitter.listeners(type).length; - }; - var Stream = require_stream(); - var Buffer2 = __require("buffer").Buffer; - var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { - }; - function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); - } - function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; - } - var debugUtil = __require("util"); - var debug; - if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog("stream"); - } else { - debug = function debug2() { +// node_modules/@colors/colors/lib/maps/zebra.js +var require_zebra = __commonJS({ + "node_modules/@colors/colors/lib/maps/zebra.js"(exports2, module2) { + module2["exports"] = function(colors) { + return function(letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); }; - } - var BufferList = require_buffer_list(); - var destroyImpl = require_destroy(); - var _require = require_state2(); - var getHighWaterMark = _require.getHighWaterMark; - var _require$codes = require_errors2().codes; - var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; - var ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; - var StringDecoder; - var createReadableStreamAsyncIterator; - var from5; - require_inherits()(Readable2, Stream); - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; - function prependListener(emitter, event, fn2) { - if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn2); - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn2); - else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn2); - else emitter._events[event] = [fn2, emitter._events[event]]; - } - function ReadableState(options, stream4, isDuplex) { - Duplex = Duplex || require_stream_duplex(); - options = options || {}; - if (typeof isDuplex !== "boolean") isDuplex = stream4 instanceof Duplex; - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex); - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - this.sync = true; - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; - this.emitClose = options.emitClose !== false; - this.autoDestroy = !!options.autoDestroy; - this.destroyed = false; - this.defaultEncoding = options.defaultEncoding || "utf8"; - this.awaitDrain = 0; - this.readingMore = false; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } - } - function Readable2(options) { - Duplex = Duplex || require_stream_duplex(); - if (!(this instanceof Readable2)) return new Readable2(options); - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); - this.readable = true; - if (options) { - if (typeof options.read === "function") this._read = options.read; - if (typeof options.destroy === "function") this._destroy = options.destroy; - } - Stream.call(this); - } - Object.defineProperty(Readable2.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === void 0) { - return false; - } - return this._readableState.destroyed; - }, - set: function set(value) { - if (!this._readableState) { - return; - } - this._readableState.destroyed = value; - } - }); - Readable2.prototype.destroy = destroyImpl.destroy; - Readable2.prototype._undestroy = destroyImpl.undestroy; - Readable2.prototype._destroy = function(err, cb) { - cb(err); }; - Readable2.prototype.push = function(chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - if (!state.objectMode) { - if (typeof chunk === "string") { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer2.from(chunk, encoding); - encoding = ""; - } - skipChunkCheck = true; + } +}); + +// node_modules/@colors/colors/lib/maps/rainbow.js +var require_rainbow = __commonJS({ + "node_modules/@colors/colors/lib/maps/rainbow.js"(exports2, module2) { + module2["exports"] = function(colors) { + var rainbowColors = ["red", "yellow", "green", "blue", "magenta"]; + return function(letter, i, exploded) { + if (letter === " ") { + return letter; + } else { + return colors[rainbowColors[i++ % rainbowColors.length]](letter); } - } else { - skipChunkCheck = true; - } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; }; - Readable2.prototype.unshift = function(chunk) { - return readableAddChunk(this, chunk, null, true, false); + } +}); + +// node_modules/@colors/colors/lib/maps/random.js +var require_random = __commonJS({ + "node_modules/@colors/colors/lib/maps/random.js"(exports2, module2) { + module2["exports"] = function(colors) { + var available = [ + "underline", + "inverse", + "grey", + "yellow", + "red", + "green", + "blue", + "white", + "cyan", + "magenta", + "brightYellow", + "brightRed", + "brightGreen", + "brightBlue", + "brightWhite", + "brightCyan", + "brightMagenta" + ]; + return function(letter, i, exploded) { + return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 2))]](letter); + }; }; - function readableAddChunk(stream4, chunk, encoding, addToFront, skipChunkCheck) { - debug("readableAddChunk", chunk); - var state = stream4._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream4, state); - } else { - var er2; - if (!skipChunkCheck) er2 = chunkInvalid(state, chunk); - if (er2) { - errorOrDestroy(stream4, er2); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream4, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); - else addChunk(stream4, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream4, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream4, state, chunk, false); - else maybeReadMore(stream4, state); - } else { - addChunk(stream4, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream4, state); - } - } - return !state.ended && (state.length < state.highWaterMark || state.length === 0); - } - function addChunk(stream4, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream4.emit("data", chunk); - } else { - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk); - else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream4); - } - maybeReadMore(stream4, state); - } - function chunkInvalid(state, chunk) { - var er2; - if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { - er2 = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); - } - return er2; + } +}); + +// node_modules/@colors/colors/lib/colors.js +var require_colors = __commonJS({ + "node_modules/@colors/colors/lib/colors.js"(exports2, module2) { + var colors = {}; + module2["exports"] = colors; + colors.themes = {}; + var util3 = __require("util"); + var ansiStyles = colors.styles = require_styles(); + var defineProps = Object.defineProperties; + var newLineRegex = new RegExp(/[\r\n]+/g); + colors.supportsColor = require_supports_colors().supportsColor; + if (typeof colors.enabled === "undefined") { + colors.enabled = colors.supportsColor() !== false; } - Readable2.prototype.isPaused = function() { - return this._readableState.flowing === false; + colors.enable = function() { + colors.enabled = true; }; - Readable2.prototype.setEncoding = function(enc) { - if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; - this._readableState.encoding = this._readableState.decoder.encoding; - var p = this._readableState.buffer.head; - var content = ""; - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - this._readableState.buffer.clear(); - if (content !== "") this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; + colors.disable = function() { + colors.enabled = false; + }; + colors.stripColors = colors.strip = function(str) { + return ("" + str).replace(/\x1B\[\d+m/g, ""); }; - var MAX_HWM = 1073741824; - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; + var stylize = colors.stylize = function stylize2(str, style) { + if (!colors.enabled) { + return str + ""; } - return n; - } - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - if (state.flowing && state.length) return state.buffer.head.data.length; - else return state.length; + var styleMap = ansiStyles[style]; + if (!styleMap && style in colors) { + return colors[style](str); } - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - if (!state.ended) { - state.needReadable = true; - return 0; + return styleMap.open + str + styleMap.close; + }; + var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + var escapeStringRegexp = function(str) { + if (typeof str !== "string") { + throw new TypeError("Expected a string"); } - return state.length; + return str.replace(matchOperatorsRe, "\\$&"); + }; + function build(_styles) { + var builder = function builder2() { + return applyStyle.apply(builder2, arguments); + }; + builder._styles = _styles; + builder.__proto__ = proto; + return builder; } - Readable2.prototype.read = function(n) { - debug("read", n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug("read: emitReadable", state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this); - else emitReadable(this); - return null; - } - n = howMuchToRead(n, state); - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - var doRead = state.needReadable; - debug("need readable", doRead); - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug("length less than watermark", doRead); - } - if (state.ended || state.reading) { - doRead = false; - debug("reading or ended", doRead); - } else if (doRead) { - debug("do read"); - state.reading = true; - state.sync = true; - if (state.length === 0) state.needReadable = true; - this._read(state.highWaterMark); - state.sync = false; - if (!state.reading) n = howMuchToRead(nOrig, state); - } - var ret; - if (n > 0) ret = fromList(n, state); - else ret = null; - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - if (state.length === 0) { - if (!state.ended) state.needReadable = true; - if (nOrig !== n && state.ended) endReadable(this); - } - if (ret !== null) this.emit("data", ret); + var styles = function() { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function(key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), "g"); + ret[key] = { + get: function() { + return build(this._styles.concat(key)); + } + }; + }); return ret; - }; - function onEofChunk(stream4, state) { - debug("onEofChunk"); - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + }(); + var proto = defineProps(function colors2() { + }, styles); + function applyStyle() { + var args = Array.prototype.slice.call(arguments); + var str = args.map(function(arg) { + if (arg != null && arg.constructor === String) { + return arg; + } else { + return util3.inspect(arg); } + }).join(" "); + if (!colors.enabled || !str) { + return str; } - state.ended = true; - if (state.sync) { - emitReadable(stream4); - } else { - state.needReadable = false; - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream4); + var newLinesPresent = str.indexOf("\n") != -1; + var nestedStyles = this._styles; + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + if (newLinesPresent) { + str = str.replace(newLineRegex, function(match) { + return code.close + match + code.open; + }); } } + return str; } - function emitReadable(stream4) { - var state = stream4._readableState; - debug("emitReadable", state.needReadable, state.emittedReadable); - state.needReadable = false; - if (!state.emittedReadable) { - debug("emitReadable", state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream4); - } - } - function emitReadable_(stream4) { - var state = stream4._readableState; - debug("emitReadable_", state.destroyed, state.length, state.ended); - if (!state.destroyed && (state.length || state.ended)) { - stream4.emit("readable"); - state.emittedReadable = false; + colors.setTheme = function(theme) { + if (typeof theme === "string") { + console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));"); + return; } - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream4); - } - function maybeReadMore(stream4, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream4, state); + for (var style in theme) { + (function(style2) { + colors[style2] = function(str) { + if (typeof theme[style2] === "object") { + var out = str; + for (var i in theme[style2]) { + out = colors[theme[style2][i]](out); + } + return out; + } + return colors[theme[style2]](str); + }; + })(style); } + }; + function init() { + var ret = {}; + Object.keys(styles).forEach(function(name) { + ret[name] = { + get: function() { + return build([name]); + } + }; + }); + return ret; } - function maybeReadMore_(stream4, state) { - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug("maybeReadMore read 0"); - stream4.read(0); - if (len === state.length) - break; - } - state.readingMore = false; + var sequencer = function sequencer2(map2, str) { + var exploded = str.split(""); + exploded = exploded.map(map2); + return exploded.join(""); + }; + colors.trap = require_trap(); + colors.zalgo = require_zalgo(); + colors.maps = {}; + colors.maps.america = require_america()(colors); + colors.maps.zebra = require_zebra()(colors); + colors.maps.rainbow = require_rainbow()(colors); + colors.maps.random = require_random()(colors); + for (map in colors.maps) { + (function(map2) { + colors[map2] = function(str) { + return sequencer(colors.maps[map2], str); + }; + })(map); } - Readable2.prototype._read = function(n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); + var map; + defineProps(colors, init()); + } +}); + +// node_modules/@colors/colors/safe.js +var require_safe = __commonJS({ + "node_modules/@colors/colors/safe.js"(exports2, module2) { + var colors = require_colors(); + module2["exports"] = colors; + } +}); + +// node_modules/triple-beam/config/cli.js +var require_cli = __commonJS({ + "node_modules/triple-beam/config/cli.js"(exports2) { + "use strict"; + exports2.levels = { + error: 0, + warn: 1, + help: 2, + data: 3, + info: 4, + debug: 5, + prompt: 6, + verbose: 7, + input: 8, + silly: 9 }; - Readable2.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn); - else src.once("end", endFn); - dest.on("unpipe", onunpipe); - function onunpipe(readable, unpipeInfo) { - debug("onunpipe"); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } + exports2.colors = { + error: "red", + warn: "yellow", + help: "cyan", + data: "grey", + info: "green", + debug: "blue", + prompt: "grey", + verbose: "cyan", + input: "grey", + silly: "magenta" + }; + } +}); + +// node_modules/triple-beam/config/npm.js +var require_npm = __commonJS({ + "node_modules/triple-beam/config/npm.js"(exports2) { + "use strict"; + exports2.levels = { + error: 0, + warn: 1, + info: 2, + http: 3, + verbose: 4, + debug: 5, + silly: 6 + }; + exports2.colors = { + error: "red", + warn: "yellow", + info: "green", + http: "green", + verbose: "cyan", + debug: "blue", + silly: "magenta" + }; + } +}); + +// node_modules/triple-beam/config/syslog.js +var require_syslog = __commonJS({ + "node_modules/triple-beam/config/syslog.js"(exports2) { + "use strict"; + exports2.levels = { + emerg: 0, + alert: 1, + crit: 2, + error: 3, + warning: 4, + notice: 5, + info: 6, + debug: 7 + }; + exports2.colors = { + emerg: "red", + alert: "yellow", + crit: "red", + error: "red", + warning: "red", + notice: "yellow", + info: "green", + debug: "blue" + }; + } +}); + +// node_modules/triple-beam/config/index.js +var require_config = __commonJS({ + "node_modules/triple-beam/config/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "cli", { + value: require_cli() + }); + Object.defineProperty(exports2, "npm", { + value: require_npm() + }); + Object.defineProperty(exports2, "syslog", { + value: require_syslog() + }); + } +}); + +// node_modules/triple-beam/index.js +var require_triple_beam = __commonJS({ + "node_modules/triple-beam/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "LEVEL", { + value: Symbol.for("level") + }); + Object.defineProperty(exports2, "MESSAGE", { + value: Symbol.for("message") + }); + Object.defineProperty(exports2, "SPLAT", { + value: Symbol.for("splat") + }); + Object.defineProperty(exports2, "configs", { + value: require_config() + }); + } +}); + +// node_modules/logform/colorize.js +var require_colorize = __commonJS({ + "node_modules/logform/colorize.js"(exports2, module2) { + "use strict"; + var colors = require_safe(); + var { LEVEL, MESSAGE } = require_triple_beam(); + colors.enabled = true; + var hasSpace = /\s+/; + var Colorizer = class _Colorizer { + constructor(opts = {}) { + if (opts.colors) { + this.addColors(opts.colors); } + this.options = opts; } - function onend() { - debug("onend"); - dest.end(); + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + static addColors(clrs) { + const nextColors = Object.keys(clrs).reduce((acc, level) => { + acc[level] = hasSpace.test(clrs[level]) ? clrs[level].split(hasSpace) : clrs[level]; + return acc; + }, {}); + _Colorizer.allColors = Object.assign({}, _Colorizer.allColors || {}, nextColors); + return _Colorizer.allColors; } - var ondrain = pipeOnDrain(src); - dest.on("drain", ondrain); - var cleanedUp = false; - function cleanup() { - debug("cleanup"); - dest.removeListener("close", onclose); - dest.removeListener("finish", onfinish); - dest.removeListener("drain", ondrain); - dest.removeListener("error", onerror); - dest.removeListener("unpipe", onunpipe); - src.removeListener("end", onend); - src.removeListener("end", unpipe); - src.removeListener("data", ondata); - cleanedUp = true; - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + /* + * Adds the colors Object to the set of allColors + * known by the Colorizer + * + * @param {Object} colors Set of color mappings to add. + */ + addColors(clrs) { + return _Colorizer.addColors(clrs); } - src.on("data", ondata); - function ondata(chunk) { - debug("ondata"); - var ret = dest.write(chunk); - debug("dest.write", ret); - if (ret === false) { - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug("false write response, pause", state.awaitDrain); - state.awaitDrain++; - } - src.pause(); + /* + * function colorize (lookup, level, message) + * Performs multi-step colorization using @colors/colors/safe + */ + colorize(lookup, level, message) { + if (typeof message === "undefined") { + message = level; + } + if (!Array.isArray(_Colorizer.allColors[lookup])) { + return colors[_Colorizer.allColors[lookup]](message); + } + for (let i = 0, len = _Colorizer.allColors[lookup].length; i < len; i++) { + message = colors[_Colorizer.allColors[lookup][i]](message); + } + return message; + } + /* + * function transform (info, opts) + * Attempts to colorize the { level, message } of the given + * `logform` info object. + */ + transform(info, opts) { + if (opts.all && typeof info[MESSAGE] === "string") { + info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]); + } + if (opts.level || opts.all || !opts.message) { + info.level = this.colorize(info[LEVEL], info.level); + } + if (opts.all || opts.message) { + info.message = this.colorize(info[LEVEL], info.level, info.message); } + return info; + } + }; + module2.exports = (opts) => new Colorizer(opts); + module2.exports.Colorizer = module2.exports.Format = Colorizer; + } +}); + +// node_modules/logform/levels.js +var require_levels = __commonJS({ + "node_modules/logform/levels.js"(exports2, module2) { + "use strict"; + var { Colorizer } = require_colorize(); + module2.exports = (config3) => { + Colorizer.addColors(config3.colors || config3); + return config3; + }; + } +}); + +// node_modules/logform/align.js +var require_align = __commonJS({ + "node_modules/logform/align.js"(exports2, module2) { + "use strict"; + var format = require_format(); + module2.exports = format((info) => { + info.message = ` ${info.message}`; + return info; + }); + } +}); + +// node_modules/logform/errors.js +var require_errors = __commonJS({ + "node_modules/logform/errors.js"(exports2, module2) { + "use strict"; + var format = require_format(); + var { LEVEL, MESSAGE } = require_triple_beam(); + module2.exports = format((einfo, { stack, cause }) => { + if (einfo instanceof Error) { + const info = Object.assign({}, einfo, { + level: einfo.level, + [LEVEL]: einfo[LEVEL] || einfo.level, + message: einfo.message, + [MESSAGE]: einfo[MESSAGE] || einfo.message + }); + if (stack) info.stack = einfo.stack; + if (cause) info.cause = einfo.cause; + return info; } - function onerror(er2) { - debug("onerror", er2); - unpipe(); - dest.removeListener("error", onerror); - if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er2); + if (!(einfo.message instanceof Error)) return einfo; + const err = einfo.message; + Object.assign(einfo, err); + einfo.message = err.message; + einfo[MESSAGE] = err.message; + if (stack) einfo.stack = err.stack; + if (cause) einfo.cause = err.cause; + return einfo; + }); + } +}); + +// node_modules/logform/pad-levels.js +var require_pad_levels = __commonJS({ + "node_modules/logform/pad-levels.js"(exports2, module2) { + "use strict"; + var { configs, LEVEL, MESSAGE } = require_triple_beam(); + var Padder = class _Padder { + constructor(opts = { levels: configs.npm.levels }) { + this.paddings = _Padder.paddingForLevels(opts.levels, opts.filler); + this.options = opts; } - prependListener(dest, "error", onerror); - function onclose() { - dest.removeListener("finish", onfinish); - unpipe(); + /** + * Returns the maximum length of keys in the specified `levels` Object. + * @param {Object} levels Set of all levels to calculate longest level against. + * @returns {Number} Maximum length of the longest level string. + */ + static getLongestLevel(levels) { + const lvls = Object.keys(levels).map((level) => level.length); + return Math.max(...lvls); } - dest.once("close", onclose); - function onfinish() { - debug("onfinish"); - dest.removeListener("close", onclose); - unpipe(); + /** + * Returns the padding for the specified `level` assuming that the + * maximum length of all levels it's associated with is `maxLength`. + * @param {String} level Level to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @param {Number} maxLength Length of the longest level + * @returns {String} Padding string for the `level` + */ + static paddingForLevel(level, filler, maxLength) { + const targetLen = maxLength + 1 - level.length; + const rep = Math.floor(targetLen / filler.length); + const padding = `${filler}${filler.repeat(rep)}`; + return padding.slice(0, targetLen); } - dest.once("finish", onfinish); - function unpipe() { - debug("unpipe"); - src.unpipe(dest); + /** + * Returns an object with the string paddings for the given `levels` + * using the specified `filler`. + * @param {Object} levels Set of all levels to calculate padding for. + * @param {String} filler Repeatable text to use for padding. + * @returns {Object} Mapping of level to desired padding. + */ + static paddingForLevels(levels, filler = " ") { + const maxLength = _Padder.getLongestLevel(levels); + return Object.keys(levels).reduce((acc, level) => { + acc[level] = _Padder.paddingForLevel(level, filler, maxLength); + return acc; + }, {}); } - dest.emit("pipe", src); - if (!state.flowing) { - debug("pipe resume"); - src.resume(); + /** + * Prepends the padding onto the `message` based on the `LEVEL` of + * the `info`. This is based on the behavior of `winston@2` which also + * prepended the level onto the message. + * + * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201 + * + * @param {Info} info Logform info object + * @param {Object} opts Options passed along to this instance. + * @returns {Info} Modified logform info object. + */ + transform(info, opts) { + info.message = `${this.paddings[info[LEVEL]]}${info.message}`; + if (info[MESSAGE]) { + info[MESSAGE] = `${this.paddings[info[LEVEL]]}${info[MESSAGE]}`; + } + return info; } - return dest; }; - function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug("pipeOnDrain", state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, "data")) { - state.flowing = true; - flow(src); + module2.exports = (opts) => new Padder(opts); + module2.exports.Padder = module2.exports.Format = Padder; + } +}); + +// node_modules/logform/cli.js +var require_cli2 = __commonJS({ + "node_modules/logform/cli.js"(exports2, module2) { + "use strict"; + var { Colorizer } = require_colorize(); + var { Padder } = require_pad_levels(); + var { configs, MESSAGE } = require_triple_beam(); + var CliFormat = class { + constructor(opts = {}) { + if (!opts.levels) { + opts.levels = configs.cli.levels; } - }; - } - Readable2.prototype.unpipe = function(dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; - if (state.pipesCount === 0) return this; - if (state.pipesCount === 1) { - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit("unpipe", this, unpipeInfo); - return this; + this.colorizer = new Colorizer(opts); + this.padder = new Padder(opts); + this.options = opts; } - if (!dest) { - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - for (var i = 0; i < len; i++) dests[i].emit("unpipe", this, { - hasUnpiped: false - }); - return this; + /* + * function transform (info, opts) + * Attempts to both: + * 1. Pad the { level } + * 2. Colorize the { level, message } + * of the given `logform` info object depending on the `opts`. + */ + transform(info, opts) { + this.colorizer.transform( + this.padder.transform(info, opts), + opts + ); + info[MESSAGE] = `${info.level}:${info.message}`; + return info; } - var index2 = indexOf(state.pipes, dest); - if (index2 === -1) return this; - state.pipes.splice(index2, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit("unpipe", this, unpipeInfo); - return this; }; - Readable2.prototype.on = function(ev, fn2) { - var res = Stream.prototype.on.call(this, ev, fn2); - var state = this._readableState; - if (ev === "data") { - state.readableListening = this.listenerCount("readable") > 0; - if (state.flowing !== false) this.resume(); - } else if (ev === "readable") { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug("on readable", state.length, state.reading); - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); + module2.exports = (opts) => new CliFormat(opts); + module2.exports.Format = CliFormat; + } +}); + +// node_modules/logform/combine.js +var require_combine = __commonJS({ + "node_modules/logform/combine.js"(exports2, module2) { + "use strict"; + var format = require_format(); + function cascade(formats) { + if (!formats.every(isValidFormat)) { + return; + } + return (info) => { + let obj = info; + for (let i = 0; i < formats.length; i++) { + obj = formats[i].transform(obj, formats[i].options); + if (!obj) { + return false; } } + return obj; + }; + } + function isValidFormat(fmt) { + if (typeof fmt.transform !== "function") { + throw new Error([ + "No transform function found on format. Did you create a format instance?", + "const myFormat = format(formatFn);", + "const instance = myFormat();" + ].join("\n")); } - return res; + return true; + } + module2.exports = (...formats) => { + const combinedFormat = format(cascade(formats)); + const instance = combinedFormat(); + instance.Format = combinedFormat.Format; + return instance; }; - Readable2.prototype.addListener = Readable2.prototype.on; - Readable2.prototype.removeListener = function(ev, fn2) { - var res = Stream.prototype.removeListener.call(this, ev, fn2); - if (ev === "readable") { - process.nextTick(updateReadableListening, this); + module2.exports.cascade = cascade; + } +}); + +// node_modules/safe-stable-stringify/index.js +var require_safe_stable_stringify = __commonJS({ + "node_modules/safe-stable-stringify/index.js"(exports2, module2) { + "use strict"; + var { hasOwnProperty: hasOwnProperty2 } = Object.prototype; + var stringify3 = configure(); + stringify3.configure = configure; + stringify3.stringify = stringify3; + stringify3.default = stringify3; + exports2.stringify = stringify3; + exports2.configure = configure; + module2.exports = stringify3; + var strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/; + function strEscape(str) { + if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) { + return `"${str}"`; } - return res; - }; - Readable2.prototype.removeAllListeners = function(ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - if (ev === "readable" || ev === void 0) { - process.nextTick(updateReadableListening, this); + return JSON.stringify(str); + } + function sort(array, comparator) { + if (array.length > 200 || comparator) { + return array.sort(comparator); + } + for (let i = 1; i < array.length; i++) { + const currentValue = array[i]; + let position = i; + while (position !== 0 && array[position - 1] > currentValue) { + array[position] = array[position - 1]; + position--; + } + array[position] = currentValue; + } + return array; + } + var typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor( + Object.getPrototypeOf( + Object.getPrototypeOf( + new Int8Array() + ) + ), + Symbol.toStringTag + ).get; + function isTypedArrayWithEntries(value) { + return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0; + } + function stringifyTypedArray(array, separator, maximumBreadth) { + if (array.length < maximumBreadth) { + maximumBreadth = array.length; + } + const whitespace = separator === "," ? "" : " "; + let res = `"0":${whitespace}${array[0]}`; + for (let i = 1; i < maximumBreadth; i++) { + res += `${separator}"${i}":${whitespace}${array[i]}`; } return res; - }; - function updateReadableListening(self2) { - var state = self2._readableState; - state.readableListening = self2.listenerCount("readable") > 0; - if (state.resumeScheduled && !state.paused) { - state.flowing = true; - } else if (self2.listenerCount("data") > 0) { - self2.resume(); + } + function getCircularValueOption(options) { + if (hasOwnProperty2.call(options, "circularValue")) { + const circularValue = options.circularValue; + if (typeof circularValue === "string") { + return `"${circularValue}"`; + } + if (circularValue == null) { + return circularValue; + } + if (circularValue === Error || circularValue === TypeError) { + return { + toString() { + throw new TypeError("Converting circular structure to JSON"); + } + }; + } + throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined'); } + return '"[Circular]"'; } - function nReadingNextTick(self2) { - debug("readable nexttick read 0"); - self2.read(0); + function getDeterministicOption(options) { + let value; + if (hasOwnProperty2.call(options, "deterministic")) { + value = options.deterministic; + if (typeof value !== "boolean" && typeof value !== "function") { + throw new TypeError('The "deterministic" argument must be of type boolean or comparator function'); + } + } + return value === void 0 ? true : value; } - Readable2.prototype.resume = function() { - var state = this._readableState; - if (!state.flowing) { - debug("resume"); - state.flowing = !state.readableListening; - resume(this, state); + function getBooleanOption(options, key) { + let value; + if (hasOwnProperty2.call(options, key)) { + value = options[key]; + if (typeof value !== "boolean") { + throw new TypeError(`The "${key}" argument must be of type boolean`); + } } - state.paused = false; - return this; - }; - function resume(stream4, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream4, state); + return value === void 0 ? true : value; + } + function getPositiveIntegerOption(options, key) { + let value; + if (hasOwnProperty2.call(options, key)) { + value = options[key]; + if (typeof value !== "number") { + throw new TypeError(`The "${key}" argument must be of type number`); + } + if (!Number.isInteger(value)) { + throw new TypeError(`The "${key}" argument must be an integer`); + } + if (value < 1) { + throw new RangeError(`The "${key}" argument must be >= 1`); + } + } + return value === void 0 ? Infinity : value; + } + function getItemCount(number) { + if (number === 1) { + return "1 item"; } + return `${number} items`; } - function resume_(stream4, state) { - debug("resume", state.reading); - if (!state.reading) { - stream4.read(0); + function getUniqueReplacerSet(replacerArray) { + const replacerSet = /* @__PURE__ */ new Set(); + for (const value of replacerArray) { + if (typeof value === "string" || typeof value === "number") { + replacerSet.add(String(value)); + } } - state.resumeScheduled = false; - stream4.emit("resume"); - flow(stream4); - if (state.flowing && !state.reading) stream4.read(0); + return replacerSet; } - Readable2.prototype.pause = function() { - debug("call pause flowing=%j", this._readableState.flowing); - if (this._readableState.flowing !== false) { - debug("pause"); - this._readableState.flowing = false; - this.emit("pause"); + function getStrictOption(options) { + if (hasOwnProperty2.call(options, "strict")) { + const value = options.strict; + if (typeof value !== "boolean") { + throw new TypeError('The "strict" argument must be of type boolean'); + } + if (value) { + return (value2) => { + let message = `Object can not safely be stringified. Received type ${typeof value2}`; + if (typeof value2 !== "function") message += ` (${value2.toString()})`; + throw new Error(message); + }; + } } - this._readableState.paused = true; - return this; - }; - function flow(stream4) { - var state = stream4._readableState; - debug("flow", state.flowing); - while (state.flowing && stream4.read() !== null) ; } - Readable2.prototype.wrap = function(stream4) { - var _this = this; - var state = this._readableState; - var paused = false; - stream4.on("end", function() { - debug("wrapped end"); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); + function configure(options) { + options = { ...options }; + const fail = getStrictOption(options); + if (fail) { + if (options.bigint === void 0) { + options.bigint = false; } - _this.push(null); - }); - stream4.on("data", function(chunk) { - debug("wrapped data"); - if (state.decoder) chunk = state.decoder.write(chunk); - if (state.objectMode && (chunk === null || chunk === void 0)) return; - else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream4.pause(); + if (!("circularValue" in options)) { + options.circularValue = Error; } - }); - for (var i in stream4) { - if (this[i] === void 0 && typeof stream4[i] === "function") { - this[i] = /* @__PURE__ */ function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream4[method].apply(stream4, arguments); - }; - }(i); + } + const circularValue = getCircularValueOption(options); + const bigint = getBooleanOption(options, "bigint"); + const deterministic = getDeterministicOption(options); + const comparator = typeof deterministic === "function" ? deterministic : void 0; + const maximumDepth = getPositiveIntegerOption(options, "maximumDepth"); + const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth"); + function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) { + let value = parent[key]; + if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { + value = value.toJSON(key); + } + value = replacer.call(parent, key, value); + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + let res = ""; + let join2 = ","; + const originalIndentation = indentation; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + if (spacer !== "") { + indentation += spacer; + res += ` +${indentation}`; + join2 = `, +${indentation}`; + } + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += join2; + } + const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; + } + if (spacer !== "") { + res += ` +${originalIndentation}`; + } + stack.pop(); + return `[${res}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + let whitespace = ""; + let separator = ""; + if (spacer !== "") { + indentation += spacer; + join2 = `, +${indentation}`; + whitespace = " "; + } + const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (deterministic && !isTypedArrayWithEntries(value)) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key2 = keys[i]; + const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; + separator = join2; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`; + separator = join2; + } + if (spacer !== "" && separator.length > 1) { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; } } - for (var n = 0; n < kProxyEvents.length; n++) { - stream4.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } - this._read = function(n2) { - debug("wrapped _read", n2); - if (paused) { - paused = false; - stream4.resume(); + function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) { + if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { + value = value.toJSON(key); } - }; - return this; - }; - if (typeof Symbol === "function") { - Readable2.prototype[Symbol.asyncIterator] = function() { - if (createReadableStreamAsyncIterator === void 0) { - createReadableStreamAsyncIterator = require_async_iterator(); + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + const originalIndentation = indentation; + let res = ""; + let join2 = ","; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + if (spacer !== "") { + indentation += spacer; + res += ` +${indentation}`; + join2 = `, +${indentation}`; + } + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += join2; + } + const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `${join2}"... ${getItemCount(removedKeys)} not stringified"`; + } + if (spacer !== "") { + res += ` +${originalIndentation}`; + } + stack.pop(); + return `[${res}]`; + } + stack.push(value); + let whitespace = ""; + if (spacer !== "") { + indentation += spacer; + join2 = `, +${indentation}`; + whitespace = " "; + } + let separator = ""; + for (const key2 of replacer) { + const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; + separator = join2; + } + } + if (spacer !== "" && separator.length > 1) { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; } - return createReadableStreamAsyncIterator(this); - }; - } - Object.defineProperty(Readable2.prototype, "readableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } - }); - Object.defineProperty(Readable2.prototype, "readableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; } - }); - Object.defineProperty(Readable2.prototype, "readableFlowing", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; + function stringifyIndent(key, value, stack, spacer, indentation) { + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (typeof value.toJSON === "function") { + value = value.toJSON(key); + if (typeof value !== "object") { + return stringifyIndent(key, value, stack, spacer, indentation); + } + if (value === null) { + return "null"; + } + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + const originalIndentation = indentation; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + indentation += spacer; + let res2 = ` +${indentation}`; + const join3 = `, +${indentation}`; + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation); + res2 += tmp2 !== void 0 ? tmp2 : "null"; + res2 += join3; + } + const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation); + res2 += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res2 += `${join3}"... ${getItemCount(removedKeys)} not stringified"`; + } + res2 += ` +${originalIndentation}`; + stack.pop(); + return `[${res2}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + indentation += spacer; + const join2 = `, +${indentation}`; + let res = ""; + let separator = ""; + let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (isTypedArrayWithEntries(value)) { + res += stringifyTypedArray(value, join2, maximumBreadth); + keys = keys.slice(value.length); + maximumPropertiesToStringify -= value.length; + separator = join2; + } + if (deterministic) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key2 = keys[i]; + const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}: ${tmp}`; + separator = join2; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`; + separator = join2; + } + if (separator !== "") { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; } } - }); - Readable2._fromList = fromList; - Object.defineProperty(Readable2.prototype, "readableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } - }); - function fromList(n, state) { - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift(); - else if (!n || n >= state.length) { - if (state.decoder) ret = state.buffer.join(""); - else if (state.buffer.length === 1) ret = state.buffer.first(); - else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - ret = state.buffer.consume(n, state.decoder); - } - return ret; - } - function endReadable(stream4) { - var state = stream4._readableState; - debug("endReadable", state.endEmitted); - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream4); + function stringifySimple(key, value, stack) { + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (typeof value.toJSON === "function") { + value = value.toJSON(key); + if (typeof value !== "object") { + return stringifySimple(key, value, stack); + } + if (value === null) { + return "null"; + } + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + let res = ""; + const hasLength = value.length !== void 0; + if (hasLength && Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i = 0; + for (; i < maximumValuesToStringify - 1; i++) { + const tmp2 = stringifySimple(String(i), value[i], stack); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += ","; + } + const tmp = stringifySimple(String(i), value[i], stack); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `,"... ${getItemCount(removedKeys)} not stringified"`; + } + stack.pop(); + return `[${res}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + let separator = ""; + let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (hasLength && isTypedArrayWithEntries(value)) { + res += stringifyTypedArray(value, ",", maximumBreadth); + keys = keys.slice(value.length); + maximumPropertiesToStringify -= value.length; + separator = ","; + } + if (deterministic) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i = 0; i < maximumPropertiesToStringify; i++) { + const key2 = keys[i]; + const tmp = stringifySimple(key2, value[key2], stack); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${tmp}`; + separator = ","; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } } - } - function endReadableNT(state, stream4) { - debug("endReadableNT", state.endEmitted, state.length); - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream4.readable = false; - stream4.emit("end"); - if (state.autoDestroy) { - var wState = stream4._writableState; - if (!wState || wState.autoDestroy && wState.finished) { - stream4.destroy(); + function stringify4(value, replacer, space) { + if (arguments.length > 1) { + let spacer = ""; + if (typeof space === "number") { + spacer = " ".repeat(Math.min(space, 10)); + } else if (typeof space === "string") { + spacer = space.slice(0, 10); + } + if (replacer != null) { + if (typeof replacer === "function") { + return stringifyFnReplacer("", { "": value }, [], replacer, spacer, ""); + } + if (Array.isArray(replacer)) { + return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, ""); + } + } + if (spacer.length !== 0) { + return stringifyIndent("", value, [], spacer, ""); } } + return stringifySimple("", value, []); } + return stringify4; } - if (typeof Symbol === "function") { - Readable2.from = function(iterable, opts) { - if (from5 === void 0) { - from5 = require_from(); - } - return from5(Readable2, iterable, opts); - }; + } +}); + +// node_modules/logform/json.js +var require_json = __commonJS({ + "node_modules/logform/json.js"(exports2, module2) { + "use strict"; + var format = require_format(); + var { MESSAGE } = require_triple_beam(); + var stringify3 = require_safe_stable_stringify(); + function replacer(key, value) { + if (typeof value === "bigint") + return value.toString(); + return value; } - function indexOf(xs2, x2) { - for (var i = 0, l = xs2.length; i < l; i++) { - if (xs2[i] === x2) return i; + module2.exports = format((info, opts) => { + const jsonStringify = stringify3.configure(opts); + info[MESSAGE] = jsonStringify(info, opts.replacer || replacer, opts.space); + return info; + }); + } +}); + +// node_modules/logform/label.js +var require_label = __commonJS({ + "node_modules/logform/label.js"(exports2, module2) { + "use strict"; + var format = require_format(); + module2.exports = format((info, opts) => { + if (opts.message) { + info.message = `[${opts.label}] ${info.message}`; + return info; } - return -1; - } + info.label = opts.label; + return info; + }); } }); -// node_modules/readable-stream/lib/_stream_duplex.js -var require_stream_duplex = __commonJS({ - "node_modules/readable-stream/lib/_stream_duplex.js"(exports2, module2) { +// node_modules/logform/logstash.js +var require_logstash = __commonJS({ + "node_modules/logform/logstash.js"(exports2, module2) { "use strict"; - var objectKeys = Object.keys || function(obj) { - var keys2 = []; - for (var key in obj) keys2.push(key); - return keys2; - }; - module2.exports = Duplex; - var Readable2 = require_stream_readable(); - var Writable = require_stream_writable(); - require_inherits()(Duplex, Readable2); - { - keys = objectKeys(Writable.prototype); - for (v = 0; v < keys.length; v++) { - method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + var format = require_format(); + var { MESSAGE } = require_triple_beam(); + var jsonStringify = require_safe_stable_stringify(); + module2.exports = format((info) => { + const logstash = {}; + if (info.message) { + logstash["@message"] = info.message; + delete info.message; } - } - var keys; - var method; - var v; - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable2.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once("end", onend); - } + if (info.timestamp) { + logstash["@timestamp"] = info.timestamp; + delete info.timestamp; } + logstash["@fields"] = info; + info[MESSAGE] = jsonStringify(logstash); + return info; + }); + } +}); + +// node_modules/logform/metadata.js +var require_metadata = __commonJS({ + "node_modules/logform/metadata.js"(exports2, module2) { + "use strict"; + var format = require_format(); + function fillExcept(info, fillExceptKeys, metadataKey) { + const savedKeys = fillExceptKeys.reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + const metadata = Object.keys(info).reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + Object.assign(info, savedKeys, { + [metadataKey]: metadata + }); + return info; } - Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; + function fillWith(info, fillWithKeys, metadataKey) { + info[metadataKey] = fillWithKeys.reduce((acc, key) => { + acc[key] = info[key]; + delete info[key]; + return acc; + }, {}); + return info; + } + module2.exports = format((info, opts = {}) => { + let metadataKey = "metadata"; + if (opts.key) { + metadataKey = opts.key; } - }); - Object.defineProperty(Duplex.prototype, "writableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); + let fillExceptKeys = []; + if (!opts.fillExcept && !opts.fillWith) { + fillExceptKeys.push("level"); + fillExceptKeys.push("message"); } - }); - Object.defineProperty(Duplex.prototype, "writableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; + if (opts.fillExcept) { + fillExceptKeys = opts.fillExcept; } - }); - function onend() { - if (this._writableState.ended) return; - process.nextTick(onEndNT, this); - } - function onEndNT(self2) { - self2.end(); - } - Object.defineProperty(Duplex.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === void 0 || this._writableState === void 0) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - if (this._readableState === void 0 || this._writableState === void 0) { - return; - } - this._readableState.destroyed = value; - this._writableState.destroyed = value; + if (fillExceptKeys.length > 0) { + return fillExcept(info, fillExceptKeys, metadataKey); } + if (opts.fillWith) { + return fillWith(info, opts.fillWith, metadataKey); + } + return info; }); } }); -// node_modules/readable-stream/lib/_stream_writable.js -var require_stream_writable = __commonJS({ - "node_modules/readable-stream/lib/_stream_writable.js"(exports2, module2) { - "use strict"; - module2.exports = Writable; - function CorkedRequest(state) { - var _this = this; - this.next = null; - this.entry = null; - this.finish = function() { - onCorkedFinish(_this, state); - }; - } - var Duplex; - Writable.WritableState = WritableState; - var internalUtil = { - deprecate: require_node2() - }; - var Stream = require_stream(); - var Buffer2 = __require("buffer").Buffer; - var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { - }; - function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); - } - function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; - } - var destroyImpl = require_destroy(); - var _require = require_state2(); - var getHighWaterMark = _require.getHighWaterMark; - var _require$codes = require_errors2().codes; - var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; - var ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE; - var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - var ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES; - var ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END; - var ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - var errorOrDestroy = destroyImpl.errorOrDestroy; - require_inherits()(Writable, Stream); - function nop() { - } - function WritableState(options, stream4, isDuplex) { - Duplex = Duplex || require_stream_duplex(); +// node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/ms/index.js"(exports2, module2) { + var s = 1e3; + var m2 = s * 60; + var h = m2 * 60; + var d = h * 24; + var w2 = d * 7; + var y2 = d * 365.25; + module2.exports = function(val, options) { options = options || {}; - if (typeof isDuplex !== "boolean") isDuplex = stream4 instanceof Duplex; - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex); - this.finalCalled = false; - this.needDrain = false; - this.ending = false; - this.ended = false; - this.finished = false; - this.destroyed = false; - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - this.defaultEncoding = options.defaultEncoding || "utf8"; - this.length = 0; - this.writing = false; - this.corked = 0; - this.sync = true; - this.bufferProcessing = false; - this.onwrite = function(er2) { - onwrite(stream4, er2); - }; - this.writecb = null; - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; - this.pendingcb = 0; - this.prefinished = false; - this.errorEmitted = false; - this.emitClose = options.emitClose !== false; - this.autoDestroy = !!options.autoDestroy; - this.bufferedRequestCount = 0; - this.corkedRequestsFree = new CorkedRequest(this); - } - WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; + var type = typeof val; + if (type === "string" && val.length > 0) { + return parse(val); + } else if (type === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); } - return out; + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) + ); }; - (function() { - try { - Object.defineProperty(WritableState.prototype, "buffer", { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") - }); - } catch (_) { + function parse(str) { + str = String(str); + if (str.length > 100) { + return; } - })(); - var realHasInstance; - if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); - } else { - realHasInstance = function realHasInstance2(object) { - return object instanceof this; - }; - } - function Writable(options) { - Duplex = Duplex || require_stream_duplex(); - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); - this.writable = true; - if (options) { - if (typeof options.write === "function") this._write = options.write; - if (typeof options.writev === "function") this._writev = options.writev; - if (typeof options.destroy === "function") this._destroy = options.destroy; - if (typeof options.final === "function") this._final = options.final; + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || "ms").toLowerCase(); + switch (type) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y2; + case "weeks": + case "week": + case "w": + return n * w2; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m2; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; } - Stream.call(this); - } - Writable.prototype.pipe = function() { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); - }; - function writeAfterEnd(stream4, cb) { - var er2 = new ERR_STREAM_WRITE_AFTER_END(); - errorOrDestroy(stream4, er2); - process.nextTick(cb, er2); } - function validChunk(stream4, state, chunk, cb) { - var er2; - if (chunk === null) { - er2 = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== "string" && !state.objectMode) { - er2 = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; } - if (er2) { - errorOrDestroy(stream4, er2); - process.nextTick(cb, er2); - return false; + if (msAbs >= h) { + return Math.round(ms / h) + "h"; } - return true; - } - Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); - if (isBuf && !Buffer2.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); + if (msAbs >= m2) { + return Math.round(ms / m2) + "m"; } - if (typeof encoding === "function") { - cb = encoding; - encoding = null; + if (msAbs >= s) { + return Math.round(ms / s) + "s"; } - if (isBuf) encoding = "buffer"; - else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== "function") cb = nop; - if (state.ending) writeAfterEnd(this, cb); - else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + return ms + "ms"; + } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); } - return ret; - }; - Writable.prototype.cork = function() { - this._writableState.corked++; - }; - Writable.prototype.uncork = function() { - var state = this._writableState; - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); } - }; - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - if (typeof encoding === "string") encoding = encoding.toLowerCase(); - if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - Object.defineProperty(Writable.prototype, "writableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); + if (msAbs >= m2) { + return plural(ms, msAbs, m2, "minute"); } - }); - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") { - chunk = Buffer2.from(chunk, encoding); + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); } - return chunk; + return ms + " ms"; } - Object.defineProperty(Writable.prototype, "writableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } + } +}); + +// node_modules/logform/ms.js +var require_ms2 = __commonJS({ + "node_modules/logform/ms.js"(exports2, module2) { + "use strict"; + var format = require_format(); + var ms = require_ms(); + module2.exports = format((info) => { + const curr = +/* @__PURE__ */ new Date(); + exports2.diff = curr - (exports2.prevTime || curr); + exports2.prevTime = curr; + info.ms = `+${ms(exports2.diff)}`; + return info; + }); + } +}); + +// node_modules/logform/pretty-print.js +var require_pretty_print = __commonJS({ + "node_modules/logform/pretty-print.js"(exports2, module2) { + "use strict"; + var inspect = __require("util").inspect; + var format = require_format(); + var { LEVEL, MESSAGE, SPLAT } = require_triple_beam(); + module2.exports = format((info, opts = {}) => { + const stripped = Object.assign({}, info); + delete stripped[LEVEL]; + delete stripped[MESSAGE]; + delete stripped[SPLAT]; + info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize); + return info; + }); + } +}); + +// node_modules/logform/printf.js +var require_printf = __commonJS({ + "node_modules/logform/printf.js"(exports2, module2) { + "use strict"; + var { MESSAGE } = require_triple_beam(); + var Printf = class { + constructor(templateFn) { + this.template = templateFn; + } + transform(info) { + info[MESSAGE] = this.template(info); + return info; + } + }; + module2.exports = (opts) => new Printf(opts); + module2.exports.Printf = module2.exports.Format = Printf; + } +}); + +// node_modules/logform/simple.js +var require_simple = __commonJS({ + "node_modules/logform/simple.js"(exports2, module2) { + "use strict"; + var format = require_format(); + var { MESSAGE } = require_triple_beam(); + var jsonStringify = require_safe_stable_stringify(); + module2.exports = format((info) => { + const stringifiedRest = jsonStringify(Object.assign({}, info, { + level: void 0, + message: void 0, + splat: void 0 + })); + const padding = info.padding && info.padding[info.level] || ""; + if (stringifiedRest !== "{}") { + info[MESSAGE] = `${info.level}:${padding} ${info.message} ${stringifiedRest}`; + } else { + info[MESSAGE] = `${info.level}:${padding} ${info.message}`; } + return info; }); - function writeOrBuffer(stream4, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = "buffer"; - chunk = newChunk; + } +}); + +// node_modules/logform/splat.js +var require_splat = __commonJS({ + "node_modules/logform/splat.js"(exports2, module2) { + "use strict"; + var util3 = __require("util"); + var { SPLAT } = require_triple_beam(); + var formatRegExp = /%[scdjifoO%]/g; + var escapedPercent = /%%/g; + var Splatter = class { + constructor(opts) { + this.options = opts; + } + /** + * Check to see if tokens <= splat.length, assign { splat, meta } into the + * `info` accordingly, and write to this instance. + * + * @param {Info} info Logform info message. + * @param {String[]} tokens Set of string interpolation tokens. + * @returns {Info} Modified info message + * @private + */ + _splat(info, tokens) { + const msg = info.message; + const splat = info[SPLAT] || info.splat || []; + const percents = msg.match(escapedPercent); + const escapes = percents && percents.length || 0; + const expectedSplat = tokens.length - escapes; + const extraSplat = expectedSplat - splat.length; + const metas = extraSplat < 0 ? splat.splice(extraSplat, -1 * extraSplat) : []; + const metalen = metas.length; + if (metalen) { + for (let i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } } + info.message = util3.format(msg, ...splat); + return info; } - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; - if (!ret) state.needDrain = true; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk, - encoding, - isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; + /** + * Transforms the `info` message by using `util.format` to complete + * any `info.message` provided it has string interpolation tokens. + * If no tokens exist then `info` is immutable. + * + * @param {Info} info Logform info message. + * @param {Object} opts Options for this instance. + * @returns {Info} Modified info message + */ + transform(info) { + const msg = info.message; + const splat = info[SPLAT] || info.splat; + if (!splat || !splat.length) { + return info; } - state.bufferedRequestCount += 1; - } else { - doWrite(stream4, state, false, len, chunk, encoding, cb); + const tokens = msg && msg.match && msg.match(formatRegExp); + if (!tokens && (splat || splat.length)) { + const metas = splat.length > 1 ? splat.splice(0) : splat; + const metalen = metas.length; + if (metalen) { + for (let i = 0; i < metalen; i++) { + Object.assign(info, metas[i]); + } + } + return info; + } + if (tokens) { + return this._splat(info, tokens); + } + return info; } - return ret; - } - function doWrite(stream4, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED("write")); - else if (writev) stream4._writev(chunk, state.onwrite); - else stream4._write(chunk, encoding, state.onwrite); - state.sync = false; - } - function onwriteError(stream4, state, sync, er2, cb) { - --state.pendingcb; - if (sync) { - process.nextTick(cb, er2); - process.nextTick(finishMaybe, stream4, state); - stream4._writableState.errorEmitted = true; - errorOrDestroy(stream4, er2); - } else { - cb(er2); - stream4._writableState.errorEmitted = true; - errorOrDestroy(stream4, er2); - finishMaybe(stream4, state); + }; + module2.exports = (opts) => new Splatter(opts); + } +}); + +// node_modules/fecha/lib/fecha.umd.js +var require_fecha_umd = __commonJS({ + "node_modules/fecha/lib/fecha.umd.js"(exports2, module2) { + (function(global2, factory) { + typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : factory(global2.fecha = {}); + })(exports2, function(exports3) { + "use strict"; + var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; + var twoDigitsOptional = "\\d\\d?"; + var twoDigits = "\\d\\d"; + var threeDigits = "\\d{3}"; + var fourDigits = "\\d{4}"; + var word = "[^\\s]+"; + var literal = /\[([^]*?)\]/gm; + function shorten2(arr, sLen) { + var newArr = []; + for (var i = 0, len = arr.length; i < len; i++) { + newArr.push(arr[i].substr(0, sLen)); + } + return newArr; } - } - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } - function onwrite(stream4, er2) { - var state = stream4._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er2) onwriteError(stream4, state, sync, er2, cb); - else { - var finished = needFinish(state) || stream4.destroyed; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream4, state); + var monthUpdate = function(arrName) { + return function(v, i18n) { + var lowerCaseArr = i18n[arrName].map(function(v2) { + return v2.toLowerCase(); + }); + var index2 = lowerCaseArr.indexOf(v.toLowerCase()); + if (index2 > -1) { + return index2; + } + return null; + }; + }; + function assign(origObj) { + var args = []; + for (var _i2 = 1; _i2 < arguments.length; _i2++) { + args[_i2 - 1] = arguments[_i2]; } - if (sync) { - process.nextTick(afterWrite, stream4, state, finished, cb); - } else { - afterWrite(stream4, state, finished, cb); + for (var _a2 = 0, args_1 = args; _a2 < args_1.length; _a2++) { + var obj = args_1[_a2]; + for (var key in obj) { + origObj[key] = obj[key]; + } } + return origObj; } - } - function afterWrite(stream4, state, finished, cb) { - if (!finished) onwriteDrain(stream4, state); - state.pendingcb--; - cb(); - finishMaybe(stream4, state); - } - function onwriteDrain(stream4, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream4.emit("drain"); - } - } - function clearBuffer(stream4, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - if (stream4._writev && entry && entry.next) { - var l = state.bufferedRequestCount; - var buffer2 = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - while (entry) { - buffer2[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; + var dayNames = [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ]; + var monthNames = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ]; + var monthNamesShort = shorten2(monthNames, 3); + var dayNamesShort = shorten2(dayNames, 3); + var defaultI18n = { + dayNamesShort, + dayNames, + monthNamesShort, + monthNames, + amPm: ["am", "pm"], + DoFn: function(dayOfMonth) { + return dayOfMonth + ["th", "st", "nd", "rd"][dayOfMonth % 10 > 3 ? 0 : (dayOfMonth - dayOfMonth % 10 !== 10 ? 1 : 0) * dayOfMonth % 10]; } - buffer2.allBuffers = allBuffers; - doWrite(stream4, state, true, state.length, buffer2, "", holder.finish); - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); + }; + var globalI18n = assign({}, defaultI18n); + var setGlobalDateI18n = function(i18n) { + return globalI18n = assign(globalI18n, i18n); + }; + var regexEscape = function(str) { + return str.replace(/[|\\{()[^$+*?.-]/g, "\\$&"); + }; + var pad4 = function(val, len) { + if (len === void 0) { + len = 2; } - state.bufferedRequestCount = 0; - } else { - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream4, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - if (state.writing) { - break; + val = String(val); + while (val.length < len) { + val = "0" + val; + } + return val; + }; + var formatFlags = { + D: function(dateObj) { + return String(dateObj.getDate()); + }, + DD: function(dateObj) { + return pad4(dateObj.getDate()); + }, + Do: function(dateObj, i18n) { + return i18n.DoFn(dateObj.getDate()); + }, + d: function(dateObj) { + return String(dateObj.getDay()); + }, + dd: function(dateObj) { + return pad4(dateObj.getDay()); + }, + ddd: function(dateObj, i18n) { + return i18n.dayNamesShort[dateObj.getDay()]; + }, + dddd: function(dateObj, i18n) { + return i18n.dayNames[dateObj.getDay()]; + }, + M: function(dateObj) { + return String(dateObj.getMonth() + 1); + }, + MM: function(dateObj) { + return pad4(dateObj.getMonth() + 1); + }, + MMM: function(dateObj, i18n) { + return i18n.monthNamesShort[dateObj.getMonth()]; + }, + MMMM: function(dateObj, i18n) { + return i18n.monthNames[dateObj.getMonth()]; + }, + YY: function(dateObj) { + return pad4(String(dateObj.getFullYear()), 4).substr(2); + }, + YYYY: function(dateObj) { + return pad4(dateObj.getFullYear(), 4); + }, + h: function(dateObj) { + return String(dateObj.getHours() % 12 || 12); + }, + hh: function(dateObj) { + return pad4(dateObj.getHours() % 12 || 12); + }, + H: function(dateObj) { + return String(dateObj.getHours()); + }, + HH: function(dateObj) { + return pad4(dateObj.getHours()); + }, + m: function(dateObj) { + return String(dateObj.getMinutes()); + }, + mm: function(dateObj) { + return pad4(dateObj.getMinutes()); + }, + s: function(dateObj) { + return String(dateObj.getSeconds()); + }, + ss: function(dateObj) { + return pad4(dateObj.getSeconds()); + }, + S: function(dateObj) { + return String(Math.round(dateObj.getMilliseconds() / 100)); + }, + SS: function(dateObj) { + return pad4(Math.round(dateObj.getMilliseconds() / 10), 2); + }, + SSS: function(dateObj) { + return pad4(dateObj.getMilliseconds(), 3); + }, + a: function(dateObj, i18n) { + return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1]; + }, + A: function(dateObj, i18n) { + return dateObj.getHours() < 12 ? i18n.amPm[0].toUpperCase() : i18n.amPm[1].toUpperCase(); + }, + ZZ: function(dateObj) { + var offset = dateObj.getTimezoneOffset(); + return (offset > 0 ? "-" : "+") + pad4(Math.floor(Math.abs(offset) / 60) * 100 + Math.abs(offset) % 60, 4); + }, + Z: function(dateObj) { + var offset = dateObj.getTimezoneOffset(); + return (offset > 0 ? "-" : "+") + pad4(Math.floor(Math.abs(offset) / 60), 2) + ":" + pad4(Math.abs(offset) % 60, 2); + } + }; + var monthParse = function(v) { + return +v - 1; + }; + var emptyDigits = [null, twoDigitsOptional]; + var emptyWord = [null, word]; + var amPm = [ + "isPm", + word, + function(v, i18n) { + var val = v.toLowerCase(); + if (val === i18n.amPm[0]) { + return 0; + } else if (val === i18n.amPm[1]) { + return 1; + } + return null; + } + ]; + var timezoneOffset = [ + "timezoneOffset", + "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?", + function(v) { + var parts = (v + "").match(/([+-]|\d\d)/gi); + if (parts) { + var minutes = +parts[1] * 60 + parseInt(parts[2], 10); + return parts[0] === "+" ? minutes : -minutes; + } + return 0; + } + ]; + var parseFlags = { + D: ["day", twoDigitsOptional], + DD: ["day", twoDigits], + Do: ["day", twoDigitsOptional + word, function(v) { + return parseInt(v, 10); + }], + M: ["month", twoDigitsOptional, monthParse], + MM: ["month", twoDigits, monthParse], + YY: [ + "year", + twoDigits, + function(v) { + var now = /* @__PURE__ */ new Date(); + var cent = +("" + now.getFullYear()).substr(0, 2); + return +("" + (+v > 68 ? cent - 1 : cent) + v); + } + ], + h: ["hour", twoDigitsOptional, void 0, "isPm"], + hh: ["hour", twoDigits, void 0, "isPm"], + H: ["hour", twoDigitsOptional], + HH: ["hour", twoDigits], + m: ["minute", twoDigitsOptional], + mm: ["minute", twoDigits], + s: ["second", twoDigitsOptional], + ss: ["second", twoDigits], + YYYY: ["year", fourDigits], + S: ["millisecond", "\\d", function(v) { + return +v * 100; + }], + SS: ["millisecond", twoDigits, function(v) { + return +v * 10; + }], + SSS: ["millisecond", threeDigits], + d: emptyDigits, + dd: emptyDigits, + ddd: emptyWord, + dddd: emptyWord, + MMM: ["month", word, monthUpdate("monthNamesShort")], + MMMM: ["month", word, monthUpdate("monthNames")], + a: amPm, + A: amPm, + ZZ: timezoneOffset, + Z: timezoneOffset + }; + var globalMasks = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + isoDate: "YYYY-MM-DD", + isoDateTime: "YYYY-MM-DDTHH:mm:ssZ", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" + }; + var setGlobalDateMasks = function(masks) { + return assign(globalMasks, masks); + }; + var format = function(dateObj, mask, i18n) { + if (mask === void 0) { + mask = globalMasks["default"]; + } + if (i18n === void 0) { + i18n = {}; + } + if (typeof dateObj === "number") { + dateObj = new Date(dateObj); + } + if (Object.prototype.toString.call(dateObj) !== "[object Date]" || isNaN(dateObj.getTime())) { + throw new Error("Invalid Date pass to format"); + } + mask = globalMasks[mask] || mask; + var literals = []; + mask = mask.replace(literal, function($0, $1) { + literals.push($1); + return "@@@"; + }); + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + mask = mask.replace(token, function($0) { + return formatFlags[$0](dateObj, combinedI18nSettings); + }); + return mask.replace(/@@@/g, function() { + return literals.shift(); + }); + }; + function parse(dateStr, format2, i18n) { + if (i18n === void 0) { + i18n = {}; + } + if (typeof format2 !== "string") { + throw new Error("Invalid format in fecha parse"); + } + format2 = globalMasks[format2] || format2; + if (dateStr.length > 1e3) { + return null; + } + var today = /* @__PURE__ */ new Date(); + var dateInfo = { + year: today.getFullYear(), + month: 0, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + isPm: null, + timezoneOffset: null + }; + var parseInfo = []; + var literals = []; + var newFormat = format2.replace(literal, function($0, $1) { + literals.push(regexEscape($1)); + return "@@@"; + }); + var specifiedFields = {}; + var requiredFields = {}; + newFormat = regexEscape(newFormat).replace(token, function($0) { + var info = parseFlags[$0]; + var field2 = info[0], regex = info[1], requiredField = info[3]; + if (specifiedFields[field2]) { + throw new Error("Invalid format. " + field2 + " specified twice in format"); + } + specifiedFields[field2] = true; + if (requiredField) { + requiredFields[requiredField] = true; } + parseInfo.push(info); + return "(" + regex + ")"; + }); + Object.keys(requiredFields).forEach(function(field2) { + if (!specifiedFields[field2]) { + throw new Error("Invalid format. " + field2 + " is required in specified format"); + } + }); + newFormat = newFormat.replace(/@@@/g, function() { + return literals.shift(); + }); + var matches = dateStr.match(new RegExp(newFormat, "i")); + if (!matches) { + return null; } - if (entry === null) state.lastBufferedRequest = null; - } - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - Writable.prototype._write = function(chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); - }; - Writable.prototype._writev = null; - Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - if (typeof chunk === "function") { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === "function") { - cb = encoding; - encoding = null; - } - if (chunk !== null && chunk !== void 0) this.write(chunk, encoding); - if (state.corked) { - state.corked = 1; - this.uncork(); - } - if (!state.ending) endWritable(this, state, cb); - return this; - }; - Object.defineProperty(Writable.prototype, "writableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } - }); - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } - function callFinal(stream4, state) { - stream4._final(function(err) { - state.pendingcb--; - if (err) { - errorOrDestroy(stream4, err); + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + for (var i = 1; i < matches.length; i++) { + var _a2 = parseInfo[i - 1], field = _a2[0], parser = _a2[2]; + var value = parser ? parser(matches[i], combinedI18nSettings) : +matches[i]; + if (value == null) { + return null; + } + dateInfo[field] = value; } - state.prefinished = true; - stream4.emit("prefinish"); - finishMaybe(stream4, state); - }); - } - function prefinish(stream4, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream4._final === "function" && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream4, state); - } else { - state.prefinished = true; - stream4.emit("prefinish"); + if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) { + dateInfo.hour = +dateInfo.hour + 12; + } else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) { + dateInfo.hour = 0; } - } - } - function finishMaybe(stream4, state) { - var need = needFinish(state); - if (need) { - prefinish(stream4, state); - if (state.pendingcb === 0) { - state.finished = true; - stream4.emit("finish"); - if (state.autoDestroy) { - var rState = stream4._readableState; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream4.destroy(); + var dateTZ; + if (dateInfo.timezoneOffset == null) { + dateTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond); + var validateFields = [ + ["month", "getMonth"], + ["day", "getDate"], + ["hour", "getHours"], + ["minute", "getMinutes"], + ["second", "getSeconds"] + ]; + for (var i = 0, len = validateFields.length; i < len; i++) { + if (specifiedFields[validateFields[i][0]] && dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]()) { + return null; } } + } else { + dateTZ = new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond)); + if (dateInfo.month > 11 || dateInfo.month < 0 || dateInfo.day > 31 || dateInfo.day < 1 || dateInfo.hour > 23 || dateInfo.hour < 0 || dateInfo.minute > 59 || dateInfo.minute < 0 || dateInfo.second > 59 || dateInfo.second < 0) { + return null; + } } + return dateTZ; } - return need; - } - function endWritable(stream4, state, cb) { - state.ending = true; - finishMaybe(stream4, state); - if (cb) { - if (state.finished) process.nextTick(cb); - else stream4.once("finish", cb); + var fecha = { + format, + parse, + defaultI18n, + setGlobalDateI18n, + setGlobalDateMasks + }; + exports3.assign = assign; + exports3.default = fecha; + exports3.format = format; + exports3.parse = parse; + exports3.defaultI18n = defaultI18n; + exports3.setGlobalDateI18n = setGlobalDateI18n; + exports3.setGlobalDateMasks = setGlobalDateMasks; + Object.defineProperty(exports3, "__esModule", { value: true }); + }); + } +}); + +// node_modules/logform/timestamp.js +var require_timestamp = __commonJS({ + "node_modules/logform/timestamp.js"(exports2, module2) { + "use strict"; + var fecha = require_fecha_umd(); + var format = require_format(); + module2.exports = format((info, opts = {}) => { + if (opts.format) { + info.timestamp = typeof opts.format === "function" ? opts.format() : fecha.format(/* @__PURE__ */ new Date(), opts.format); } - state.ended = true; - stream4.writable = false; - } - function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; + if (!info.timestamp) { + info.timestamp = (/* @__PURE__ */ new Date()).toISOString(); } - state.corkedRequestsFree.next = corkReq; - } - Object.defineProperty(Writable.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === void 0) { - return false; - } - return this._writableState.destroyed; - }, - set: function set(value) { - if (!this._writableState) { - return; - } - this._writableState.destroyed = value; + if (opts.alias) { + info[opts.alias] = info.timestamp; } + return info; }); - Writable.prototype.destroy = destroyImpl.destroy; - Writable.prototype._undestroy = destroyImpl.undestroy; - Writable.prototype._destroy = function(err, cb) { - cb(err); - }; } }); -// node_modules/winston-transport/modern.js -var require_modern = __commonJS({ - "node_modules/winston-transport/modern.js"(exports2, module2) { +// node_modules/logform/uncolorize.js +var require_uncolorize = __commonJS({ + "node_modules/logform/uncolorize.js"(exports2, module2) { "use strict"; - var util3 = __require("util"); - var Writable = require_stream_writable(); - var { LEVEL } = require_triple_beam(); - var TransportStream = module2.exports = function TransportStream2(options = {}) { - Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); - this.format = options.format; - this.level = options.level; - this.handleExceptions = options.handleExceptions; - this.handleRejections = options.handleRejections; - this.silent = options.silent; - if (options.log) this.log = options.log; - if (options.logv) this.logv = options.logv; - if (options.close) this.close = options.close; - this.once("pipe", (logger) => { - this.levels = logger.levels; - this.parent = logger; - }); - this.once("unpipe", (src) => { - if (src === this.parent) { - this.parent = null; - if (this.close) { - this.close(); - } - } - }); - }; - util3.inherits(TransportStream, Writable); - TransportStream.prototype._write = function _write(info, enc, callback) { - if (this.silent || info.exception === true && !this.handleExceptions) { - return callback(null); - } - const level = this.level || this.parent && this.parent.level; - if (!level || this.levels[level] >= this.levels[info[LEVEL]]) { - if (info && !this.format) { - return this.log(info, callback); - } - let errState; - let transformed; - try { - transformed = this.format.transform(Object.assign({}, info), this.format.options); - } catch (err) { - errState = err; - } - if (errState || !transformed) { - callback(); - if (errState) throw errState; - return; - } - return this.log(transformed, callback); - } - this._writableState.sync = false; - return callback(null); - }; - TransportStream.prototype._writev = function _writev(chunks, callback) { - if (this.logv) { - const infos = chunks.filter(this._accept, this); - if (!infos.length) { - return callback(null); - } - return this.logv(infos, callback); + var colors = require_safe(); + var format = require_format(); + var { MESSAGE } = require_triple_beam(); + module2.exports = format((info, opts) => { + if (opts.level !== false) { + info.level = colors.strip(info.level); } - for (let i = 0; i < chunks.length; i++) { - if (!this._accept(chunks[i])) continue; - if (chunks[i].chunk && !this.format) { - this.log(chunks[i].chunk, chunks[i].callback); - continue; - } - let errState; - let transformed; - try { - transformed = this.format.transform( - Object.assign({}, chunks[i].chunk), - this.format.options - ); - } catch (err) { - errState = err; - } - if (errState || !transformed) { - chunks[i].callback(); - if (errState) { - callback(null); - throw errState; - } - } else { - this.log(transformed, chunks[i].callback); - } + if (opts.message !== false) { + info.message = colors.strip(String(info.message)); } - return callback(null); - }; - TransportStream.prototype._accept = function _accept(write) { - const info = write.chunk; - if (this.silent) { - return false; + if (opts.raw !== false && info[MESSAGE]) { + info[MESSAGE] = colors.strip(String(info[MESSAGE])); } - const level = this.level || this.parent && this.parent.level; - if (info.exception === true || !level || this.levels[level] >= this.levels[info[LEVEL]]) { - if (this.handleExceptions || info.exception !== true) { - return true; - } + return info; + }); + } +}); + +// node_modules/logform/index.js +var require_logform = __commonJS({ + "node_modules/logform/index.js"(exports2) { + "use strict"; + var format = exports2.format = require_format(); + exports2.levels = require_levels(); + function exposeFormat(name, requireFormat) { + Object.defineProperty(format, name, { + get() { + return requireFormat(); + }, + configurable: true + }); + } + exposeFormat("align", function() { + return require_align(); + }); + exposeFormat("errors", function() { + return require_errors(); + }); + exposeFormat("cli", function() { + return require_cli2(); + }); + exposeFormat("combine", function() { + return require_combine(); + }); + exposeFormat("colorize", function() { + return require_colorize(); + }); + exposeFormat("json", function() { + return require_json(); + }); + exposeFormat("label", function() { + return require_label(); + }); + exposeFormat("logstash", function() { + return require_logstash(); + }); + exposeFormat("metadata", function() { + return require_metadata(); + }); + exposeFormat("ms", function() { + return require_ms2(); + }); + exposeFormat("padLevels", function() { + return require_pad_levels(); + }); + exposeFormat("prettyPrint", function() { + return require_pretty_print(); + }); + exposeFormat("printf", function() { + return require_printf(); + }); + exposeFormat("simple", function() { + return require_simple(); + }); + exposeFormat("splat", function() { + return require_splat(); + }); + exposeFormat("timestamp", function() { + return require_timestamp(); + }); + exposeFormat("uncolorize", function() { + return require_uncolorize(); + }); + } +}); + +// node_modules/winston/lib/winston/common.js +var require_common = __commonJS({ + "node_modules/winston/lib/winston/common.js"(exports2) { + "use strict"; + var { format } = __require("util"); + exports2.warn = { + deprecated(prop) { + return () => { + throw new Error(format("{ %s } was removed in winston@3.0.0.", prop)); + }; + }, + useFormat(prop) { + return () => { + throw new Error([ + format("{ %s } was removed in winston@3.0.0.", prop), + "Use a custom winston.format = winston.format(function) instead." + ].join("\n")); + }; + }, + forFunctions(obj, type, props) { + props.forEach((prop) => { + obj[prop] = exports2.warn[type](prop); + }); + }, + forProperties(obj, type, props) { + props.forEach((prop) => { + const notice = exports2.warn[type](prop); + Object.defineProperty(obj, prop, { + get: notice, + set: notice + }); + }); } - return false; }; - TransportStream.prototype._nop = function _nop() { - return void 0; + } +}); + +// node_modules/winston/package.json +var require_package2 = __commonJS({ + "node_modules/winston/package.json"(exports2, module2) { + module2.exports = { + name: "winston", + description: "A logger for just about everything.", + version: "3.17.0", + author: "Charlie Robbins ", + maintainers: [ + "David Hyde " + ], + repository: { + type: "git", + url: "https://github.com/winstonjs/winston.git" + }, + keywords: [ + "winston", + "logger", + "logging", + "logs", + "sysadmin", + "bunyan", + "pino", + "loglevel", + "tools", + "json", + "stream" + ], + dependencies: { + "@dabh/diagnostics": "^2.0.2", + "@colors/colors": "^1.6.0", + async: "^3.2.3", + "is-stream": "^2.0.0", + logform: "^2.7.0", + "one-time": "^1.0.0", + "readable-stream": "^3.4.0", + "safe-stable-stringify": "^2.3.1", + "stack-trace": "0.0.x", + "triple-beam": "^1.3.0", + "winston-transport": "^4.9.0" + }, + devDependencies: { + "@babel/cli": "^7.23.9", + "@babel/core": "^7.24.0", + "@babel/preset-env": "^7.24.0", + "@dabh/eslint-config-populist": "^4.4.0", + "@types/node": "^20.11.24", + "abstract-winston-transport": "^0.5.1", + assume: "^2.2.0", + "cross-spawn-async": "^2.2.5", + eslint: "^8.57.0", + hock: "^1.4.1", + mocha: "^10.3.0", + nyc: "^17.1.0", + rimraf: "5.0.1", + split2: "^4.1.0", + "std-mocks": "^2.0.0", + through2: "^4.0.2", + "winston-compat": "^0.1.5" + }, + main: "./lib/winston.js", + browser: "./dist/winston", + types: "./index.d.ts", + scripts: { + lint: "eslint lib/*.js lib/winston/*.js lib/winston/**/*.js --resolve-plugins-relative-to ./node_modules/@dabh/eslint-config-populist", + test: "rimraf test/fixtures/logs/* && mocha", + "test:coverage": "nyc npm run test:unit", + "test:unit": "mocha test/unit", + "test:integration": "mocha test/integration", + build: "rimraf dist && babel lib -d dist", + prepublishOnly: "npm run build" + }, + engines: { + node: ">= 12.0.0" + }, + license: "MIT" }; } }); -// node_modules/winston-transport/legacy.js -var require_legacy = __commonJS({ - "node_modules/winston-transport/legacy.js"(exports2, module2) { - "use strict"; - var util3 = __require("util"); - var { LEVEL } = require_triple_beam(); - var TransportStream = require_modern(); - var LegacyTransportStream = module2.exports = function LegacyTransportStream2(options = {}) { - TransportStream.call(this, options); - if (!options.transport || typeof options.transport.log !== "function") { - throw new Error("Invalid transport, must be an object with a log method."); - } - this.transport = options.transport; - this.level = this.level || options.transport.level; - this.handleExceptions = this.handleExceptions || options.transport.handleExceptions; - this._deprecated(); - function transportError(err) { - this.emit("error", err, this.transport); - } - if (!this.transport.__winstonError) { - this.transport.__winstonError = transportError.bind(this); - this.transport.on("error", this.transport.__winstonError); - } - }; - util3.inherits(LegacyTransportStream, TransportStream); - LegacyTransportStream.prototype._write = function _write(info, enc, callback) { - if (this.silent || info.exception === true && !this.handleExceptions) { - return callback(null); - } - if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) { - this.transport.log(info[LEVEL], info.message, info, this._nop); - } - callback(null); - }; - LegacyTransportStream.prototype._writev = function _writev(chunks, callback) { - for (let i = 0; i < chunks.length; i++) { - if (this._accept(chunks[i])) { - this.transport.log( - chunks[i].chunk[LEVEL], - chunks[i].chunk.message, - chunks[i].chunk, - this._nop - ); - chunks[i].callback(); - } - } - return callback(null); - }; - LegacyTransportStream.prototype._deprecated = function _deprecated() { - console.error([ - `${this.transport.name} is a legacy winston transport. Consider upgrading: `, - "- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md" - ].join("\n")); - }; - LegacyTransportStream.prototype.close = function close() { - if (this.transport.close) { - this.transport.close(); - } - if (this.transport.__winstonError) { - this.transport.removeListener("error", this.transport.__winstonError); - this.transport.__winstonError = null; - } - }; +// node_modules/util-deprecate/node.js +var require_node = __commonJS({ + "node_modules/util-deprecate/node.js"(exports2, module2) { + module2.exports = __require("util").deprecate; } }); -// node_modules/winston-transport/index.js -var require_winston_transport = __commonJS({ - "node_modules/winston-transport/index.js"(exports2, module2) { - "use strict"; - module2.exports = require_modern(); - module2.exports.LegacyTransportStream = require_legacy(); +// node_modules/readable-stream/lib/internal/streams/stream.js +var require_stream = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/stream.js"(exports2, module2) { + module2.exports = __require("stream"); } }); -// node_modules/winston/lib/winston/transports/console.js -var require_console = __commonJS({ - "node_modules/winston/lib/winston/transports/console.js"(exports2, module2) { +// node_modules/readable-stream/lib/internal/streams/destroy.js +var require_destroy = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports2, module2) { "use strict"; - var os2 = __require("os"); - var { LEVEL, MESSAGE } = require_triple_beam(); - var TransportStream = require_winston_transport(); - module2.exports = class Console extends TransportStream { - /** - * Constructor function for the Console transport object responsible for - * persisting log messages and metadata to a terminal or TTY. - * @param {!Object} [options={}] - Options for this instance. - */ - constructor(options = {}) { - super(options); - this.name = options.name || "console"; - this.stderrLevels = this._stringArrayToSet(options.stderrLevels); - this.consoleWarnLevels = this._stringArrayToSet(options.consoleWarnLevels); - this.eol = typeof options.eol === "string" ? options.eol : os2.EOL; - this.forceConsole = options.forceConsole || false; - this._consoleLog = console.log.bind(console); - this._consoleWarn = console.warn.bind(console); - this._consoleError = console.error.bind(console); - this.setMaxListeners(30); - } - /** - * Core logging method exposed to Winston. - * @param {Object} info - TODO: add param description. - * @param {Function} callback - TODO: add param description. - * @returns {undefined} - */ - log(info, callback) { - setImmediate(() => this.emit("logged", info)); - if (this.stderrLevels[info[LEVEL]]) { - if (console._stderr && !this.forceConsole) { - console._stderr.write(`${info[MESSAGE]}${this.eol}`); - } else { - this._consoleError(info[MESSAGE]); - } - if (callback) { - callback(); + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); } - return; - } else if (this.consoleWarnLevels[info[LEVEL]]) { - if (console._stderr && !this.forceConsole) { - console._stderr.write(`${info[MESSAGE]}${this.eol}`); + } + return this; + } + if (this._readableState) { + this._readableState.destroyed = true; + } + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function(err2) { + if (!cb && err2) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err2); } else { - this._consoleWarn(info[MESSAGE]); - } - if (callback) { - callback(); + process.nextTick(emitCloseNT, _this); } - return; - } - if (console._stdout && !this.forceConsole) { - console._stdout.write(`${info[MESSAGE]}${this.eol}`); + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err2); } else { - this._consoleLog(info[MESSAGE]); - } - if (callback) { - callback(); + process.nextTick(emitCloseNT, _this); } + }); + return this; + } + function emitErrorAndCloseNT(self2, err) { + emitErrorNT(self2, err); + emitCloseNT(self2); + } + function emitCloseNT(self2) { + if (self2._writableState && !self2._writableState.emitClose) return; + if (self2._readableState && !self2._readableState.emitClose) return; + self2.emit("close"); + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - /** - * Returns a Set-like object with strArray's elements as keys (each with the - * value true). - * @param {Array} strArray - Array of Set-elements as strings. - * @param {?string} [errMsg] - Custom error message thrown on invalid input. - * @returns {Object} - TODO: add return description. - * @private - */ - _stringArrayToSet(strArray, errMsg) { - if (!strArray) return {}; - errMsg = errMsg || "Cannot make set from type other than Array of string elements"; - if (!Array.isArray(strArray)) { - throw new Error(errMsg); - } - return strArray.reduce((set, el2) => { - if (typeof el2 !== "string") { - throw new Error(errMsg); - } - set[el2] = true; - return set; - }, {}); + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; } - }; - } -}); - -// node_modules/async/internal/isArrayLike.js -var require_isArrayLike = __commonJS({ - "node_modules/async/internal/isArrayLike.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = isArrayLike; - function isArrayLike(value) { - return value && typeof value.length === "number" && value.length >= 0 && value.length % 1 === 0; - } - module2.exports = exports2.default; - } -}); - -// node_modules/async/internal/initialParams.js -var require_initialParams = __commonJS({ - "node_modules/async/internal/initialParams.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = function(fn2) { - return function(...args) { - var callback = args.pop(); - return fn2.call(this, args, callback); - }; - }; - module2.exports = exports2.default; - } -}); - -// node_modules/async/internal/setImmediate.js -var require_setImmediate = __commonJS({ - "node_modules/async/internal/setImmediate.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.fallback = fallback2; - exports2.wrap = wrap; - var hasQueueMicrotask = exports2.hasQueueMicrotask = typeof queueMicrotask === "function" && queueMicrotask; - var hasSetImmediate = exports2.hasSetImmediate = typeof setImmediate === "function" && setImmediate; - var hasNextTick = exports2.hasNextTick = typeof process === "object" && typeof process.nextTick === "function"; - function fallback2(fn2) { - setTimeout(fn2, 0); } - function wrap(defer) { - return (fn2, ...args) => defer(() => fn2(...args)); + function emitErrorNT(self2, err) { + self2.emit("error", err); } - var _defer; - if (hasQueueMicrotask) { - _defer = queueMicrotask; - } else if (hasSetImmediate) { - _defer = setImmediate; - } else if (hasNextTick) { - _defer = process.nextTick; - } else { - _defer = fallback2; + function errorOrDestroy(stream4, err) { + var rState = stream4._readableState; + var wState = stream4._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream4.destroy(err); + else stream4.emit("error", err); } - exports2.default = wrap(_defer); + module2.exports = { + destroy, + undestroy, + errorOrDestroy + }; } }); -// node_modules/async/asyncify.js -var require_asyncify = __commonJS({ - "node_modules/async/asyncify.js"(exports2, module2) { +// node_modules/readable-stream/errors.js +var require_errors2 = __commonJS({ + "node_modules/readable-stream/errors.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = asyncify; - var _initialParams = require_initialParams(); - var _initialParams2 = _interopRequireDefault(_initialParams); - var _setImmediate2 = require_setImmediate(); - var _setImmediate22 = _interopRequireDefault(_setImmediate2); - var _wrapAsync = require_wrapAsync(); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function asyncify(func) { - if ((0, _wrapAsync.isAsync)(func)) { - return function(...args) { - const callback = args.pop(); - const promise = func.apply(this, args); - return handlePromise(promise, callback); - }; + var codes = {}; + function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; } - return (0, _initialParams2.default)(function(args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - if (result && typeof result.then === "function") { - return handlePromise(result, callback); + function getMessage(arg1, arg2, arg3) { + if (typeof message === "string") { + return message; } else { - callback(null, result); + return message(arg1, arg2, arg3); } - }); - } - function handlePromise(promise, callback) { - return promise.then((value) => { - invokeCallback(callback, null, value); - }, (err) => { - invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); - }); - } - function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (err) { - (0, _setImmediate22.default)((e) => { - throw e; - }, err); } + class NodeError extends Base { + constructor(arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; } - module2.exports = exports2.default; - } -}); - -// node_modules/async/internal/wrapAsync.js -var require_wrapAsync = __commonJS({ - "node_modules/async/internal/wrapAsync.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.isAsyncIterable = exports2.isAsyncGenerator = exports2.isAsync = void 0; - var _asyncify = require_asyncify(); - var _asyncify2 = _interopRequireDefault(_asyncify); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function isAsync(fn2) { - return fn2[Symbol.toStringTag] === "AsyncFunction"; - } - function isAsyncGenerator(fn2) { - return fn2[Symbol.toStringTag] === "AsyncGenerator"; + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(", ")}, or ` + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } } - function isAsyncIterable(obj) { - return typeof obj[Symbol.asyncIterator] === "function"; + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } - function wrapAsync2(asyncFn) { - if (typeof asyncFn !== "function") throw new Error("expected a function"); - return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; + function endsWith2(str, search, this_len) { + if (this_len === void 0 || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; } - exports2.default = wrapAsync2; - exports2.isAsync = isAsync; - exports2.isAsyncGenerator = isAsyncGenerator; - exports2.isAsyncIterable = isAsyncIterable; - } -}); - -// node_modules/async/internal/awaitify.js -var require_awaitify = __commonJS({ - "node_modules/async/internal/awaitify.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = awaitify; - function awaitify(asyncFn, arity) { - if (!arity) arity = asyncFn.length; - if (!arity) throw new Error("arity is undefined"); - function awaitable(...args) { - if (typeof args[arity - 1] === "function") { - return asyncFn.apply(this, args); - } - return new Promise((resolve, reject) => { - args[arity - 1] = (err, ...cbArgs) => { - if (err) return reject(err); - resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); - }; - asyncFn.apply(this, args); - }); + function includes(str, search, start) { + if (typeof start !== "number") { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; } - return awaitable; } - module2.exports = exports2.default; - } -}); - -// node_modules/async/internal/parallel.js -var require_parallel2 = __commonJS({ - "node_modules/async/internal/parallel.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true + createErrorType("ERR_INVALID_OPT_VALUE", function(name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { + let determiner; + if (typeof expected === "string" && startsWith(expected, "not ")) { + determiner = "must not be"; + expected = expected.replace(/^not /, ""); + } else { + determiner = "must be"; + } + let msg; + if (endsWith2(name, " argument")) { + msg = `The ${name} ${determiner} ${oneOf(expected, "type")}`; + } else { + const type = includes(name, ".") ? "property" : "argument"; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, "type")}`; + } + msg += `. Received type ${typeof actual}`; + return msg; + }, TypeError); + createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); + createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name) { + return "The " + name + " method is not implemented"; }); - var _isArrayLike = require_isArrayLike(); - var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - var _wrapAsync = require_wrapAsync(); - var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - var _awaitify = require_awaitify(); - var _awaitify2 = _interopRequireDefault(_awaitify); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - exports2.default = (0, _awaitify2.default)((eachfn, tasks, callback) => { - var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; - eachfn(tasks, (task, key, taskCb) => { - (0, _wrapAsync2.default)(task)((err, ...result) => { - if (result.length < 2) { - [result] = result; - } - results[key] = result; - taskCb(err); - }); - }, (err) => callback(err, results)); - }, 3); - module2.exports = exports2.default; + createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); + createErrorType("ERR_STREAM_DESTROYED", function(name) { + return "Cannot call " + name + " after a stream was destroyed"; + }); + createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); + createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); + createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { + return "Unknown encoding: " + arg; + }, TypeError); + createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); + module2.exports.codes = codes; } }); -// node_modules/async/internal/once.js -var require_once = __commonJS({ - "node_modules/async/internal/once.js"(exports2, module2) { +// node_modules/readable-stream/lib/internal/streams/state.js +var require_state = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/state.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = once; - function once(fn2) { - function wrapper(...args) { - if (fn2 === null) return; - var callFn = fn2; - fn2 = null; - callFn.apply(this, args); + var ERR_INVALID_OPT_VALUE = require_errors2().codes.ERR_INVALID_OPT_VALUE; + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } + function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : "highWaterMark"; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); } - Object.assign(wrapper, fn2); - return wrapper; + return state.objectMode ? 16 : 16 * 1024; } - module2.exports = exports2.default; - } -}); - -// node_modules/async/internal/getIterator.js -var require_getIterator = __commonJS({ - "node_modules/async/internal/getIterator.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = function(coll) { - return coll[Symbol.iterator] && coll[Symbol.iterator](); + module2.exports = { + getHighWaterMark }; - module2.exports = exports2.default; } }); -// node_modules/async/internal/iterator.js -var require_iterator = __commonJS({ - "node_modules/async/internal/iterator.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = createIterator; - var _isArrayLike = require_isArrayLike(); - var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - var _getIterator = require_getIterator(); - var _getIterator2 = _interopRequireDefault(_getIterator); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? { value: coll[i], key: i } : null; - }; - } - function createES2015Iterator(iterator2) { - var i = -1; - return function next() { - var item = iterator2.next(); - if (item.done) return null; - i++; - return { value: item.value, key: i }; +// node_modules/inherits/inherits_browser.js +var require_inherits_browser = __commonJS({ + "node_modules/inherits/inherits_browser.js"(exports2, module2) { + if (typeof Object.create === "function") { + module2.exports = function inherits2(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } }; - } - function createObjectIterator(obj) { - var okeys = obj ? Object.keys(obj) : []; - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - if (key === "__proto__") { - return next(); + } else { + module2.exports = function inherits2(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; } - return i < len ? { value: obj[key], key } : null; }; } - function createIterator(coll) { - if ((0, _isArrayLike2.default)(coll)) { - return createArrayIterator(coll); - } - var iterator2 = (0, _getIterator2.default)(coll); - return iterator2 ? createES2015Iterator(iterator2) : createObjectIterator(coll); - } - module2.exports = exports2.default; } }); -// node_modules/async/internal/onlyOnce.js -var require_onlyOnce = __commonJS({ - "node_modules/async/internal/onlyOnce.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = onlyOnce; - function onlyOnce(fn2) { - return function(...args) { - if (fn2 === null) throw new Error("Callback was already called."); - var callFn = fn2; - fn2 = null; - callFn.apply(this, args); - }; +// node_modules/inherits/inherits.js +var require_inherits = __commonJS({ + "node_modules/inherits/inherits.js"(exports2, module2) { + try { + util3 = __require("util"); + if (typeof util3.inherits !== "function") throw ""; + module2.exports = util3.inherits; + } catch (e) { + module2.exports = require_inherits_browser(); } - module2.exports = exports2.default; - } -}); - -// node_modules/async/internal/breakLoop.js -var require_breakLoop = __commonJS({ - "node_modules/async/internal/breakLoop.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - var breakLoop = {}; - exports2.default = breakLoop; - module2.exports = exports2.default; + var util3; } }); -// node_modules/async/internal/asyncEachOfLimit.js -var require_asyncEachOfLimit = __commonJS({ - "node_modules/async/internal/asyncEachOfLimit.js"(exports2, module2) { +// node_modules/readable-stream/lib/internal/streams/buffer_list.js +var require_buffer_list = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = asyncEachOfLimit; - var _breakLoop = require_breakLoop(); - var _breakLoop2 = _interopRequireDefault(_breakLoop); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; } - function asyncEachOfLimit(generator, limit, iteratee, callback) { - let done = false; - let canceled = false; - let awaiting = false; - let running = 0; - let idx = 0; - function replenish() { - if (running >= limit || awaiting || done) return; - awaiting = true; - generator.next().then(({ value, done: iterDone }) => { - if (canceled || done) return; - awaiting = false; - if (iterDone) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running++; - iteratee(value, idx, iterateeCallback); - idx++; - replenish(); - }).catch(handleError); + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } - function iterateeCallback(err, result) { - running -= 1; - if (canceled) return; - if (err) return handleError(err); - if (err === false) { - done = true; - canceled = true; - return; - } - if (result === _breakLoop2.default || done && running <= 0) { - done = true; - return callback(null); - } - replenish(); + return target; + } + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; } - function handleError(err) { - if (canceled) return; - awaiting = false; - done = true; - callback(err); + return obj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); } - replenish(); } - module2.exports = exports2.default; - } -}); - -// node_modules/async/internal/eachOfLimit.js -var require_eachOfLimit = __commonJS({ - "node_modules/async/internal/eachOfLimit.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - var _once = require_once(); - var _once2 = _interopRequireDefault(_once); - var _iterator = require_iterator(); - var _iterator2 = _interopRequireDefault(_iterator); - var _onlyOnce = require_onlyOnce(); - var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - var _wrapAsync = require_wrapAsync(); - var _asyncEachOfLimit = require_asyncEachOfLimit(); - var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit); - var _breakLoop = require_breakLoop(); - var _breakLoop2 = _interopRequireDefault(_breakLoop); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); + } } - exports2.default = (limit) => { - return (obj, iteratee, callback) => { - callback = (0, _once2.default)(callback); - if (limit <= 0) { - throw new RangeError("concurrency limit cannot be less than 1"); + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var _require = __require("buffer"); + var Buffer2 = _require.Buffer; + var _require2 = __require("util"); + var inspect = _require2.inspect; + var custom = inspect && inspect.custom || "inspect"; + function copyBuffer(src, target, offset) { + Buffer2.prototype.copy.call(src, target, offset); + } + module2.exports = /* @__PURE__ */ function() { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; } - if (!obj) { - return callback(null); + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; } - if ((0, _wrapAsync.isAsyncGenerator)(obj)) { - return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback); + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; } - if ((0, _wrapAsync.isAsyncIterable)(obj)) { - return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback); + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; } - var nextElem = (0, _iterator2.default)(obj); - var done = false; - var canceled = false; - var running = 0; - var looping = false; - function iterateeCallback(err, value) { - if (canceled) return; - running -= 1; - if (err) { - done = true; - callback(err); - } else if (err === false) { - done = true; - canceled = true; - } else if (value === _breakLoop2.default || done && running <= 0) { - done = true; - return callback(null); - } else if (!looping) { - replenish(); + }, { + key: "join", + value: function join2(s) { + if (this.length === 0) return ""; + var p = this.head; + var ret = "" + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat3(n) { + if (this.length === 0) return Buffer2.alloc(0); + var ret = Buffer2.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; } + return ret; } - function replenish() { - looping = true; - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + ret = this.shift(); + } else { + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str; + else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); } - return; + break; } - running += 1; - iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); + ++c; } - looping = false; + this.length -= c; + return ret; } - replenish(); - }; - }; - module2.exports = exports2.default; - } -}); - -// node_modules/async/eachOfLimit.js -var require_eachOfLimit2 = __commonJS({ - "node_modules/async/eachOfLimit.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - var _eachOfLimit2 = require_eachOfLimit(); - var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); - var _wrapAsync = require_wrapAsync(); - var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - var _awaitify = require_awaitify(); - var _awaitify2 = _interopRequireDefault(_awaitify); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function eachOfLimit(coll, limit, iteratee, callback) { - return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); - } - exports2.default = (0, _awaitify2.default)(eachOfLimit, 4); - module2.exports = exports2.default; + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer2.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; + }(); } }); -// node_modules/async/eachOfSeries.js -var require_eachOfSeries = __commonJS({ - "node_modules/async/eachOfSeries.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - var _eachOfLimit = require_eachOfLimit2(); - var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - var _awaitify = require_awaitify(); - var _awaitify2 = _interopRequireDefault(_awaitify); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function eachOfSeries(coll, iteratee, callback) { - return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); +// node_modules/safe-buffer/index.js +var require_safe_buffer = __commonJS({ + "node_modules/safe-buffer/index.js"(exports2, module2) { + var buffer2 = __require("buffer"); + var Buffer2 = buffer2.Buffer; + function copyProps(src, dst) { + for (var key in src) { + dst[key] = src[key]; + } } - exports2.default = (0, _awaitify2.default)(eachOfSeries, 3); - module2.exports = exports2.default; - } -}); - -// node_modules/async/series.js -var require_series = __commonJS({ - "node_modules/async/series.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = series; - var _parallel2 = require_parallel2(); - var _parallel3 = _interopRequireDefault(_parallel2); - var _eachOfSeries = require_eachOfSeries(); - var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; + if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + module2.exports = buffer2; + } else { + copyProps(buffer2, exports2); + exports2.Buffer = SafeBuffer; } - function series(tasks, callback) { - return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback); + function SafeBuffer(arg, encodingOrOffset, length) { + return Buffer2(arg, encodingOrOffset, length); } - module2.exports = exports2.default; - } -}); - -// node_modules/readable-stream/lib/_stream_transform.js -var require_stream_transform = __commonJS({ - "node_modules/readable-stream/lib/_stream_transform.js"(exports2, module2) { - "use strict"; - module2.exports = Transform; - var _require$codes = require_errors2().codes; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; - var ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING; - var ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - var Duplex = require_stream_duplex(); - require_inherits()(Transform, Duplex); - function afterTransform(er2, data) { - var ts2 = this._transformState; - ts2.transforming = false; - var cb = ts2.writecb; - if (cb === null) { - return this.emit("error", new ERR_MULTIPLE_CALLBACK()); - } - ts2.writechunk = null; - ts2.writecb = null; - if (data != null) - this.push(data); - cb(er2); - var rs2 = this._readableState; - rs2.reading = false; - if (rs2.needReadable || rs2.length < rs2.highWaterMark) { - this._read(rs2.highWaterMark); + SafeBuffer.prototype = Object.create(Buffer2.prototype); + copyProps(Buffer2, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + throw new TypeError("Argument must not be a number"); } - } - function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - this._readableState.needReadable = true; - this._readableState.sync = false; - if (options) { - if (typeof options.transform === "function") this._transform = options.transform; - if (typeof options.flush === "function") this._flush = options.flush; + return Buffer2(arg, encodingOrOffset, length); + }; + SafeBuffer.alloc = function(size5, fill, encoding) { + if (typeof size5 !== "number") { + throw new TypeError("Argument must be a number"); } - this.on("prefinish", prefinish); - } - function prefinish() { - var _this = this; - if (typeof this._flush === "function" && !this._readableState.destroyed) { - this._flush(function(er2, data) { - done(_this, er2, data); - }); + var buf = Buffer2(size5); + if (fill !== void 0) { + if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } } else { - done(this, null, null); + buf.fill(0); } - } - Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; - Transform.prototype._transform = function(chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); + return buf; }; - Transform.prototype._write = function(chunk, encoding, cb) { - var ts2 = this._transformState; - ts2.writecb = cb; - ts2.writechunk = chunk; - ts2.writeencoding = encoding; - if (!ts2.transforming) { - var rs2 = this._readableState; - if (ts2.needTransform || rs2.needReadable || rs2.length < rs2.highWaterMark) this._read(rs2.highWaterMark); + SafeBuffer.allocUnsafe = function(size5) { + if (typeof size5 !== "number") { + throw new TypeError("Argument must be a number"); } + return Buffer2(size5); }; - Transform.prototype._read = function(n) { - var ts2 = this._transformState; - if (ts2.writechunk !== null && !ts2.transforming) { - ts2.transforming = true; - this._transform(ts2.writechunk, ts2.writeencoding, ts2.afterTransform); - } else { - ts2.needTransform = true; + SafeBuffer.allocUnsafeSlow = function(size5) { + if (typeof size5 !== "number") { + throw new TypeError("Argument must be a number"); } + return buffer2.SlowBuffer(size5); }; - Transform.prototype._destroy = function(err, cb) { - Duplex.prototype._destroy.call(this, err, function(err2) { - cb(err2); - }); - }; - function done(stream4, er2, data) { - if (er2) return stream4.emit("error", er2); - if (data != null) - stream4.push(data); - if (stream4._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream4._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream4.push(null); - } } }); -// node_modules/readable-stream/lib/_stream_passthrough.js -var require_stream_passthrough = __commonJS({ - "node_modules/readable-stream/lib/_stream_passthrough.js"(exports2, module2) { +// node_modules/string_decoder/lib/string_decoder.js +var require_string_decoder = __commonJS({ + "node_modules/string_decoder/lib/string_decoder.js"(exports2) { "use strict"; - module2.exports = PassThrough; - var Transform = require_stream_transform(); - require_inherits()(PassThrough, Transform); - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); - } - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); + var Buffer2 = require_safe_buffer().Buffer; + var isEncoding = Buffer2.isEncoding || function(encoding) { + encoding = "" + encoding; + switch (encoding && encoding.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } }; - } -}); - -// node_modules/readable-stream/lib/internal/streams/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports2, module2) { - "use strict"; - var eos; - function once(callback) { - var called = false; - return function() { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; - } - var _require$codes = require_errors2().codes; - var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; - var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - function noop2(err) { - if (err) throw err; - } - function isRequest2(stream4) { - return stream4.setHeader && typeof stream4.abort === "function"; - } - function destroyer(stream4, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream4.on("close", function() { - closed = true; - }); - if (eos === void 0) eos = require_end_of_stream(); - eos(stream4, { - readable: reading, - writable: writing - }, function(err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function(err) { - if (closed) return; - if (destroyed) return; - destroyed = true; - if (isRequest2(stream4)) return stream4.abort(); - if (typeof stream4.destroy === "function") return stream4.destroy(); - callback(err || new ERR_STREAM_DESTROYED("pipe")); - }; - } - function call2(fn2) { - fn2(); + function _normalizeEncoding(enc) { + if (!enc) return "utf8"; + var retried; + while (true) { + switch (enc) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return enc; + default: + if (retried) return; + enc = ("" + enc).toLowerCase(); + retried = true; + } + } } - function pipe(from5, to2) { - return from5.pipe(to2); + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc); + return nenc || enc; } - function popCallback(streams) { - if (!streams.length) return noop2; - if (typeof streams[streams.length - 1] !== "function") return noop2; - return streams.pop(); + exports2.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case "utf16le": + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case "utf8": + this.fillLast = utf8FillLast; + nb = 4; + break; + case "base64": + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer2.allocUnsafe(nb); } - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; + StringDecoder.prototype.write = function(buf) { + if (buf.length === 0) return ""; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === void 0) return ""; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - if (streams.length < 2) { - throw new ERR_MISSING_ARGS("streams"); + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ""; + }; + StringDecoder.prototype.end = utf8End; + StringDecoder.prototype.text = utf8Text; + StringDecoder.prototype.fillLast = function(buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); } - var error; - var destroys = streams.map(function(stream4, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream4, reading, writing, function(err) { - if (!error) error = err; - if (err) destroys.forEach(call2); - if (reading) return; - destroys.forEach(call2); - callback(error); - }); - }); - return streams.reduce(pipe); - } - module2.exports = pipeline; - } -}); - -// node_modules/readable-stream/readable.js -var require_readable = __commonJS({ - "node_modules/readable-stream/readable.js"(exports2, module2) { - var Stream = __require("stream"); - if (process.env.READABLE_STREAM === "disable" && Stream) { - module2.exports = Stream.Readable; - Object.assign(module2.exports, Stream); - module2.exports.Stream = Stream; - } else { - exports2 = module2.exports = require_stream_readable(); - exports2.Stream = Stream || exports2; - exports2.Readable = exports2; - exports2.Writable = require_stream_writable(); - exports2.Duplex = require_stream_duplex(); - exports2.Transform = require_stream_transform(); - exports2.PassThrough = require_stream_passthrough(); - exports2.finished = require_end_of_stream(); - exports2.pipeline = require_pipeline(); - } - } -}); - -// node_modules/@dabh/diagnostics/diagnostics.js -var require_diagnostics = __commonJS({ - "node_modules/@dabh/diagnostics/diagnostics.js"(exports2, module2) { - var adapters = []; - var modifiers2 = []; - var logger = function devnull() { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; }; - function use(adapter) { - if (~adapters.indexOf(adapter)) return false; - adapters.push(adapter); - return true; - } - function set(custom) { - logger = custom; + function utf8CheckByte(byte) { + if (byte <= 127) return 0; + else if (byte >> 5 === 6) return 2; + else if (byte >> 4 === 14) return 3; + else if (byte >> 3 === 30) return 4; + return byte >> 6 === 2 ? -1 : -2; } - function enabled(namespace) { - var async = []; - for (var i = 0; i < adapters.length; i++) { - if (adapters[i].async) { - async.push(adapters[i]); - continue; + function utf8CheckIncomplete(self2, buf, i) { + var j2 = buf.length - 1; + if (j2 < i) return 0; + var nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 1; + return nb; + } + if (--j2 < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 2; + return nb; + } + if (--j2 < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j2]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0; + else self2.lastNeed = nb - 3; } - if (adapters[i](namespace)) return true; + return nb; } - if (!async.length) return false; - return new Promise(function pinky(resolve) { - Promise.all( - async.map(function prebind(fn2) { - return fn2(namespace); - }) - ).then(function resolved(values) { - resolve(values.some(Boolean)); - }); - }); - } - function modify(fn2) { - if (~modifiers2.indexOf(fn2)) return false; - modifiers2.push(fn2); - return true; + return 0; } - function write() { - logger.apply(logger, arguments); + function utf8CheckExtraBytes(self2, buf, p) { + if ((buf[0] & 192) !== 128) { + self2.lastNeed = 0; + return "\uFFFD"; + } + if (self2.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 192) !== 128) { + self2.lastNeed = 1; + return "\uFFFD"; + } + if (self2.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 192) !== 128) { + self2.lastNeed = 2; + return "\uFFFD"; + } + } + } } - function process4(message) { - for (var i = 0; i < modifiers2.length; i++) { - message = modifiers2[i].apply(modifiers2[i], arguments); + function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== void 0) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); } - return message; + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; + } + function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString("utf8", i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString("utf8", i, end); } - function introduce(fn2, options) { - var has = Object.prototype.hasOwnProperty; - for (var key in options) { - if (has.call(options, key)) { - fn2[key] = options[key]; + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) return r + "\uFFFD"; + return r; + } + function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString("utf16le", i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 55296 && c <= 56319) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } } + return r; } - return fn2; - } - function nope(options) { - options.enabled = false; - options.modify = modify; - options.set = set; - options.use = use; - return introduce(function diagnopes() { - return false; - }, options); + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString("utf16le", i, buf.length - 1); } - function yep(options) { - function diagnostics() { - var args = Array.prototype.slice.call(arguments, 0); - write.call(write, options, process4(args, options)); - return true; + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString("utf16le", 0, end); } - options.enabled = true; - options.modify = modify; - options.set = set; - options.use = use; - return introduce(diagnostics, options); + return r; } - module2.exports = function create(diagnostics) { - diagnostics.introduce = introduce; - diagnostics.enabled = enabled; - diagnostics.process = process4; - diagnostics.modify = modify; - diagnostics.write = write; - diagnostics.nope = nope; - diagnostics.yep = yep; - diagnostics.set = set; - diagnostics.use = use; - return diagnostics; - }; - } -}); - -// node_modules/@dabh/diagnostics/node/production.js -var require_production = __commonJS({ - "node_modules/@dabh/diagnostics/node/production.js"(exports2, module2) { - var create = require_diagnostics(); - var diagnostics = create(function prod(namespace, options) { - options = options || {}; - options.namespace = namespace; - options.prod = true; - options.dev = false; - if (!(options.force || prod.force)) return prod.nope(options); - return prod.yep(options); - }); - module2.exports = diagnostics; - } -}); - -// node_modules/color-name/index.js -var require_color_name = __commonJS({ - "node_modules/color-name/index.js"(exports2, module2) { - "use strict"; - module2.exports = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] - }; - } -}); - -// node_modules/simple-swizzle/node_modules/is-arrayish/index.js -var require_is_arrayish = __commonJS({ - "node_modules/simple-swizzle/node_modules/is-arrayish/index.js"(exports2, module2) { - module2.exports = function isArrayish(obj) { - if (!obj || typeof obj === "string") { - return false; + function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString("base64", i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; } - return obj instanceof Array || Array.isArray(obj) || obj.length >= 0 && (obj.splice instanceof Function || Object.getOwnPropertyDescriptor(obj, obj.length - 1) && obj.constructor.name !== "String"); - }; + return buf.toString("base64", i, buf.length - n); + } + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); + return r; + } + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ""; + } } }); -// node_modules/simple-swizzle/index.js -var require_simple_swizzle = __commonJS({ - "node_modules/simple-swizzle/index.js"(exports2, module2) { +// node_modules/readable-stream/lib/internal/streams/end-of-stream.js +var require_end_of_stream = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports2, module2) { "use strict"; - var isArrayish = require_is_arrayish(); - var concat3 = Array.prototype.concat; - var slice3 = Array.prototype.slice; - var swizzle = module2.exports = function swizzle2(args) { - var results = []; - for (var i = 0, len = args.length; i < len; i++) { - var arg = args[i]; - if (isArrayish(arg)) { - results = concat3.call(results, slice3.call(arg)); - } else { - results.push(arg); + var ERR_STREAM_PREMATURE_CLOSE = require_errors2().codes.ERR_STREAM_PREMATURE_CLOSE; + function once(callback) { + var called = false; + return function() { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; + } + function noop2() { + } + function isRequest2(stream4) { + return stream4.setHeader && typeof stream4.abort === "function"; + } + function eos(stream4, opts, callback) { + if (typeof opts === "function") return eos(stream4, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop2); + var readable = opts.readable || opts.readable !== false && stream4.readable; + var writable = opts.writable || opts.writable !== false && stream4.writable; + var onlegacyfinish = function onlegacyfinish2() { + if (!stream4.writable) onfinish(); + }; + var writableEnded = stream4._writableState && stream4._writableState.finished; + var onfinish = function onfinish2() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream4); + }; + var readableEnded = stream4._readableState && stream4._readableState.endEmitted; + var onend = function onend2() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream4); + }; + var onerror = function onerror2(err) { + callback.call(stream4, err); + }; + var onclose = function onclose2() { + var err; + if (readable && !readableEnded) { + if (!stream4._readableState || !stream4._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream4, err); } + if (writable && !writableEnded) { + if (!stream4._writableState || !stream4._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream4, err); + } + }; + var onrequest = function onrequest2() { + stream4.req.on("finish", onfinish); + }; + if (isRequest2(stream4)) { + stream4.on("complete", onfinish); + stream4.on("abort", onclose); + if (stream4.req) onrequest(); + else stream4.on("request", onrequest); + } else if (writable && !stream4._writableState) { + stream4.on("end", onlegacyfinish); + stream4.on("close", onlegacyfinish); } - return results; - }; - swizzle.wrap = function(fn2) { + stream4.on("end", onend); + stream4.on("finish", onfinish); + if (opts.error !== false) stream4.on("error", onerror); + stream4.on("close", onclose); return function() { - return fn2(swizzle(arguments)); + stream4.removeListener("complete", onfinish); + stream4.removeListener("abort", onclose); + stream4.removeListener("request", onrequest); + if (stream4.req) stream4.req.removeListener("finish", onfinish); + stream4.removeListener("end", onlegacyfinish); + stream4.removeListener("close", onlegacyfinish); + stream4.removeListener("finish", onfinish); + stream4.removeListener("end", onend); + stream4.removeListener("error", onerror); + stream4.removeListener("close", onclose); }; - }; + } + module2.exports = eos; } }); -// node_modules/color-string/index.js -var require_color_string = __commonJS({ - "node_modules/color-string/index.js"(exports2, module2) { - var colorNames = require_color_name(); - var swizzle = require_simple_swizzle(); - var hasOwnProperty2 = Object.hasOwnProperty; - var reverseNames = /* @__PURE__ */ Object.create(null); - for (name in colorNames) { - if (hasOwnProperty2.call(colorNames, name)) { - reverseNames[colorNames[name]] = name; +// node_modules/readable-stream/lib/internal/streams/async_iterator.js +var require_async_iterator = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/async_iterator.js"(exports2, module2) { + "use strict"; + var _Object$setPrototypeO; + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; } + return obj; } - var name; - var cs = module2.exports = { - to: {}, - get: {} - }; - cs.get = function(string) { - var prefix = string.substring(0, 3).toLowerCase(); - var val; - var model; - switch (prefix) { - case "hsl": - val = cs.get.hsl(string); - model = "hsl"; - break; - case "hwb": - val = cs.get.hwb(string); - model = "hwb"; - break; - default: - val = cs.get.rgb(string); - model = "rgb"; - break; - } - if (!val) { - return null; - } - return { model, value: val }; - }; - cs.get.rgb = function(string) { - if (!string) { - return null; + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); } - var abbr = /^#([a-f0-9]{3,4})$/i; - var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i; - var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; - var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; - var keyword = /^(\w+)$/; - var rgb = [0, 0, 0, 1]; - var match; - var i; - var hexAlpha; - if (match = string.match(hex)) { - hexAlpha = match[2]; - match = match[1]; - for (i = 0; i < 3; i++) { - var i2 = i * 2; - rgb[i] = parseInt(match.slice(i2, i2 + 2), 16); - } - if (hexAlpha) { - rgb[3] = parseInt(hexAlpha, 16) / 255; + return (hint === "string" ? String : Number)(input); + } + var finished = require_end_of_stream(); + var kLastResolve = Symbol("lastResolve"); + var kLastReject = Symbol("lastReject"); + var kError = Symbol("error"); + var kEnded = Symbol("ended"); + var kLastPromise = Symbol("lastPromise"); + var kHandlePromise = Symbol("handlePromise"); + var kStream = Symbol("stream"); + function createIterResult(value, done) { + return { + value, + done + }; + } + function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); } - } else if (match = string.match(abbr)) { - match = match[1]; - hexAlpha = match[3]; - for (i = 0; i < 3; i++) { - rgb[i] = parseInt(match[i] + match[i], 16); + } + } + function onReadable(iter) { + process.nextTick(readAndResolve, iter); + } + function wrapForNext(lastPromise, iter) { + return function(resolve, reject) { + lastPromise.then(function() { + if (iter[kEnded]) { + resolve(createIterResult(void 0, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; + } + var AsyncIteratorPrototype = Object.getPrototypeOf(function() { + }); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); } - if (hexAlpha) { - rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255; + if (this[kEnded]) { + return Promise.resolve(createIterResult(void 0, true)); } - } else if (match = string.match(rgba)) { - for (i = 0; i < 3; i++) { - rgb[i] = parseInt(match[i + 1], 0); + if (this[kStream].destroyed) { + return new Promise(function(resolve, reject) { + process.nextTick(function() { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(void 0, true)); + } + }); + }); } - if (match[4]) { - if (match[5]) { - rgb[3] = parseFloat(match[4]) * 0.01; - } else { - rgb[3] = parseFloat(match[4]); + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); } + promise = new Promise(this[kHandlePromise]); } - } else if (match = string.match(per)) { - for (i = 0; i < 3; i++) { - rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); - } - if (match[4]) { - if (match[5]) { - rgb[3] = parseFloat(match[4]) * 0.01; + this[kLastPromise] = promise; + return promise; + } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + return new Promise(function(resolve, reject) { + _this2[kStream].destroy(null, function(err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(void 0, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream4) { + var _Object$create; + var iterator2 = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream4, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream4._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator2[kStream].read(); + if (data) { + iterator2[kLastPromise] = null; + iterator2[kLastResolve] = null; + iterator2[kLastReject] = null; + resolve(createIterResult(data, false)); } else { - rgb[3] = parseFloat(match[4]); + iterator2[kLastResolve] = resolve; + iterator2[kLastReject] = reject; } + }, + writable: true + }), _Object$create)); + iterator2[kLastPromise] = null; + finished(stream4, function(err) { + if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + var reject = iterator2[kLastReject]; + if (reject !== null) { + iterator2[kLastPromise] = null; + iterator2[kLastResolve] = null; + iterator2[kLastReject] = null; + reject(err); + } + iterator2[kError] = err; + return; } - } else if (match = string.match(keyword)) { - if (match[1] === "transparent") { - return [0, 0, 0, 0]; - } - if (!hasOwnProperty2.call(colorNames, match[1])) { - return null; + var resolve = iterator2[kLastResolve]; + if (resolve !== null) { + iterator2[kLastPromise] = null; + iterator2[kLastResolve] = null; + iterator2[kLastReject] = null; + resolve(createIterResult(void 0, true)); } - rgb = colorNames[match[1]]; - rgb[3] = 1; - return rgb; + iterator2[kEnded] = true; + }); + stream4.on("readable", onReadable.bind(null, iterator2)); + return iterator2; + }; + module2.exports = createReadableStreamAsyncIterator; + } +}); + +// node_modules/readable-stream/lib/internal/streams/from.js +var require_from = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/from.js"(exports2, module2) { + "use strict"; + function asyncGeneratorStep(gen3, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen3[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + if (info.done) { + resolve(value); } else { - return null; + Promise.resolve(value).then(_next, _throw); } - for (i = 0; i < 3; i++) { - rgb[i] = clamp(rgb[i], 0, 255); + } + function _asyncToGenerator(fn2) { + return function() { + var self2 = this, args = arguments; + return new Promise(function(resolve, reject) { + var gen3 = fn2.apply(self2, args); + function _next(value) { + asyncGeneratorStep(gen3, resolve, reject, _next, _throw, "next", value); + } + function _throw(err) { + asyncGeneratorStep(gen3, resolve, reject, _next, _throw, "throw", err); + } + _next(void 0); + }); + }; + } + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys.push.apply(keys, symbols); } - rgb[3] = clamp(rgb[3], 0, 1); - return rgb; - }; - cs.get.hsl = function(string) { - if (!string) { - return null; + return keys; + } + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } - var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; - var match = string.match(hsl); - if (match) { - var alpha = parseFloat(match[4]); - var h = (parseFloat(match[1]) % 360 + 360) % 360; - var s = clamp(parseFloat(match[2]), 0, 100); - var l = clamp(parseFloat(match[3]), 0, 100); - var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); - return [h, s, l, a]; + return target; + } + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; } - return null; - }; - cs.get.hwb = function(string) { - if (!string) { - return null; + return obj; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); } - var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; - var match = string.match(hwb); - if (match) { - var alpha = parseFloat(match[4]); - var h = (parseFloat(match[1]) % 360 + 360) % 360; - var w2 = clamp(parseFloat(match[2]), 0, 100); - var b2 = clamp(parseFloat(match[3]), 0, 100); - var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); - return [h, w2, b2, a]; + return (hint === "string" ? String : Number)(input); + } + var ERR_INVALID_ARG_TYPE = require_errors2().codes.ERR_INVALID_ARG_TYPE; + function from5(Readable2, iterable, opts) { + var iterator2; + if (iterable && typeof iterable.next === "function") { + iterator2 = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator2 = iterable[Symbol.asyncIterator](); + else if (iterable && iterable[Symbol.iterator]) iterator2 = iterable[Symbol.iterator](); + else throw new ERR_INVALID_ARG_TYPE("iterable", ["Iterable"], iterable); + var readable = new Readable2(_objectSpread({ + objectMode: true + }, opts)); + var reading = false; + readable._read = function() { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); } - return null; - }; - cs.to.hex = function() { - var rgba = swizzle(arguments); - return "#" + hexDouble(rgba[0]) + hexDouble(rgba[1]) + hexDouble(rgba[2]) + (rgba[3] < 1 ? hexDouble(Math.round(rgba[3] * 255)) : ""); - }; - cs.to.rgb = function() { - var rgba = swizzle(arguments); - return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ")" : "rgba(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ", " + rgba[3] + ")"; - }; - cs.to.rgb.percent = function() { - var rgba = swizzle(arguments); - var r = Math.round(rgba[0] / 255 * 100); - var g = Math.round(rgba[1] / 255 * 100); - var b2 = Math.round(rgba[2] / 255 * 100); - return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + r + "%, " + g + "%, " + b2 + "%)" : "rgba(" + r + "%, " + g + "%, " + b2 + "%, " + rgba[3] + ")"; - }; - cs.to.hsl = function() { - var hsla = swizzle(arguments); - return hsla.length < 4 || hsla[3] === 1 ? "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)" : "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + hsla[3] + ")"; - }; - cs.to.hwb = function() { - var hwba = swizzle(arguments); - var a = ""; - if (hwba.length >= 4 && hwba[3] !== 1) { - a = ", " + hwba[3]; + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator2.next(), value = _yield$iterator$next.value, done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); } - return "hwb(" + hwba[0] + ", " + hwba[1] + "%, " + hwba[2] + "%" + a + ")"; - }; - cs.to.keyword = function(rgb) { - return reverseNames[rgb.slice(0, 3)]; - }; - function clamp(num2, min, max) { - return Math.min(Math.max(min, num2), max); - } - function hexDouble(num2) { - var str = Math.round(num2).toString(16).toUpperCase(); - return str.length < 2 ? "0" + str : str; + return readable; } + module2.exports = from5; } }); -// node_modules/color/node_modules/color-convert/node_modules/color-name/index.js -var require_color_name2 = __commonJS({ - "node_modules/color/node_modules/color-convert/node_modules/color-name/index.js"(exports2, module2) { +// node_modules/readable-stream/lib/_stream_readable.js +var require_stream_readable = __commonJS({ + "node_modules/readable-stream/lib/_stream_readable.js"(exports2, module2) { "use strict"; - module2.exports = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] + module2.exports = Readable2; + var Duplex; + Readable2.ReadableState = ReadableState; + var EE = __require("events").EventEmitter; + var EElistenerCount = function EElistenerCount2(emitter, type) { + return emitter.listeners(type).length; }; - } -}); - -// node_modules/color/node_modules/color-convert/conversions.js -var require_conversions = __commonJS({ - "node_modules/color/node_modules/color-convert/conversions.js"(exports2, module2) { - var cssKeywords = require_color_name2(); - var reverseKeywords = {}; - for (key in cssKeywords) { - if (cssKeywords.hasOwnProperty(key)) { - reverseKeywords[cssKeywords[key]] = key; + var Stream = require_stream(); + var Buffer2 = __require("buffer").Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var debugUtil = __require("util"); + var debug; + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog("stream"); + } else { + debug = function debug2() { + }; + } + var BufferList = require_buffer_list(); + var destroyImpl = require_destroy(); + var _require = require_state(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors2().codes; + var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; + var ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + var StringDecoder; + var createReadableStreamAsyncIterator; + var from5; + require_inherits()(Readable2, Stream); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + function prependListener(emitter, event, fn2) { + if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn2); + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn2); + else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn2); + else emitter._events[event] = [fn2, emitter._events[event]]; + } + function ReadableState(options, stream4, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream4 instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + this.sync = true; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + this.emitClose = options.emitClose !== false; + this.autoDestroy = !!options.autoDestroy; + this.destroyed = false; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.awaitDrain = 0; + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; } } - var key; - var convert = module2.exports = { - rgb: { channels: 3, labels: "rgb" }, - hsl: { channels: 3, labels: "hsl" }, - hsv: { channels: 3, labels: "hsv" }, - hwb: { channels: 3, labels: "hwb" }, - cmyk: { channels: 4, labels: "cmyk" }, - xyz: { channels: 3, labels: "xyz" }, - lab: { channels: 3, labels: "lab" }, - lch: { channels: 3, labels: "lch" }, - hex: { channels: 1, labels: ["hex"] }, - keyword: { channels: 1, labels: ["keyword"] }, - ansi16: { channels: 1, labels: ["ansi16"] }, - ansi256: { channels: 1, labels: ["ansi256"] }, - hcg: { channels: 3, labels: ["h", "c", "g"] }, - apple: { channels: 3, labels: ["r16", "g16", "b16"] }, - gray: { channels: 1, labels: ["gray"] } - }; - for (model in convert) { - if (convert.hasOwnProperty(model)) { - if (!("channels" in convert[model])) { - throw new Error("missing channels property: " + model); - } - if (!("labels" in convert[model])) { - throw new Error("missing channel labels property: " + model); - } - if (convert[model].labels.length !== convert[model].channels) { - throw new Error("channel and label counts mismatch: " + model); - } - channels = convert[model].channels; - labels = convert[model].labels; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], "channels", { value: channels }); - Object.defineProperty(convert[model], "labels", { value: labels }); + function Readable2(options) { + Duplex = Duplex || require_stream_duplex(); + if (!(this instanceof Readable2)) return new Readable2(options); + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + this.readable = true; + if (options) { + if (typeof options.read === "function") this._read = options.read; + if (typeof options.destroy === "function") this._destroy = options.destroy; } + Stream.call(this); } - var channels; - var labels; - var model; - convert.rgb.hsl = function(rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b2 = rgb[2] / 255; - var min = Math.min(r, g, b2); - var max = Math.max(r, g, b2); - var delta = max - min; - var h; - var s; - var l; - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b2) / delta; - } else if (g === max) { - h = 2 + (b2 - r) / delta; - } else if (b2 === max) { - h = 4 + (r - g) / delta; - } - h = Math.min(h * 60, 360); - if (h < 0) { - h += 360; + Object.defineProperty(Readable2.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === void 0) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; } - l = (min + max) / 2; - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); + }); + Readable2.prototype.destroy = destroyImpl.destroy; + Readable2.prototype._undestroy = destroyImpl.undestroy; + Readable2.prototype._destroy = function(err, cb) { + cb(err); + }; + Readable2.prototype.push = function(chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === "string") { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer2.from(chunk, encoding); + encoding = ""; + } + skipChunkCheck = true; + } } else { - s = delta / (2 - max - min); + skipChunkCheck = true; } - return [h, s * 100, l * 100]; + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; - convert.rgb.hsv = function(rgb) { - var rdif; - var gdif; - var bdif; - var h; - var s; - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b2 = rgb[2] / 255; - var v = Math.max(r, g, b2); - var diff = v - Math.min(r, g, b2); - var diffc = function(c) { - return (v - c) / 6 / diff + 1 / 2; - }; - if (diff === 0) { - h = s = 0; + Readable2.prototype.unshift = function(chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream4, chunk, encoding, addToFront, skipChunkCheck) { + debug("readableAddChunk", chunk); + var state = stream4._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream4, state); } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b2); - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = 1 / 3 + rdif - bdif; - } else if (b2 === v) { - h = 2 / 3 + gdif - rdif; - } - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; + var er2; + if (!skipChunkCheck) er2 = chunkInvalid(state, chunk); + if (er2) { + errorOrDestroy(stream4, er2); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream4, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else addChunk(stream4, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream4, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream4, state, chunk, false); + else maybeReadMore(stream4, state); + } else { + addChunk(stream4, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream4, state); } } - return [ - h * 360, - s * 100, - v * 100 - ]; - }; - convert.rgb.hwb = function(rgb) { - var r = rgb[0]; - var g = rgb[1]; - var b2 = rgb[2]; - var h = convert.rgb.hsl(rgb)[0]; - var w2 = 1 / 255 * Math.min(r, Math.min(g, b2)); - b2 = 1 - 1 / 255 * Math.max(r, Math.max(g, b2)); - return [h, w2 * 100, b2 * 100]; - }; - convert.rgb.cmyk = function(rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b2 = rgb[2] / 255; - var c; - var m2; - var y2; - var k2; - k2 = Math.min(1 - r, 1 - g, 1 - b2); - c = (1 - r - k2) / (1 - k2) || 0; - m2 = (1 - g - k2) / (1 - k2) || 0; - y2 = (1 - b2 - k2) / (1 - k2) || 0; - return [c * 100, m2 * 100, y2 * 100, k2 * 100]; - }; - function comparativeDistance(x2, y2) { - return Math.pow(x2[0] - y2[0], 2) + Math.pow(x2[1] - y2[1], 2) + Math.pow(x2[2] - y2[2], 2); + return !state.ended && (state.length < state.highWaterMark || state.length === 0); } - convert.rgb.keyword = function(rgb) { - var reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; + function addChunk(stream4, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream4.emit("data", chunk); + } else { + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk); + else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream4); } - var currentClosestDistance = Infinity; - var currentClosestKeyword; - for (var keyword in cssKeywords) { - if (cssKeywords.hasOwnProperty(keyword)) { - var value = cssKeywords[keyword]; - var distance = comparativeDistance(rgb, value); - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } + maybeReadMore(stream4, state); + } + function chunkInvalid(state, chunk) { + var er2; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) { + er2 = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); } - return currentClosestKeyword; - }; - convert.keyword.rgb = function(keyword) { - return cssKeywords[keyword]; - }; - convert.rgb.xyz = function(rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b2 = rgb[2] / 255; - r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; - g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; - b2 = b2 > 0.04045 ? Math.pow((b2 + 0.055) / 1.055, 2.4) : b2 / 12.92; - var x2 = r * 0.4124 + g * 0.3576 + b2 * 0.1805; - var y2 = r * 0.2126 + g * 0.7152 + b2 * 0.0722; - var z = r * 0.0193 + g * 0.1192 + b2 * 0.9505; - return [x2 * 100, y2 * 100, z * 100]; + return er2; + } + Readable2.prototype.isPaused = function() { + return this._readableState.flowing === false; }; - convert.rgb.lab = function(rgb) { - var xyz = convert.rgb.xyz(rgb); - var x2 = xyz[0]; - var y2 = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b2; - x2 /= 95.047; - y2 /= 100; - z /= 108.883; - x2 = x2 > 8856e-6 ? Math.pow(x2, 1 / 3) : 7.787 * x2 + 16 / 116; - y2 = y2 > 8856e-6 ? Math.pow(y2, 1 / 3) : 7.787 * y2 + 16 / 116; - z = z > 8856e-6 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; - l = 116 * y2 - 16; - a = 500 * (x2 - y2); - b2 = 200 * (y2 - z); - return [l, a, b2]; + Readable2.prototype.setEncoding = function(enc) { + if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + this._readableState.encoding = this._readableState.decoder.encoding; + var p = this._readableState.buffer.head; + var content = ""; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== "") this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; }; - convert.hsl.rgb = function(hsl) { - var h = hsl[0] / 360; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var t1; - var t2; - var t3; - var rgb; - var val; - if (s === 0) { - val = l * 255; - return [val, val, val]; + var MAX_HWM = 1073741824; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; } - if (l < 0.5) { - t2 = l * (1 + s); + return n; + } + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + if (state.flowing && state.length) return state.buffer.head.data.length; + else return state.length; + } + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + Readable2.prototype.read = function(n) { + debug("read", n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug("read: emitReadable", state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this); + else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + var doRead = state.needReadable; + debug("need readable", doRead); + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug("length less than watermark", doRead); + } + if (state.ended || state.reading) { + doRead = false; + debug("reading or ended", doRead); + } else if (doRead) { + debug("do read"); + state.reading = true; + state.sync = true; + if (state.length === 0) state.needReadable = true; + this._read(state.highWaterMark); + state.sync = false; + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state); + else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; } else { - t2 = l + s - l * s; + state.length -= n; + state.awaitDrain = 0; } - t1 = 2 * l - t2; - rgb = [0, 0, 0]; - for (var i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - if (t3 > 1) { - t3--; + if (state.length === 0) { + if (!state.ended) state.needReadable = true; + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit("data", ret); + return ret; + }; + function onEofChunk(stream4, state) { + debug("onEofChunk"); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; + } + state.ended = true; + if (state.sync) { + emitReadable(stream4); + } else { + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream4); } - rgb[i] = val * 255; } - return rgb; - }; - convert.hsl.hsv = function(hsl) { - var h = hsl[0]; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var smin = s; - var lmin = Math.max(l, 0.01); - var sv; - var v; - l *= 2; - s *= l <= 1 ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - v = (l + s) / 2; - sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); - return [h, sv * 100, v * 100]; - }; - convert.hsv.rgb = function(hsv) { - var h = hsv[0] / 60; - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var hi2 = Math.floor(h) % 6; - var f = h - Math.floor(h); - var p = 255 * v * (1 - s); - var q2 = 255 * v * (1 - s * f); - var t = 255 * v * (1 - s * (1 - f)); - v *= 255; - switch (hi2) { - case 0: - return [v, t, p]; - case 1: - return [q2, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q2, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q2]; + } + function emitReadable(stream4) { + var state = stream4._readableState; + debug("emitReadable", state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug("emitReadable", state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream4); + } + } + function emitReadable_(stream4) { + var state = stream4._readableState; + debug("emitReadable_", state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream4.emit("readable"); + state.emittedReadable = false; } - }; - convert.hsv.hsl = function(hsv) { - var h = hsv[0]; - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var vmin = Math.max(v, 0.01); - var lmin; - var sl2; - var l; - l = (2 - s) * v; - lmin = (2 - s) * vmin; - sl2 = s * vmin; - sl2 /= lmin <= 1 ? lmin : 2 - lmin; - sl2 = sl2 || 0; - l /= 2; - return [h, sl2 * 100, l * 100]; - }; - convert.hwb.rgb = function(hwb) { - var h = hwb[0] / 360; - var wh = hwb[1] / 100; - var bl2 = hwb[2] / 100; - var ratio = wh + bl2; - var i; - var v; - var f; - var n; - if (ratio > 1) { - wh /= ratio; - bl2 /= ratio; + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream4); + } + function maybeReadMore(stream4, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream4, state); } - i = Math.floor(6 * h); - v = 1 - bl2; - f = 6 * h - i; - if ((i & 1) !== 0) { - f = 1 - f; + } + function maybeReadMore_(stream4, state) { + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug("maybeReadMore read 0"); + stream4.read(0); + if (len === state.length) + break; } - n = wh + f * (v - wh); - var r; - var g; - var b2; - switch (i) { - default: - case 6: + state.readingMore = false; + } + Readable2.prototype._read = function(n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); + }; + Readable2.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { case 0: - r = v; - g = n; - b2 = wh; + state.pipes = dest; break; case 1: - r = n; - g = v; - b2 = wh; - break; - case 2: - r = wh; - g = v; - b2 = n; - break; - case 3: - r = wh; - g = n; - b2 = v; - break; - case 4: - r = n; - g = wh; - b2 = v; + state.pipes = [state.pipes, dest]; break; - case 5: - r = v; - g = wh; - b2 = n; + default: + state.pipes.push(dest); break; } - return [r * 255, g * 255, b2 * 255]; - }; - convert.cmyk.rgb = function(cmyk) { - var c = cmyk[0] / 100; - var m2 = cmyk[1] / 100; - var y2 = cmyk[2] / 100; - var k2 = cmyk[3] / 100; - var r; - var g; - var b2; - r = 1 - Math.min(1, c * (1 - k2) + k2); - g = 1 - Math.min(1, m2 * (1 - k2) + k2); - b2 = 1 - Math.min(1, y2 * (1 - k2) + k2); - return [r * 255, g * 255, b2 * 255]; - }; - convert.xyz.rgb = function(xyz) { - var x2 = xyz[0] / 100; - var y2 = xyz[1] / 100; - var z = xyz[2] / 100; - var r; - var g; - var b2; - r = x2 * 3.2406 + y2 * -1.5372 + z * -0.4986; - g = x2 * -0.9689 + y2 * 1.8758 + z * 0.0415; - b2 = x2 * 0.0557 + y2 * -0.204 + z * 1.057; - r = r > 31308e-7 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : r * 12.92; - g = g > 31308e-7 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : g * 12.92; - b2 = b2 > 31308e-7 ? 1.055 * Math.pow(b2, 1 / 2.4) - 0.055 : b2 * 12.92; - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b2 = Math.min(Math.max(0, b2), 1); - return [r * 255, g * 255, b2 * 255]; - }; - convert.xyz.lab = function(xyz) { - var x2 = xyz[0]; - var y2 = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b2; - x2 /= 95.047; - y2 /= 100; - z /= 108.883; - x2 = x2 > 8856e-6 ? Math.pow(x2, 1 / 3) : 7.787 * x2 + 16 / 116; - y2 = y2 > 8856e-6 ? Math.pow(y2, 1 / 3) : 7.787 * y2 + 16 / 116; - z = z > 8856e-6 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; - l = 116 * y2 - 16; - a = 500 * (x2 - y2); - b2 = 200 * (y2 - z); - return [l, a, b2]; - }; - convert.lab.xyz = function(lab) { - var l = lab[0]; - var a = lab[1]; - var b2 = lab[2]; - var x2; - var y2; - var z; - y2 = (l + 16) / 116; - x2 = a / 500 + y2; - z = y2 - b2 / 200; - var y22 = Math.pow(y2, 3); - var x22 = Math.pow(x2, 3); - var z2 = Math.pow(z, 3); - y2 = y22 > 8856e-6 ? y22 : (y2 - 16 / 116) / 7.787; - x2 = x22 > 8856e-6 ? x22 : (x2 - 16 / 116) / 7.787; - z = z2 > 8856e-6 ? z2 : (z - 16 / 116) / 7.787; - x2 *= 95.047; - y2 *= 100; - z *= 108.883; - return [x2, y2, z]; - }; - convert.lab.lch = function(lab) { - var l = lab[0]; - var a = lab[1]; - var b2 = lab[2]; - var hr2; - var h; - var c; - hr2 = Math.atan2(b2, a); - h = hr2 * 360 / 2 / Math.PI; - if (h < 0) { - h += 360; + state.pipesCount += 1; + debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn); + else src.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable, unpipeInfo) { + debug("onunpipe"); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } } - c = Math.sqrt(a * a + b2 * b2); - return [l, c, h]; - }; - convert.lch.lab = function(lch) { - var l = lch[0]; - var c = lch[1]; - var h = lch[2]; - var a; - var b2; - var hr2; - hr2 = h / 360 * 2 * Math.PI; - a = c * Math.cos(hr2); - b2 = c * Math.sin(hr2); - return [l, a, b2]; - }; - convert.rgb.ansi16 = function(args) { - var r = args[0]; - var g = args[1]; - var b2 = args[2]; - var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; - value = Math.round(value / 50); - if (value === 0) { - return 30; + function onend() { + debug("onend"); + dest.end(); } - var ansi = 30 + (Math.round(b2 / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); - if (value === 2) { - ansi += 60; + var ondrain = pipeOnDrain(src); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src.removeListener("end", onend); + src.removeListener("end", unpipe); + src.removeListener("data", ondata); + cleanedUp = true; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - return ansi; - }; - convert.hsv.ansi16 = function(args) { - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); - }; - convert.rgb.ansi256 = function(args) { - var r = args[0]; - var g = args[1]; - var b2 = args[2]; - if (r === g && g === b2) { - if (r < 8) { - return 16; + src.on("data", ondata); + function ondata(chunk) { + debug("ondata"); + var ret = dest.write(chunk); + debug("dest.write", ret); + if (ret === false) { + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug("false write response, pause", state.awaitDrain); + state.awaitDrain++; + } + src.pause(); } - if (r > 248) { - return 231; + } + function onerror(er2) { + debug("onerror", er2); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er2); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug("unpipe"); + src.unpipe(dest); + } + dest.emit("pipe", src); + if (!state.flowing) { + debug("pipe resume"); + src.resume(); + } + return dest; + }; + function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug("pipeOnDrain", state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, "data")) { + state.flowing = true; + flow(src); } - return Math.round((r - 8) / 247 * 24) + 232; + }; + } + Readable2.prototype.unpipe = function(dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + if (state.pipesCount === 0) return this; + if (state.pipesCount === 1) { + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit("unpipe", this, unpipeInfo); + return this; } - var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b2 / 255 * 5); - return ansi; + if (!dest) { + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit("unpipe", this, { + hasUnpiped: false + }); + return this; + } + var index2 = indexOf(state.pipes, dest); + if (index2 === -1) return this; + state.pipes.splice(index2, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit("unpipe", this, unpipeInfo); + return this; }; - convert.ansi16.rgb = function(args) { - var color = args % 10; - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; + Readable2.prototype.on = function(ev, fn2) { + var res = Stream.prototype.on.call(this, ev, fn2); + var state = this._readableState; + if (ev === "data") { + state.readableListening = this.listenerCount("readable") > 0; + if (state.flowing !== false) this.resume(); + } else if (ev === "readable") { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug("on readable", state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } } - color = color / 10.5 * 255; - return [color, color, color]; } - var mult = (~~(args > 50) + 1) * 0.5; - var r = (color & 1) * mult * 255; - var g = (color >> 1 & 1) * mult * 255; - var b2 = (color >> 2 & 1) * mult * 255; - return [r, g, b2]; + return res; }; - convert.ansi256.rgb = function(args) { - if (args >= 232) { - var c = (args - 232) * 10 + 8; - return [c, c, c]; + Readable2.prototype.addListener = Readable2.prototype.on; + Readable2.prototype.removeListener = function(ev, fn2) { + var res = Stream.prototype.removeListener.call(this, ev, fn2); + if (ev === "readable") { + process.nextTick(updateReadableListening, this); } - args -= 16; - var rem; - var r = Math.floor(args / 36) / 5 * 255; - var g = Math.floor((rem = args % 36) / 6) / 5 * 255; - var b2 = rem % 6 / 5 * 255; - return [r, g, b2]; + return res; }; - convert.rgb.hex = function(args) { - var integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255); - var string = integer.toString(16).toUpperCase(); - return "000000".substring(string.length) + string; + Readable2.prototype.removeAllListeners = function(ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === "readable" || ev === void 0) { + process.nextTick(updateReadableListening, this); + } + return res; }; - convert.hex.rgb = function(args) { - var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; + function updateReadableListening(self2) { + var state = self2._readableState; + state.readableListening = self2.listenerCount("readable") > 0; + if (state.resumeScheduled && !state.paused) { + state.flowing = true; + } else if (self2.listenerCount("data") > 0) { + self2.resume(); } - var colorString = match[0]; - if (match[0].length === 3) { - colorString = colorString.split("").map(function(char) { - return char + char; - }).join(""); + } + function nReadingNextTick(self2) { + debug("readable nexttick read 0"); + self2.read(0); + } + Readable2.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug("resume"); + state.flowing = !state.readableListening; + resume(this, state); } - var integer = parseInt(colorString, 16); - var r = integer >> 16 & 255; - var g = integer >> 8 & 255; - var b2 = integer & 255; - return [r, g, b2]; + state.paused = false; + return this; }; - convert.rgb.hcg = function(rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b2 = rgb[2] / 255; - var max = Math.max(Math.max(r, g), b2); - var min = Math.min(Math.min(r, g), b2); - var chroma = max - min; - var grayscale; - var hue; - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; + function resume(stream4, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream4, state); } - if (chroma <= 0) { - hue = 0; - } else if (max === r) { - hue = (g - b2) / chroma % 6; - } else if (max === g) { - hue = 2 + (b2 - r) / chroma; - } else { - hue = 4 + (r - g) / chroma + 4; + } + function resume_(stream4, state) { + debug("resume", state.reading); + if (!state.reading) { + stream4.read(0); } - hue /= 6; - hue %= 1; - return [hue * 360, chroma * 100, grayscale * 100]; - }; - convert.hsl.hcg = function(hsl) { - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var c = 1; - var f = 0; - if (l < 0.5) { - c = 2 * s * l; - } else { - c = 2 * s * (1 - l); + state.resumeScheduled = false; + stream4.emit("resume"); + flow(stream4); + if (state.flowing && !state.reading) stream4.read(0); + } + Readable2.prototype.pause = function() { + debug("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug("pause"); + this._readableState.flowing = false; + this.emit("pause"); } - if (c < 1) { - f = (l - 0.5 * c) / (1 - c); + this._readableState.paused = true; + return this; + }; + function flow(stream4) { + var state = stream4._readableState; + debug("flow", state.flowing); + while (state.flowing && stream4.read() !== null) ; + } + Readable2.prototype.wrap = function(stream4) { + var _this = this; + var state = this._readableState; + var paused = false; + stream4.on("end", function() { + debug("wrapped end"); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream4.on("data", function(chunk) { + debug("wrapped data"); + if (state.decoder) chunk = state.decoder.write(chunk); + if (state.objectMode && (chunk === null || chunk === void 0)) return; + else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream4.pause(); + } + }); + for (var i in stream4) { + if (this[i] === void 0 && typeof stream4[i] === "function") { + this[i] = /* @__PURE__ */ function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream4[method].apply(stream4, arguments); + }; + }(i); + } } - return [hsl[0], c * 100, f * 100]; - }; - convert.hsv.hcg = function(hsv) { - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var c = s * v; - var f = 0; - if (c < 1) { - f = (v - c) / (1 - c); + for (var n = 0; n < kProxyEvents.length; n++) { + stream4.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } - return [hsv[0], c * 100, f * 100]; + this._read = function(n2) { + debug("wrapped _read", n2); + if (paused) { + paused = false; + stream4.resume(); + } + }; + return this; }; - convert.hcg.rgb = function(hcg) { - var h = hcg[0] / 360; - var c = hcg[1] / 100; - var g = hcg[2] / 100; - if (c === 0) { - return [g * 255, g * 255, g * 255]; + if (typeof Symbol === "function") { + Readable2.prototype[Symbol.asyncIterator] = function() { + if (createReadableStreamAsyncIterator === void 0) { + createReadableStreamAsyncIterator = require_async_iterator(); + } + return createReadableStreamAsyncIterator(this); + }; + } + Object.defineProperty(Readable2.prototype, "readableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; } - var pure = [0, 0, 0]; - var hi2 = h % 1 * 6; - var v = hi2 % 1; - var w2 = 1 - v; - var mg = 0; - switch (Math.floor(hi2)) { - case 0: - pure[0] = 1; - pure[1] = v; - pure[2] = 0; - break; - case 1: - pure[0] = w2; - pure[1] = 1; - pure[2] = 0; - break; - case 2: - pure[0] = 0; - pure[1] = 1; - pure[2] = v; - break; - case 3: - pure[0] = 0; - pure[1] = w2; - pure[2] = 1; - break; - case 4: - pure[0] = v; - pure[1] = 0; - pure[2] = 1; - break; - default: - pure[0] = 1; - pure[1] = 0; - pure[2] = w2; + }); + Object.defineProperty(Readable2.prototype, "readableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; } - mg = (1 - c) * g; - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; - }; - convert.hcg.hsv = function(hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - var v = c + g * (1 - c); - var f = 0; - if (v > 0) { - f = c / v; + }); + Object.defineProperty(Readable2.prototype, "readableFlowing", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } } - return [hcg[0], f * 100, v * 100]; - }; - convert.hcg.hsl = function(hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - var l = g * (1 - c) + 0.5 * c; - var s = 0; - if (l > 0 && l < 0.5) { - s = c / (2 * l); - } else if (l >= 0.5 && l < 1) { - s = c / (2 * (1 - l)); + }); + Readable2._fromList = fromList; + Object.defineProperty(Readable2.prototype, "readableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; } - return [hcg[0], s * 100, l * 100]; - }; - convert.hcg.hwb = function(hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - var v = c + g * (1 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; - }; - convert.hwb.hcg = function(hwb) { - var w2 = hwb[1] / 100; - var b2 = hwb[2] / 100; - var v = 1 - b2; - var c = v - w2; - var g = 0; - if (c < 1) { - g = (v - c) / (1 - c); + }); + function fromList(n, state) { + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift(); + else if (!n || n >= state.length) { + if (state.decoder) ret = state.buffer.join(""); + else if (state.buffer.length === 1) ret = state.buffer.first(); + else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + ret = state.buffer.consume(n, state.decoder); } - return [hwb[0], c * 100, g * 100]; - }; - convert.apple.rgb = function(apple) { - return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; - }; - convert.rgb.apple = function(rgb) { - return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; - }; - convert.gray.rgb = function(args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; - }; - convert.gray.hsl = convert.gray.hsv = function(args) { - return [0, 0, args[0]]; - }; - convert.gray.hwb = function(gray) { - return [0, 100, gray[0]]; - }; - convert.gray.cmyk = function(gray) { - return [0, 0, 0, gray[0]]; - }; - convert.gray.lab = function(gray) { - return [gray[0], 0, 0]; - }; - convert.gray.hex = function(gray) { - var val = Math.round(gray[0] / 100 * 255) & 255; - var integer = (val << 16) + (val << 8) + val; - var string = integer.toString(16).toUpperCase(); - return "000000".substring(string.length) + string; - }; - convert.rgb.gray = function(rgb) { - var val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; - }; - } -}); - -// node_modules/color/node_modules/color-convert/route.js -var require_route = __commonJS({ - "node_modules/color/node_modules/color-convert/route.js"(exports2, module2) { - var conversions = require_conversions(); - function buildGraph() { - var graph = {}; - var models = Object.keys(conversions); - for (var len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; + return ret; + } + function endReadable(stream4) { + var state = stream4._readableState; + debug("endReadable", state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream4); } - return graph; } - function deriveBFS(fromModel) { - var graph = buildGraph(); - var queue = [fromModel]; - graph[fromModel].distance = 0; - while (queue.length) { - var current = queue.pop(); - var adjacents = Object.keys(conversions[current]); - for (var len = adjacents.length, i = 0; i < len; i++) { - var adjacent = adjacents[i]; - var node = graph[adjacent]; - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); + function endReadableNT(state, stream4) { + debug("endReadableNT", state.endEmitted, state.length); + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream4.readable = false; + stream4.emit("end"); + if (state.autoDestroy) { + var wState = stream4._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream4.destroy(); } } } - return graph; } - function link(from5, to2) { - return function(args) { - return to2(from5(args)); + if (typeof Symbol === "function") { + Readable2.from = function(iterable, opts) { + if (from5 === void 0) { + from5 = require_from(); + } + return from5(Readable2, iterable, opts); }; } - function wrapConversion(toModel, graph) { - var path = [graph[toModel].parent, toModel]; - var fn2 = conversions[graph[toModel].parent][toModel]; - var cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn2 = link(conversions[graph[cur].parent][cur], fn2); - cur = graph[cur].parent; + function indexOf(xs2, x2) { + for (var i = 0, l = xs2.length; i < l; i++) { + if (xs2[i] === x2) return i; } - fn2.conversion = path; - return fn2; + return -1; } - module2.exports = function(fromModel) { - var graph = deriveBFS(fromModel); - var conversion = {}; - var models = Object.keys(graph); - for (var len = models.length, i = 0; i < len; i++) { - var toModel = models[i]; - var node = graph[toModel]; - if (node.parent === null) { - continue; - } - conversion[toModel] = wrapConversion(toModel, graph); - } - return conversion; - }; } }); -// node_modules/color/node_modules/color-convert/index.js -var require_color_convert = __commonJS({ - "node_modules/color/node_modules/color-convert/index.js"(exports2, module2) { - var conversions = require_conversions(); - var route = require_route(); - var convert = {}; - var models = Object.keys(conversions); - function wrapRaw(fn2) { - var wrappedFn = function(args) { - if (args === void 0 || args === null) { - return args; - } - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); +// node_modules/readable-stream/lib/_stream_duplex.js +var require_stream_duplex = __commonJS({ + "node_modules/readable-stream/lib/_stream_duplex.js"(exports2, module2) { + "use strict"; + var objectKeys = Object.keys || function(obj) { + var keys2 = []; + for (var key in obj) keys2.push(key); + return keys2; + }; + module2.exports = Duplex; + var Readable2 = require_stream_readable(); + var Writable = require_stream_writable(); + require_inherits()(Duplex, Readable2); + { + keys = objectKeys(Writable.prototype); + for (v = 0; v < keys.length; v++) { + method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + var keys; + var method; + var v; + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable2.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once("end", onend); } - return fn2(args); - }; - if ("conversion" in fn2) { - wrappedFn.conversion = fn2.conversion; } - return wrappedFn; } - function wrapRounded(fn2) { - var wrappedFn = function(args) { - if (args === void 0 || args === null) { - return args; + Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } + }); + function onend() { + if (this._writableState.ended) return; + process.nextTick(onEndNT, this); + } + function onEndNT(self2) { + self2.end(); + } + Object.defineProperty(Duplex.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === void 0 || this._writableState === void 0) { + return false; } - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + if (this._readableState === void 0 || this._writableState === void 0) { + return; } - var result = fn2(args); - if (typeof result === "object") { - for (var len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + } +}); + +// node_modules/readable-stream/lib/_stream_writable.js +var require_stream_writable = __commonJS({ + "node_modules/readable-stream/lib/_stream_writable.js"(exports2, module2) { + "use strict"; + module2.exports = Writable; + function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state); + }; + } + var Duplex; + Writable.WritableState = WritableState; + var internalUtil = { + deprecate: require_node() + }; + var Stream = require_stream(); + var Buffer2 = __require("buffer").Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = require_destroy(); + var _require = require_state(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors2().codes; + var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; + var ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + var ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES; + var ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END; + var ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + var errorOrDestroy = destroyImpl.errorOrDestroy; + require_inherits()(Writable, Stream); + function nop() { + } + function WritableState(options, stream4, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream4 instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = function(er2) { + onwrite(stream4, er2); + }; + this.writecb = null; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + this.pendingcb = 0; + this.prefinished = false; + this.errorEmitted = false; + this.emitClose = options.emitClose !== false; + this.autoDestroy = !!options.autoDestroy; + this.bufferedRequestCount = 0; + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") + }); + } catch (_) { + } + })(); + var realHasInstance; + if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; } - return result; + }); + } else { + realHasInstance = function realHasInstance2(object) { + return object instanceof this; }; - if ("conversion" in fn2) { - wrappedFn.conversion = fn2.conversion; - } - return wrappedFn; } - models.forEach(function(fromModel) { - convert[fromModel] = {}; - Object.defineProperty(convert[fromModel], "channels", { value: conversions[fromModel].channels }); - Object.defineProperty(convert[fromModel], "labels", { value: conversions[fromModel].labels }); - var routes = route(fromModel); - var routeModels = Object.keys(routes); - routeModels.forEach(function(toModel) { - var fn2 = routes[toModel]; - convert[fromModel][toModel] = wrapRounded(fn2); - convert[fromModel][toModel].raw = wrapRaw(fn2); - }); - }); - module2.exports = convert; - } -}); - -// node_modules/color/index.js -var require_color = __commonJS({ - "node_modules/color/index.js"(exports2, module2) { - "use strict"; - var colorString = require_color_string(); - var convert = require_color_convert(); - var _slice = [].slice; - var skippedModels = [ - // to be honest, I don't really feel like keyword belongs in color convert, but eh. - "keyword", - // gray conflicts with some method names, and has its own method defined. - "gray", - // shouldn't really be in color-convert either... - "hex" - ]; - var hashedModelKeys = {}; - Object.keys(convert).forEach(function(model) { - hashedModelKeys[_slice.call(convert[model].labels).sort().join("")] = model; - }); - var limiters = {}; - function Color(obj, model) { - if (!(this instanceof Color)) { - return new Color(obj, model); + function Writable(options) { + Duplex = Duplex || require_stream_duplex(); + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + this.writable = true; + if (options) { + if (typeof options.write === "function") this._write = options.write; + if (typeof options.writev === "function") this._writev = options.writev; + if (typeof options.destroy === "function") this._destroy = options.destroy; + if (typeof options.final === "function") this._final = options.final; } - if (model && model in skippedModels) { - model = null; + Stream.call(this); + } + Writable.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function writeAfterEnd(stream4, cb) { + var er2 = new ERR_STREAM_WRITE_AFTER_END(); + errorOrDestroy(stream4, er2); + process.nextTick(cb, er2); + } + function validChunk(stream4, state, chunk, cb) { + var er2; + if (chunk === null) { + er2 = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== "string" && !state.objectMode) { + er2 = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); } - if (model && !(model in convert)) { - throw new Error("Unknown model: " + model); + if (er2) { + errorOrDestroy(stream4, er2); + process.nextTick(cb, er2); + return false; } - var i; - var channels; - if (obj == null) { - this.model = "rgb"; - this.color = [0, 0, 0]; - this.valpha = 1; - } else if (obj instanceof Color) { - this.model = obj.model; - this.color = obj.color.slice(); - this.valpha = obj.valpha; - } else if (typeof obj === "string") { - var result = colorString.get(obj); - if (result === null) { - throw new Error("Unable to parse color from string: " + obj); - } - this.model = result.model; - channels = convert[this.model].channels; - this.color = result.value.slice(0, channels); - this.valpha = typeof result.value[channels] === "number" ? result.value[channels] : 1; - } else if (obj.length) { - this.model = model || "rgb"; - channels = convert[this.model].channels; - var newArr = _slice.call(obj, 0, channels); - this.color = zeroArray(newArr, channels); - this.valpha = typeof obj[channels] === "number" ? obj[channels] : 1; - } else if (typeof obj === "number") { - obj &= 16777215; - this.model = "rgb"; - this.color = [ - obj >> 16 & 255, - obj >> 8 & 255, - obj & 255 - ]; - this.valpha = 1; - } else { - this.valpha = 1; - var keys = Object.keys(obj); - if ("alpha" in obj) { - keys.splice(keys.indexOf("alpha"), 1); - this.valpha = typeof obj.alpha === "number" ? obj.alpha : 0; - } - var hashedKeys = keys.sort().join(""); - if (!(hashedKeys in hashedModelKeys)) { - throw new Error("Unable to parse color from object: " + JSON.stringify(obj)); - } - this.model = hashedModelKeys[hashedKeys]; - var labels = convert[this.model].labels; - var color = []; - for (i = 0; i < labels.length; i++) { - color.push(obj[labels[i]]); - } - this.color = zeroArray(color); + return true; + } + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer2.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); } - if (limiters[this.model]) { - channels = convert[this.model].channels; - for (i = 0; i < channels; i++) { - var limit = limiters[this.model][i]; - if (limit) { - this.color[i] = limit(this.color[i]); - } - } + if (typeof encoding === "function") { + cb = encoding; + encoding = null; } - this.valpha = Math.max(0, Math.min(1, this.valpha)); - if (Object.freeze) { - Object.freeze(this); + if (isBuf) encoding = "buffer"; + else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== "function") cb = nop; + if (state.ending) writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } - } - Color.prototype = { - toString: function() { - return this.string(); - }, - toJSON: function() { - return this[this.model](); - }, - string: function(places) { - var self2 = this.model in colorString.to ? this : this.rgb(); - self2 = self2.round(typeof places === "number" ? places : 1); - var args = self2.valpha === 1 ? self2.color : self2.color.concat(this.valpha); - return colorString.to[self2.model](args); - }, - percentString: function(places) { - var self2 = this.rgb().round(typeof places === "number" ? places : 1); - var args = self2.valpha === 1 ? self2.color : self2.color.concat(this.valpha); - return colorString.to.rgb.percent(args); - }, - array: function() { - return this.valpha === 1 ? this.color.slice() : this.color.concat(this.valpha); - }, - object: function() { - var result = {}; - var channels = convert[this.model].channels; - var labels = convert[this.model].labels; - for (var i = 0; i < channels; i++) { - result[labels[i]] = this.color[i]; - } - if (this.valpha !== 1) { - result.alpha = this.valpha; - } - return result; - }, - unitArray: function() { - var rgb = this.rgb().color; - rgb[0] /= 255; - rgb[1] /= 255; - rgb[2] /= 255; - if (this.valpha !== 1) { - rgb.push(this.valpha); - } - return rgb; - }, - unitObject: function() { - var rgb = this.rgb().object(); - rgb.r /= 255; - rgb.g /= 255; - rgb.b /= 255; - if (this.valpha !== 1) { - rgb.alpha = this.valpha; - } - return rgb; - }, - round: function(places) { - places = Math.max(places || 0, 0); - return new Color(this.color.map(roundToPlace(places)).concat(this.valpha), this.model); - }, - alpha: function(val) { - if (arguments.length) { - return new Color(this.color.concat(Math.max(0, Math.min(1, val))), this.model); - } - return this.valpha; - }, - // rgb - red: getset("rgb", 0, maxfn(255)), - green: getset("rgb", 1, maxfn(255)), - blue: getset("rgb", 2, maxfn(255)), - hue: getset(["hsl", "hsv", "hsl", "hwb", "hcg"], 0, function(val) { - return (val % 360 + 360) % 360; - }), - // eslint-disable-line brace-style - saturationl: getset("hsl", 1, maxfn(100)), - lightness: getset("hsl", 2, maxfn(100)), - saturationv: getset("hsv", 1, maxfn(100)), - value: getset("hsv", 2, maxfn(100)), - chroma: getset("hcg", 1, maxfn(100)), - gray: getset("hcg", 2, maxfn(100)), - white: getset("hwb", 1, maxfn(100)), - wblack: getset("hwb", 2, maxfn(100)), - cyan: getset("cmyk", 0, maxfn(100)), - magenta: getset("cmyk", 1, maxfn(100)), - yellow: getset("cmyk", 2, maxfn(100)), - black: getset("cmyk", 3, maxfn(100)), - x: getset("xyz", 0, maxfn(100)), - y: getset("xyz", 1, maxfn(100)), - z: getset("xyz", 2, maxfn(100)), - l: getset("lab", 0, maxfn(100)), - a: getset("lab", 1), - b: getset("lab", 2), - keyword: function(val) { - if (arguments.length) { - return new Color(val); - } - return convert[this.model].keyword(this.color); - }, - hex: function(val) { - if (arguments.length) { - return new Color(val); - } - return colorString.to.hex(this.rgb().round().color); - }, - rgbNumber: function() { - var rgb = this.rgb().color; - return (rgb[0] & 255) << 16 | (rgb[1] & 255) << 8 | rgb[2] & 255; - }, - luminosity: function() { - var rgb = this.rgb().color; - var lum = []; - for (var i = 0; i < rgb.length; i++) { - var chan = rgb[i] / 255; - lum[i] = chan <= 0.03928 ? chan / 12.92 : Math.pow((chan + 0.055) / 1.055, 2.4); - } - return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; - }, - contrast: function(color2) { - var lum1 = this.luminosity(); - var lum2 = color2.luminosity(); - if (lum1 > lum2) { - return (lum1 + 0.05) / (lum2 + 0.05); - } - return (lum2 + 0.05) / (lum1 + 0.05); - }, - level: function(color2) { - var contrastRatio = this.contrast(color2); - if (contrastRatio >= 7.1) { - return "AAA"; - } - return contrastRatio >= 4.5 ? "AA" : ""; - }, - isDark: function() { - var rgb = this.rgb().color; - var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1e3; - return yiq < 128; - }, - isLight: function() { - return !this.isDark(); - }, - negate: function() { - var rgb = this.rgb(); - for (var i = 0; i < 3; i++) { - rgb.color[i] = 255 - rgb.color[i]; - } - return rgb; - }, - lighten: function(ratio) { - var hsl = this.hsl(); - hsl.color[2] += hsl.color[2] * ratio; - return hsl; - }, - darken: function(ratio) { - var hsl = this.hsl(); - hsl.color[2] -= hsl.color[2] * ratio; - return hsl; - }, - saturate: function(ratio) { - var hsl = this.hsl(); - hsl.color[1] += hsl.color[1] * ratio; - return hsl; - }, - desaturate: function(ratio) { - var hsl = this.hsl(); - hsl.color[1] -= hsl.color[1] * ratio; - return hsl; - }, - whiten: function(ratio) { - var hwb = this.hwb(); - hwb.color[1] += hwb.color[1] * ratio; - return hwb; - }, - blacken: function(ratio) { - var hwb = this.hwb(); - hwb.color[2] += hwb.color[2] * ratio; - return hwb; - }, - grayscale: function() { - var rgb = this.rgb().color; - var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; - return Color.rgb(val, val, val); - }, - fade: function(ratio) { - return this.alpha(this.valpha - this.valpha * ratio); - }, - opaquer: function(ratio) { - return this.alpha(this.valpha + this.valpha * ratio); - }, - rotate: function(degrees) { - var hsl = this.hsl(); - var hue = hsl.color[0]; - hue = (hue + degrees) % 360; - hue = hue < 0 ? 360 + hue : hue; - hsl.color[0] = hue; - return hsl; - }, - mix: function(mixinColor, weight) { - if (!mixinColor || !mixinColor.rgb) { - throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor); - } - var color1 = mixinColor.rgb(); - var color2 = this.rgb(); - var p = weight === void 0 ? 0.5 : weight; - var w2 = 2 * p - 1; - var a = color1.alpha() - color2.alpha(); - var w1 = ((w2 * a === -1 ? w2 : (w2 + a) / (1 + w2 * a)) + 1) / 2; - var w22 = 1 - w1; - return Color.rgb( - w1 * color1.red() + w22 * color2.red(), - w1 * color1.green() + w22 * color2.green(), - w1 * color1.blue() + w22 * color2.blue(), - color1.alpha() * p + color2.alpha() * (1 - p) - ); + return ret; + }; + Writable.prototype.cork = function() { + this._writableState.corked++; + }; + Writable.prototype.uncork = function() { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; - Object.keys(convert).forEach(function(model) { - if (skippedModels.indexOf(model) !== -1) { - return; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + if (typeof encoding === "string") encoding = encoding.toLowerCase(); + if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + Object.defineProperty(Writable.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); } - var channels = convert[model].channels; - Color.prototype[model] = function() { - if (this.model === model) { - return new Color(this); - } - if (arguments.length) { - return new Color(arguments, model); - } - var newAlpha = typeof arguments[channels] === "number" ? channels : this.valpha; - return new Color(assertArray(convert[this.model][model].raw(this.color)).concat(newAlpha), model); - }; - Color[model] = function(color) { - if (typeof color === "number") { - color = zeroArray(_slice.call(arguments), channels); - } - return new Color(color, model); - }; }); - function roundTo(num2, places) { - return Number(num2.toFixed(places)); - } - function roundToPlace(places) { - return function(num2) { - return roundTo(num2, places); - }; + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") { + chunk = Buffer2.from(chunk, encoding); + } + return chunk; } - function getset(model, channel, modifier) { - model = Array.isArray(model) ? model : [model]; - model.forEach(function(m2) { - (limiters[m2] || (limiters[m2] = []))[channel] = modifier; - }); - model = model[0]; - return function(val) { - var result; - if (arguments.length) { - if (modifier) { - val = modifier(val); - } - result = this[model](); - result.color[channel] = val; - return result; + Object.defineProperty(Writable.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } + }); + function writeOrBuffer(stream4, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = "buffer"; + chunk = newChunk; } - result = this[model]().color[channel]; - if (modifier) { - result = modifier(result); + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk, + encoding, + isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; } - return result; - }; + state.bufferedRequestCount += 1; + } else { + doWrite(stream4, state, false, len, chunk, encoding, cb); + } + return ret; } - function maxfn(max) { - return function(v) { - return Math.max(0, Math.min(max, v)); - }; + function doWrite(stream4, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED("write")); + else if (writev) stream4._writev(chunk, state.onwrite); + else stream4._write(chunk, encoding, state.onwrite); + state.sync = false; + } + function onwriteError(stream4, state, sync, er2, cb) { + --state.pendingcb; + if (sync) { + process.nextTick(cb, er2); + process.nextTick(finishMaybe, stream4, state); + stream4._writableState.errorEmitted = true; + errorOrDestroy(stream4, er2); + } else { + cb(er2); + stream4._writableState.errorEmitted = true; + errorOrDestroy(stream4, er2); + finishMaybe(stream4, state); + } } - function assertArray(val) { - return Array.isArray(val) ? val : [val]; + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } - function zeroArray(arr, length) { - for (var i = 0; i < length; i++) { - if (typeof arr[i] !== "number") { - arr[i] = 0; + function onwrite(stream4, er2) { + var state = stream4._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er2) onwriteError(stream4, state, sync, er2, cb); + else { + var finished = needFinish(state) || stream4.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream4, state); + } + if (sync) { + process.nextTick(afterWrite, stream4, state, finished, cb); + } else { + afterWrite(stream4, state, finished, cb); } } - return arr; } - module2.exports = Color; - } -}); - -// node_modules/text-hex/index.js -var require_text_hex = __commonJS({ - "node_modules/text-hex/index.js"(exports2, module2) { - "use strict"; - module2.exports = function hex(str) { - for (var i = 0, hash2 = 0; i < str.length; hash2 = str.charCodeAt(i++) + ((hash2 << 5) - hash2)) ; - var color = Math.floor( - Math.abs( - Math.sin(hash2) * 1e4 % 1 * 16777216 - ) - ).toString(16); - return "#" + Array(6 - color.length + 1).join("0") + color; - }; - } -}); - -// node_modules/colorspace/index.js -var require_colorspace = __commonJS({ - "node_modules/colorspace/index.js"(exports2, module2) { - "use strict"; - var color = require_color(); - var hex = require_text_hex(); - module2.exports = function colorspace(namespace, delimiter) { - var split3 = namespace.split(delimiter || ":"); - var base = hex(split3[0]); - if (!split3.length) return base; - for (var i = 0, l = split3.length - 1; i < l; i++) { - base = color(base).mix(color(hex(split3[i + 1]))).saturate(1).hex(); - } - return base; - }; - } -}); - -// node_modules/kuler/index.js -var require_kuler = __commonJS({ - "node_modules/kuler/index.js"(exports2, module2) { - "use strict"; - function Kuler(text, color) { - if (color) return new Kuler(text).style(color); - if (!(this instanceof Kuler)) return new Kuler(text); - this.text = text; + function afterWrite(stream4, state, finished, cb) { + if (!finished) onwriteDrain(stream4, state); + state.pendingcb--; + cb(); + finishMaybe(stream4, state); } - Kuler.prototype.prefix = "\x1B["; - Kuler.prototype.suffix = "m"; - Kuler.prototype.hex = function hex(color) { - color = color[0] === "#" ? color.substring(1) : color; - if (color.length === 3) { - color = color.split(""); - color[5] = color[2]; - color[4] = color[2]; - color[3] = color[1]; - color[2] = color[1]; - color[1] = color[0]; - color = color.join(""); + function onwriteDrain(stream4, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream4.emit("drain"); } - var r = color.substring(0, 2), g = color.substring(2, 4), b2 = color.substring(4, 6); - return [parseInt(r, 16), parseInt(g, 16), parseInt(b2, 16)]; - }; - Kuler.prototype.rgb = function rgb(r, g, b2) { - var red = r / 255 * 5, green = g / 255 * 5, blue = b2 / 255 * 5; - return this.ansi(red, green, blue); - }; - Kuler.prototype.ansi = function ansi(r, g, b2) { - var red = Math.round(r), green = Math.round(g), blue = Math.round(b2); - return 16 + red * 36 + green * 6 + blue; - }; - Kuler.prototype.reset = function reset() { - return this.prefix + "39;49" + this.suffix; - }; - Kuler.prototype.style = function style(color) { - return this.prefix + "38;5;" + this.rgb.apply(this, this.hex(color)) + this.suffix + this.text + this.reset(); - }; - module2.exports = Kuler; - } -}); - -// node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js -var require_namespace_ansi = __commonJS({ - "node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js"(exports2, module2) { - var colorspace = require_colorspace(); - var kuler = require_kuler(); - module2.exports = function ansiModifier(args, options) { - var namespace = options.namespace; - var ansi = options.colors !== false ? kuler(namespace + ":", colorspace(namespace)) : namespace + ":"; - args[0] = ansi + " " + args[0]; - return args; - }; - } -}); - -// node_modules/enabled/index.js -var require_enabled = __commonJS({ - "node_modules/enabled/index.js"(exports2, module2) { - "use strict"; - module2.exports = function enabled(name, variable) { - if (!variable) return false; - var variables = variable.split(/[\s,]+/), i = 0; - for (; i < variables.length; i++) { - variable = variables[i].replace("*", ".*?"); - if ("-" === variable.charAt(0)) { - if (new RegExp("^" + variable.substr(1) + "$").test(name)) { - return false; - } - continue; + } + function clearBuffer(stream4, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream4._writev && entry && entry.next) { + var l = state.bufferedRequestCount; + var buffer2 = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer2[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; } - if (new RegExp("^" + variable + "$").test(name)) { - return true; + buffer2.allBuffers = allBuffers; + doWrite(stream4, state, true, state.length, buffer2, "", holder.finish); + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); } - } - return false; - }; - } -}); - -// node_modules/@dabh/diagnostics/adapters/index.js -var require_adapters = __commonJS({ - "node_modules/@dabh/diagnostics/adapters/index.js"(exports2, module2) { - var enabled = require_enabled(); - module2.exports = function create(fn2) { - return function adapter(namespace) { - try { - return enabled(namespace, fn2()); - } catch (e) { + state.bufferedRequestCount = 0; + } else { + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream4, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + if (state.writing) { + break; + } } - return false; - }; + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); }; - } -}); - -// node_modules/@dabh/diagnostics/adapters/process.env.js -var require_process_env = __commonJS({ - "node_modules/@dabh/diagnostics/adapters/process.env.js"(exports2, module2) { - var adapter = require_adapters(); - module2.exports = adapter(function processenv() { - return process.env.DEBUG || process.env.DIAGNOSTICS; - }); - } -}); - -// node_modules/@dabh/diagnostics/logger/console.js -var require_console2 = __commonJS({ - "node_modules/@dabh/diagnostics/logger/console.js"(exports2, module2) { - module2.exports = function(meta, messages) { - try { - Function.prototype.apply.call(console.log, console, messages); - } catch (e) { + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== void 0) this.write(chunk, encoding); + if (state.corked) { + state.corked = 1; + this.uncork(); } + if (!state.ending) endWritable(this, state, cb); + return this; }; - } -}); - -// node_modules/@dabh/diagnostics/node/development.js -var require_development = __commonJS({ - "node_modules/@dabh/diagnostics/node/development.js"(exports2, module2) { - var create = require_diagnostics(); - var tty = __require("tty").isatty(1); - var diagnostics = create(function dev(namespace, options) { - options = options || {}; - options.colors = "colors" in options ? options.colors : tty; - options.namespace = namespace; - options.prod = false; - options.dev = true; - if (!dev.enabled(namespace) && !(options.force || dev.force)) { - return dev.nope(options); + Object.defineProperty(Writable.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; } - return dev.yep(options); }); - diagnostics.modify(require_namespace_ansi()); - diagnostics.use(require_process_env()); - diagnostics.set(require_console2()); - module2.exports = diagnostics; - } -}); - -// node_modules/@dabh/diagnostics/node/index.js -var require_node3 = __commonJS({ - "node_modules/@dabh/diagnostics/node/index.js"(exports2, module2) { - if (process.env.NODE_ENV === "production") { - module2.exports = require_production(); - } else { - module2.exports = require_development(); - } - } -}); - -// node_modules/winston/lib/winston/tail-file.js -var require_tail_file = __commonJS({ - "node_modules/winston/lib/winston/tail-file.js"(exports2, module2) { - "use strict"; - var fs2 = __require("fs"); - var { StringDecoder } = __require("string_decoder"); - var { Stream } = require_readable(); - function noop2() { + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } - module2.exports = (options, iter) => { - const buffer2 = Buffer.alloc(64 * 1024); - const decode2 = new StringDecoder("utf8"); - const stream4 = new Stream(); - let buff = ""; - let pos = 0; - let row = 0; - if (options.start === -1) { - delete options.start; - } - stream4.readable = true; - stream4.destroy = () => { - stream4.destroyed = true; - stream4.emit("end"); - stream4.emit("close"); - }; - fs2.open(options.file, "a+", "0644", (err, fd2) => { + function callFinal(stream4, state) { + stream4._final(function(err) { + state.pendingcb--; if (err) { - if (!iter) { - stream4.emit("error", err); - } else { - iter(err); - } - stream4.destroy(); - return; + errorOrDestroy(stream4, err); } - (function read() { - if (stream4.destroyed) { - fs2.close(fd2, noop2); - return; - } - return fs2.read(fd2, buffer2, 0, buffer2.length, pos, (error, bytes) => { - if (error) { - if (!iter) { - stream4.emit("error", error); - } else { - iter(error); - } - stream4.destroy(); - return; - } - if (!bytes) { - if (buff) { - if (options.start == null || row > options.start) { - if (!iter) { - stream4.emit("line", buff); - } else { - iter(null, buff); - } - } - row++; - buff = ""; - } - return setTimeout(read, 1e3); - } - let data = decode2.write(buffer2.slice(0, bytes)); - if (!iter) { - stream4.emit("data", data); - } - data = (buff + data).split(/\n+/); - const l = data.length - 1; - let i = 0; - for (; i < l; i++) { - if (options.start == null || row > options.start) { - if (!iter) { - stream4.emit("line", data[i]); - } else { - iter(null, data[i]); - } - } - row++; - } - buff = data[l]; - pos += bytes; - return read(); - }); - })(); + state.prefinished = true; + stream4.emit("prefinish"); + finishMaybe(stream4, state); }); - if (!iter) { - return stream4; - } - return stream4.destroy; - }; - } -}); - -// node_modules/winston/lib/winston/transports/file.js -var require_file = __commonJS({ - "node_modules/winston/lib/winston/transports/file.js"(exports2, module2) { - "use strict"; - var fs2 = __require("fs"); - var path = __require("path"); - var asyncSeries = require_series(); - var zlib2 = __require("zlib"); - var { MESSAGE } = require_triple_beam(); - var { Stream, PassThrough } = require_readable(); - var TransportStream = require_winston_transport(); - var debug = require_node3()("winston:file"); - var os2 = __require("os"); - var tailFile = require_tail_file(); - module2.exports = class File extends TransportStream { - /** - * Constructor function for the File transport object responsible for - * persisting log messages and metadata to one or more files. - * @param {Object} options - Options for this instance. - */ - constructor(options = {}) { - super(options); - this.name = options.name || "file"; - function throwIf(target, ...args) { - args.slice(1).forEach((name) => { - if (options[name]) { - throw new Error(`Cannot set ${name} and ${target} together`); - } - }); - } - this._stream = new PassThrough(); - this._stream.setMaxListeners(30); - this._onError = this._onError.bind(this); - if (options.filename || options.dirname) { - throwIf("filename or dirname", "stream"); - this._basename = this.filename = options.filename ? path.basename(options.filename) : "winston.log"; - this.dirname = options.dirname || path.dirname(options.filename); - this.options = options.options || { flags: "a" }; - } else if (options.stream) { - console.warn("options.stream will be removed in winston@4. Use winston.transports.Stream"); - throwIf("stream", "filename", "maxsize"); - this._dest = this._stream.pipe(this._setupStream(options.stream)); - this.dirname = path.dirname(this._dest.path); + } + function prefinish(stream4, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream4._final === "function" && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream4, state); } else { - throw new Error("Cannot log to file without filename or stream."); + state.prefinished = true; + stream4.emit("prefinish"); } - this.maxsize = options.maxsize || null; - this.rotationFormat = options.rotationFormat || false; - this.zippedArchive = options.zippedArchive || false; - this.maxFiles = options.maxFiles || null; - this.eol = typeof options.eol === "string" ? options.eol : os2.EOL; - this.tailable = options.tailable || false; - this.lazy = options.lazy || false; - this._size = 0; - this._pendingSize = 0; - this._created = 0; - this._drain = false; - this._opening = false; - this._ending = false; - this._fileExist = false; - if (this.dirname) this._createLogDirIfNotExist(this.dirname); - if (!this.lazy) this.open(); } - finishIfEnding() { - if (this._ending) { - if (this._opening) { - this.once("open", () => { - this._stream.once("finish", () => this.emit("finish")); - setImmediate(() => this._stream.end()); - }); - } else { - this._stream.once("finish", () => this.emit("finish")); - setImmediate(() => this._stream.end()); + } + function finishMaybe(stream4, state) { + var need = needFinish(state); + if (need) { + prefinish(stream4, state); + if (state.pendingcb === 0) { + state.finished = true; + stream4.emit("finish"); + if (state.autoDestroy) { + var rState = stream4._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream4.destroy(); + } } } } - /** - * Core logging method exposed to Winston. Metadata is optional. - * @param {Object} info - TODO: add param description. - * @param {Function} callback - TODO: add param description. - * @returns {undefined} - */ - log(info, callback = () => { - }) { - if (this.silent) { - callback(); - return true; - } - if (this._drain) { - this._stream.once("drain", () => { - this._drain = false; - this.log(info, callback); - }); - return; + return need; + } + function endWritable(stream4, state, cb) { + state.ending = true; + finishMaybe(stream4, state); + if (cb) { + if (state.finished) process.nextTick(cb); + else stream4.once("finish", cb); + } + state.ended = true; + stream4.writable = false; + } + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + state.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === void 0) { + return false; } - if (this._rotate) { - this._stream.once("rotate", () => { - this._rotate = false; - this.log(info, callback); - }); + return this._writableState.destroyed; + }, + set: function set(value) { + if (!this._writableState) { return; } - if (this.lazy) { - if (!this._fileExist) { - if (!this._opening) { - this.open(); - } - this.once("open", () => { - this._fileExist = true; - this.log(info, callback); - return; - }); - return; - } - if (this._needsNewFile(this._pendingSize)) { - this._dest.once("close", () => { - if (!this._opening) { - this.open(); - } - this.once("open", () => { - this.log(info, callback); - return; - }); - return; - }); - return; + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + cb(err); + }; + } +}); + +// node_modules/winston-transport/modern.js +var require_modern = __commonJS({ + "node_modules/winston-transport/modern.js"(exports2, module2) { + "use strict"; + var util3 = __require("util"); + var Writable = require_stream_writable(); + var { LEVEL } = require_triple_beam(); + var TransportStream = module2.exports = function TransportStream2(options = {}) { + Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark }); + this.format = options.format; + this.level = options.level; + this.handleExceptions = options.handleExceptions; + this.handleRejections = options.handleRejections; + this.silent = options.silent; + if (options.log) this.log = options.log; + if (options.logv) this.logv = options.logv; + if (options.close) this.close = options.close; + this.once("pipe", (logger) => { + this.levels = logger.levels; + this.parent = logger; + }); + this.once("unpipe", (src) => { + if (src === this.parent) { + this.parent = null; + if (this.close) { + this.close(); } } - const output = `${info[MESSAGE]}${this.eol}`; - const bytes = Buffer.byteLength(output); - function logged() { - this._size += bytes; - this._pendingSize -= bytes; - debug("logged %s %s", this._size, output); - this.emit("logged", info); - if (this._rotate) { - return; - } - if (this._opening) { - return; - } - if (!this._needsNewFile()) { - return; - } - if (this.lazy) { - this._endStream(() => { - this.emit("fileclosed"); - }); - return; - } - this._rotate = true; - this._endStream(() => this._rotateFile()); + }); + }; + util3.inherits(TransportStream, Writable); + TransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || info.exception === true && !this.handleExceptions) { + return callback(null); + } + const level = this.level || this.parent && this.parent.level; + if (!level || this.levels[level] >= this.levels[info[LEVEL]]) { + if (info && !this.format) { + return this.log(info, callback); } - this._pendingSize += bytes; - if (this._opening && !this.rotatedWhileOpening && this._needsNewFile(this._size + this._pendingSize)) { - this.rotatedWhileOpening = true; + let errState; + let transformed; + try { + transformed = this.format.transform(Object.assign({}, info), this.format.options); + } catch (err) { + errState = err; } - const written = this._stream.write(output, logged.bind(this)); - if (!written) { - this._drain = true; - this._stream.once("drain", () => { - this._drain = false; - callback(); - }); - } else { + if (errState || !transformed) { callback(); + if (errState) throw errState; + return; } - debug("written", written, this._drain); - this.finishIfEnding(); - return written; + return this.log(transformed, callback); } - /** - * Query the transport. Options object is optional. - * @param {Object} options - Loggly-like query options for this instance. - * @param {function} callback - Continuation to respond to when complete. - * TODO: Refactor me. - */ - query(options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; + this._writableState.sync = false; + return callback(null); + }; + TransportStream.prototype._writev = function _writev(chunks, callback) { + if (this.logv) { + const infos = chunks.filter(this._accept, this); + if (!infos.length) { + return callback(null); } - options = normalizeQuery(options); - const file = path.join(this.dirname, this.filename); - let buff = ""; - let results = []; - let row = 0; - const stream4 = fs2.createReadStream(file, { - encoding: "utf8" - }); - stream4.on("error", (err) => { - if (stream4.readable) { - stream4.destroy(); - } - if (!callback) { - return; - } - return err.code !== "ENOENT" ? callback(err) : callback(null, results); - }); - stream4.on("data", (data) => { - data = (buff + data).split(/\n+/); - const l = data.length - 1; - let i = 0; - for (; i < l; i++) { - if (!options.start || row >= options.start) { - add(data[i]); - } - row++; - } - buff = data[l]; - }); - stream4.on("close", () => { - if (buff) { - add(buff, true); - } - if (options.order === "desc") { - results = results.reverse(); - } - if (callback) callback(null, results); - }); - function add(buff2, attempt) { - try { - const log = JSON.parse(buff2); - if (check(log)) { - push(log); - } - } catch (e) { - if (!attempt) { - stream4.emit("error", e); - } - } + return this.logv(infos, callback); + } + for (let i = 0; i < chunks.length; i++) { + if (!this._accept(chunks[i])) continue; + if (chunks[i].chunk && !this.format) { + this.log(chunks[i].chunk, chunks[i].callback); + continue; } - function push(log) { - if (options.rows && results.length >= options.rows && options.order !== "desc") { - if (stream4.readable) { - stream4.destroy(); - } - return; - } - if (options.fields) { - log = options.fields.reduce((obj, key) => { - obj[key] = log[key]; - return obj; - }, {}); - } - if (options.order === "desc") { - if (results.length >= options.rows) { - results.shift(); - } - } - results.push(log); + let errState; + let transformed; + try { + transformed = this.format.transform( + Object.assign({}, chunks[i].chunk), + this.format.options + ); + } catch (err) { + errState = err; } - function check(log) { - if (!log) { - return; - } - if (typeof log !== "object") { - return; - } - const time = new Date(log.timestamp); - if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) { - return; + if (errState || !transformed) { + chunks[i].callback(); + if (errState) { + callback(null); + throw errState; } - return true; + } else { + this.log(transformed, chunks[i].callback); } - function normalizeQuery(options2) { - options2 = options2 || {}; - options2.rows = options2.rows || options2.limit || 10; - options2.start = options2.start || 0; - options2.until = options2.until || /* @__PURE__ */ new Date(); - if (typeof options2.until !== "object") { - options2.until = new Date(options2.until); - } - options2.from = options2.from || options2.until - 24 * 60 * 60 * 1e3; - if (typeof options2.from !== "object") { - options2.from = new Date(options2.from); - } - options2.order = options2.order || "desc"; - return options2; + } + return callback(null); + }; + TransportStream.prototype._accept = function _accept(write) { + const info = write.chunk; + if (this.silent) { + return false; + } + const level = this.level || this.parent && this.parent.level; + if (info.exception === true || !level || this.levels[level] >= this.levels[info[LEVEL]]) { + if (this.handleExceptions || info.exception !== true) { + return true; } } - /** - * Returns a log stream for this transport. Options object is optional. - * @param {Object} options - Stream options for this instance. - * @returns {Stream} - TODO: add return description. - * TODO: Refactor me. - */ - stream(options = {}) { - const file = path.join(this.dirname, this.filename); - const stream4 = new Stream(); - const tail = { - file, - start: options.start - }; - stream4.destroy = tailFile(tail, (err, line) => { - if (err) { - return stream4.emit("error", err); - } - try { - stream4.emit("data", line); - line = JSON.parse(line); - stream4.emit("log", line); - } catch (e) { - stream4.emit("error", e); - } - }); - return stream4; + return false; + }; + TransportStream.prototype._nop = function _nop() { + return void 0; + }; + } +}); + +// node_modules/winston-transport/legacy.js +var require_legacy = __commonJS({ + "node_modules/winston-transport/legacy.js"(exports2, module2) { + "use strict"; + var util3 = __require("util"); + var { LEVEL } = require_triple_beam(); + var TransportStream = require_modern(); + var LegacyTransportStream = module2.exports = function LegacyTransportStream2(options = {}) { + TransportStream.call(this, options); + if (!options.transport || typeof options.transport.log !== "function") { + throw new Error("Invalid transport, must be an object with a log method."); } - /** - * Checks to see the filesize of. - * @returns {undefined} - */ - open() { - if (!this.filename) return; - if (this._opening) return; - this._opening = true; - this.stat((err, size5) => { - if (err) { - return this.emit("error", err); - } - debug("stat done: %s { size: %s }", this.filename, size5); - this._size = size5; - this._dest = this._createStream(this._stream); - this._opening = false; - this.once("open", () => { - if (!this._stream.emit("rotate")) { - this._rotate = false; - } - }); - }); + this.transport = options.transport; + this.level = this.level || options.transport.level; + this.handleExceptions = this.handleExceptions || options.transport.handleExceptions; + this._deprecated(); + function transportError(err) { + this.emit("error", err, this.transport); } - /** - * Stat the file and assess information in order to create the proper stream. - * @param {function} callback - TODO: add param description. - * @returns {undefined} - */ - stat(callback) { - const target = this._getFile(); - const fullpath = path.join(this.dirname, target); - fs2.stat(fullpath, (err, stat) => { - if (err && err.code === "ENOENT") { - debug("ENOENT\xA0ok", fullpath); - this.filename = target; - return callback(null, 0); - } - if (err) { - debug(`err ${err.code} ${fullpath}`); - return callback(err); - } - if (!stat || this._needsNewFile(stat.size)) { - return this._incFile(() => this.stat(callback)); - } - this.filename = target; - callback(null, stat.size); - }); + if (!this.transport.__winstonError) { + this.transport.__winstonError = transportError.bind(this); + this.transport.on("error", this.transport.__winstonError); } - /** - * Closes the stream associated with this instance. - * @param {function} cb - TODO: add param description. - * @returns {undefined} - */ - close(cb) { - if (!this._stream) { - return; - } - this._stream.end(() => { - if (cb) { - cb(); - } - this.emit("flush"); - this.emit("closed"); - }); + }; + util3.inherits(LegacyTransportStream, TransportStream); + LegacyTransportStream.prototype._write = function _write(info, enc, callback) { + if (this.silent || info.exception === true && !this.handleExceptions) { + return callback(null); } - /** - * TODO: add method description. - * @param {number} size - TODO: add param description. - * @returns {undefined} - */ - _needsNewFile(size5) { - size5 = size5 || this._size; - return this.maxsize && size5 >= this.maxsize; + if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) { + this.transport.log(info[LEVEL], info.message, info, this._nop); } - /** - * TODO: add method description. - * @param {Error} err - TODO: add param description. - * @returns {undefined} - */ - _onError(err) { - this.emit("error", err); + callback(null); + }; + LegacyTransportStream.prototype._writev = function _writev(chunks, callback) { + for (let i = 0; i < chunks.length; i++) { + if (this._accept(chunks[i])) { + this.transport.log( + chunks[i].chunk[LEVEL], + chunks[i].chunk.message, + chunks[i].chunk, + this._nop + ); + chunks[i].callback(); + } } - /** - * TODO: add method description. - * @param {Stream} stream - TODO: add param description. - * @returns {mixed} - TODO: add return description. - */ - _setupStream(stream4) { - stream4.on("error", this._onError); - return stream4; + return callback(null); + }; + LegacyTransportStream.prototype._deprecated = function _deprecated() { + console.error([ + `${this.transport.name} is a legacy winston transport. Consider upgrading: `, + "- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md" + ].join("\n")); + }; + LegacyTransportStream.prototype.close = function close() { + if (this.transport.close) { + this.transport.close(); } - /** - * TODO: add method description. - * @param {Stream} stream - TODO: add param description. - * @returns {mixed} - TODO: add return description. - */ - _cleanupStream(stream4) { - stream4.removeListener("error", this._onError); - stream4.destroy(); - return stream4; + if (this.transport.__winstonError) { + this.transport.removeListener("error", this.transport.__winstonError); + this.transport.__winstonError = null; } + }; + } +}); + +// node_modules/winston-transport/index.js +var require_winston_transport = __commonJS({ + "node_modules/winston-transport/index.js"(exports2, module2) { + "use strict"; + module2.exports = require_modern(); + module2.exports.LegacyTransportStream = require_legacy(); + } +}); + +// node_modules/winston/lib/winston/transports/console.js +var require_console = __commonJS({ + "node_modules/winston/lib/winston/transports/console.js"(exports2, module2) { + "use strict"; + var os2 = __require("os"); + var { LEVEL, MESSAGE } = require_triple_beam(); + var TransportStream = require_winston_transport(); + module2.exports = class Console extends TransportStream { /** - * TODO: add method description. + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. */ - _rotateFile() { - this._incFile(() => this.open()); + constructor(options = {}) { + super(options); + this.name = options.name || "console"; + this.stderrLevels = this._stringArrayToSet(options.stderrLevels); + this.consoleWarnLevels = this._stringArrayToSet(options.consoleWarnLevels); + this.eol = typeof options.eol === "string" ? options.eol : os2.EOL; + this.forceConsole = options.forceConsole || false; + this._consoleLog = console.log.bind(console); + this._consoleWarn = console.warn.bind(console); + this._consoleError = console.error.bind(console); + this.setMaxListeners(30); } /** - * Unpipe from the stream that has been marked as full and end it so it - * flushes to disk. - * - * @param {function} callback - Callback for when the current file has closed. - * @private + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} */ - _endStream(callback = () => { - }) { - if (this._dest) { - this._stream.unpipe(this._dest); - this._dest.end(() => { - this._cleanupStream(this._dest); + log(info, callback) { + setImmediate(() => this.emit("logged", info)); + if (this.stderrLevels[info[LEVEL]]) { + if (console._stderr && !this.forceConsole) { + console._stderr.write(`${info[MESSAGE]}${this.eol}`); + } else { + this._consoleError(info[MESSAGE]); + } + if (callback) { callback(); - }); + } + return; + } else if (this.consoleWarnLevels[info[LEVEL]]) { + if (console._stderr && !this.forceConsole) { + console._stderr.write(`${info[MESSAGE]}${this.eol}`); + } else { + this._consoleWarn(info[MESSAGE]); + } + if (callback) { + callback(); + } + return; + } + if (console._stdout && !this.forceConsole) { + console._stdout.write(`${info[MESSAGE]}${this.eol}`); } else { + this._consoleLog(info[MESSAGE]); + } + if (callback) { callback(); } } /** - * Returns the WritableStream for the active file on this instance. If we - * should gzip the file then a zlib stream is returned. - * - * @param {ReadableStream} source –PassThrough to pipe to the file when open. - * @returns {WritableStream} Stream that writes to disk for the active file. + * Returns a Set-like object with strArray's elements as keys (each with the + * value true). + * @param {Array} strArray - Array of Set-elements as strings. + * @param {?string} [errMsg] - Custom error message thrown on invalid input. + * @returns {Object} - TODO: add return description. + * @private */ - _createStream(source) { - const fullpath = path.join(this.dirname, this.filename); - debug("create stream start", fullpath, this.options); - const dest = fs2.createWriteStream(fullpath, this.options).on("error", (err) => debug(err)).on("close", () => debug("close", dest.path, dest.bytesWritten)).on("open", () => { - debug("file open ok", fullpath); - this.emit("open", fullpath); - source.pipe(dest); - if (this.rotatedWhileOpening) { - this._stream = new PassThrough(); - this._stream.setMaxListeners(30); - this._rotateFile(); - this.rotatedWhileOpening = false; - this._cleanupStream(dest); - source.end(); + _stringArrayToSet(strArray, errMsg) { + if (!strArray) return {}; + errMsg = errMsg || "Cannot make set from type other than Array of string elements"; + if (!Array.isArray(strArray)) { + throw new Error(errMsg); + } + return strArray.reduce((set, el2) => { + if (typeof el2 !== "string") { + throw new Error(errMsg); } - }); - debug("create stream ok", fullpath); - return dest; + set[el2] = true; + return set; + }, {}); } - /** - * TODO: add method description. - * @param {function} callback - TODO: add param description. - * @returns {undefined} - */ - _incFile(callback) { - debug("_incFile", this.filename); - const ext = path.extname(this._basename); - const basename = path.basename(this._basename, ext); - const tasks = []; - if (this.zippedArchive) { - tasks.push( - function(cb) { - const num2 = this._created > 0 && !this.tailable ? this._created : ""; - this._compressFile( - path.join(this.dirname, `${basename}${num2}${ext}`), - path.join(this.dirname, `${basename}${num2}${ext}.gz`), - cb - ); - }.bind(this) - ); + }; + } +}); + +// node_modules/async/internal/isArrayLike.js +var require_isArrayLike = __commonJS({ + "node_modules/async/internal/isArrayLike.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = isArrayLike; + function isArrayLike(value) { + return value && typeof value.length === "number" && value.length >= 0 && value.length % 1 === 0; + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/initialParams.js +var require_initialParams = __commonJS({ + "node_modules/async/internal/initialParams.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = function(fn2) { + return function(...args) { + var callback = args.pop(); + return fn2.call(this, args, callback); + }; + }; + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/setImmediate.js +var require_setImmediate = __commonJS({ + "node_modules/async/internal/setImmediate.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.fallback = fallback2; + exports2.wrap = wrap; + var hasQueueMicrotask = exports2.hasQueueMicrotask = typeof queueMicrotask === "function" && queueMicrotask; + var hasSetImmediate = exports2.hasSetImmediate = typeof setImmediate === "function" && setImmediate; + var hasNextTick = exports2.hasNextTick = typeof process === "object" && typeof process.nextTick === "function"; + function fallback2(fn2) { + setTimeout(fn2, 0); + } + function wrap(defer) { + return (fn2, ...args) => defer(() => fn2(...args)); + } + var _defer; + if (hasQueueMicrotask) { + _defer = queueMicrotask; + } else if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } else { + _defer = fallback2; + } + exports2.default = wrap(_defer); + } +}); + +// node_modules/async/asyncify.js +var require_asyncify = __commonJS({ + "node_modules/async/asyncify.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = asyncify; + var _initialParams = require_initialParams(); + var _initialParams2 = _interopRequireDefault(_initialParams); + var _setImmediate2 = require_setImmediate(); + var _setImmediate22 = _interopRequireDefault(_setImmediate2); + var _wrapAsync = require_wrapAsync(); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function asyncify(func) { + if ((0, _wrapAsync.isAsync)(func)) { + return function(...args) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback); + }; + } + return (0, _initialParams2.default)(function(args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); } - tasks.push( - function(cb) { - if (!this.tailable) { - this._created += 1; - this._checkMaxFilesIncrementing(ext, basename, cb); - } else { - this._checkMaxFilesTailable(ext, basename, cb); - } - }.bind(this) - ); - asyncSeries(tasks, callback); + if (result && typeof result.then === "function") { + return handlePromise(result, callback); + } else { + callback(null, result); + } + }); + } + function handlePromise(promise, callback) { + return promise.then((value) => { + invokeCallback(callback, null, value); + }, (err) => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); + } + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + (0, _setImmediate22.default)((e) => { + throw e; + }, err); } - /** - * Gets the next filename to use for this instance in the case that log - * filesizes are being capped. - * @returns {string} - TODO: add return description. - * @private - */ - _getFile() { - const ext = path.extname(this._basename); - const basename = path.basename(this._basename, ext); - const isRotation = this.rotationFormat ? this.rotationFormat() : this._created; - return !this.tailable && this._created ? `${basename}${isRotation}${ext}` : `${basename}${ext}`; + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/wrapAsync.js +var require_wrapAsync = __commonJS({ + "node_modules/async/internal/wrapAsync.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.isAsyncIterable = exports2.isAsyncGenerator = exports2.isAsync = void 0; + var _asyncify = require_asyncify(); + var _asyncify2 = _interopRequireDefault(_asyncify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function isAsync(fn2) { + return fn2[Symbol.toStringTag] === "AsyncFunction"; + } + function isAsyncGenerator(fn2) { + return fn2[Symbol.toStringTag] === "AsyncGenerator"; + } + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === "function"; + } + function wrapAsync2(asyncFn) { + if (typeof asyncFn !== "function") throw new Error("expected a function"); + return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; + } + exports2.default = wrapAsync2; + exports2.isAsync = isAsync; + exports2.isAsyncGenerator = isAsyncGenerator; + exports2.isAsyncIterable = isAsyncIterable; + } +}); + +// node_modules/async/internal/awaitify.js +var require_awaitify = __commonJS({ + "node_modules/async/internal/awaitify.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = awaitify; + function awaitify(asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error("arity is undefined"); + function awaitable(...args) { + if (typeof args[arity - 1] === "function") { + return asyncFn.apply(this, args); + } + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err); + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }); } - /** - * Increment the number of files created or checked by this instance. - * @param {mixed} ext - TODO: add param description. - * @param {mixed} basename - TODO: add param description. - * @param {mixed} callback - TODO: add param description. - * @returns {undefined} - * @private - */ - _checkMaxFilesIncrementing(ext, basename, callback) { - if (!this.maxFiles || this._created < this.maxFiles) { - return setImmediate(callback); + return awaitable; + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/parallel.js +var require_parallel = __commonJS({ + "node_modules/async/internal/parallel.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _isArrayLike = require_isArrayLike(); + var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + var _wrapAsync = require_wrapAsync(); + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + var _awaitify = require_awaitify(); + var _awaitify2 = _interopRequireDefault(_awaitify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + exports2.default = (0, _awaitify2.default)((eachfn, tasks, callback) => { + var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; + eachfn(tasks, (task, key, taskCb) => { + (0, _wrapAsync2.default)(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, (err) => callback(err, results)); + }, 3); + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/once.js +var require_once = __commonJS({ + "node_modules/async/internal/once.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = once; + function once(fn2) { + function wrapper(...args) { + if (fn2 === null) return; + var callFn = fn2; + fn2 = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn2); + return wrapper; + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/getIterator.js +var require_getIterator = __commonJS({ + "node_modules/async/internal/getIterator.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = function(coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + }; + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/iterator.js +var require_iterator = __commonJS({ + "node_modules/async/internal/iterator.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = createIterator; + var _isArrayLike = require_isArrayLike(); + var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + var _getIterator = require_getIterator(); + var _getIterator2 = _interopRequireDefault(_getIterator); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? { value: coll[i], key: i } : null; + }; + } + function createES2015Iterator(iterator2) { + var i = -1; + return function next() { + var item = iterator2.next(); + if (item.done) return null; + i++; + return { value: item.value, key: i }; + }; + } + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === "__proto__") { + return next(); } - const oldest = this._created - this.maxFiles; - const isOldest = oldest !== 0 ? oldest : ""; - const isZipped = this.zippedArchive ? ".gz" : ""; - const filePath = `${basename}${isOldest}${ext}${isZipped}`; - const target = path.join(this.dirname, filePath); - fs2.unlink(target, callback); + return i < len ? { value: obj[key], key } : null; + }; + } + function createIterator(coll) { + if ((0, _isArrayLike2.default)(coll)) { + return createArrayIterator(coll); + } + var iterator2 = (0, _getIterator2.default)(coll); + return iterator2 ? createES2015Iterator(iterator2) : createObjectIterator(coll); + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/onlyOnce.js +var require_onlyOnce = __commonJS({ + "node_modules/async/internal/onlyOnce.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = onlyOnce; + function onlyOnce(fn2) { + return function(...args) { + if (fn2 === null) throw new Error("Callback was already called."); + var callFn = fn2; + fn2 = null; + callFn.apply(this, args); + }; + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/breakLoop.js +var require_breakLoop = __commonJS({ + "node_modules/async/internal/breakLoop.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var breakLoop = {}; + exports2.default = breakLoop; + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/asyncEachOfLimit.js +var require_asyncEachOfLimit = __commonJS({ + "node_modules/async/internal/asyncEachOfLimit.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = asyncEachOfLimit; + var _breakLoop = require_breakLoop(); + var _breakLoop2 = _interopRequireDefault(_breakLoop); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + function replenish() { + if (running >= limit || awaiting || done) return; + awaiting = true; + generator.next().then(({ value, done: iterDone }) => { + if (canceled || done) return; + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); } - /** - * Roll files forward based on integer, up to maxFiles. e.g. if base if - * file.log and it becomes oversized, roll to file1.log, and allow file.log - * to be re-used. If file is oversized again, roll file1.log to file2.log, - * roll file.log to file1.log, and so on. - * @param {mixed} ext - TODO: add param description. - * @param {mixed} basename - TODO: add param description. - * @param {mixed} callback - TODO: add param description. - * @returns {undefined} - * @private - */ - _checkMaxFilesTailable(ext, basename, callback) { - const tasks = []; - if (!this.maxFiles) { + function iterateeCallback(err, result) { + running -= 1; + if (canceled) return; + if (err) return handleError(err); + if (err === false) { + done = true; + canceled = true; return; } - const isZipped = this.zippedArchive ? ".gz" : ""; - for (let x2 = this.maxFiles - 1; x2 > 1; x2--) { - tasks.push(function(i, cb) { - let fileName = `${basename}${i - 1}${ext}${isZipped}`; - const tmppath = path.join(this.dirname, fileName); - fs2.exists(tmppath, (exists) => { - if (!exists) { - return cb(null); - } - fileName = `${basename}${i}${ext}${isZipped}`; - fs2.rename(tmppath, path.join(this.dirname, fileName), cb); - }); - }.bind(this, x2)); + if (result === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); } - asyncSeries(tasks, () => { - fs2.rename( - path.join(this.dirname, `${basename}${ext}${isZipped}`), - path.join(this.dirname, `${basename}1${ext}${isZipped}`), - callback - ); - }); - } - /** - * Compresses src to dest with gzip and unlinks src - * @param {string} src - path to source file. - * @param {string} dest - path to zipped destination file. - * @param {Function} callback - callback called after file has been compressed. - * @returns {undefined} - * @private - */ - _compressFile(src, dest, callback) { - fs2.access(src, fs2.F_OK, (err) => { - if (err) { - return callback(); - } - var gzip = zlib2.createGzip(); - var inp = fs2.createReadStream(src); - var out = fs2.createWriteStream(dest); - out.on("finish", () => { - fs2.unlink(src, callback); - }); - inp.pipe(gzip).pipe(out); - }); + replenish(); } - _createLogDirIfNotExist(dirPath) { - if (!fs2.existsSync(dirPath)) { - fs2.mkdirSync(dirPath, { recursive: true }); - } + function handleError(err) { + if (canceled) return; + awaiting = false; + done = true; + callback(err); } - }; + replenish(); + } + module2.exports = exports2.default; } }); -// node_modules/winston/lib/winston/transports/http.js -var require_http = __commonJS({ - "node_modules/winston/lib/winston/transports/http.js"(exports2, module2) { +// node_modules/async/internal/eachOfLimit.js +var require_eachOfLimit = __commonJS({ + "node_modules/async/internal/eachOfLimit.js"(exports2, module2) { "use strict"; - var http3 = __require("http"); - var https2 = __require("https"); - var { Stream } = require_readable(); - var TransportStream = require_winston_transport(); - var { configure } = require_safe_stable_stringify(); - module2.exports = class Http extends TransportStream { - /** - * Constructor function for the Http transport object responsible for - * persisting log messages and metadata to a terminal or TTY. - * @param {!Object} [options={}] - Options for this instance. - */ - // eslint-disable-next-line max-statements - constructor(options = {}) { - super(options); - this.options = options; - this.name = options.name || "http"; - this.ssl = !!options.ssl; - this.host = options.host || "localhost"; - this.port = options.port; - this.auth = options.auth; - this.path = options.path || ""; - this.maximumDepth = options.maximumDepth; - this.agent = options.agent; - this.headers = options.headers || {}; - this.headers["content-type"] = "application/json"; - this.batch = options.batch || false; - this.batchInterval = options.batchInterval || 5e3; - this.batchCount = options.batchCount || 10; - this.batchOptions = []; - this.batchTimeoutID = -1; - this.batchCallback = {}; - if (!this.port) { - this.port = this.ssl ? 443 : 80; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _once = require_once(); + var _once2 = _interopRequireDefault(_once); + var _iterator = require_iterator(); + var _iterator2 = _interopRequireDefault(_iterator); + var _onlyOnce = require_onlyOnce(); + var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + var _wrapAsync = require_wrapAsync(); + var _asyncEachOfLimit = require_asyncEachOfLimit(); + var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit); + var _breakLoop = require_breakLoop(); + var _breakLoop2 = _interopRequireDefault(_breakLoop); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + exports2.default = (limit) => { + return (obj, iteratee, callback) => { + callback = (0, _once2.default)(callback); + if (limit <= 0) { + throw new RangeError("concurrency limit cannot be less than 1"); } - } - /** - * Core logging method exposed to Winston. - * @param {Object} info - TODO: add param description. - * @param {function} callback - TODO: add param description. - * @returns {undefined} - */ - log(info, callback) { - this._request(info, null, null, (err, res) => { - if (res && res.statusCode !== 200) { - err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`); - } - if (err) { - this.emit("warn", err); - } else { - this.emit("logged", info); - } - }); - if (callback) { - setImmediate(callback); + if (!obj) { + return callback(null); } - } - /** - * Query the transport. Options object is optional. - * @param {Object} options - Loggly-like query options for this instance. - * @param {function} callback - Continuation to respond to when complete. - * @returns {undefined} - */ - query(options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; + if ((0, _wrapAsync.isAsyncGenerator)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback); } - options = { - method: "query", - params: this.normalizeQuery(options) - }; - const auth = options.params.auth || null; - delete options.params.auth; - const path = options.params.path || null; - delete options.params.path; - this._request(options, auth, path, (err, res, body) => { - if (res && res.statusCode !== 200) { - err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`); - } + if ((0, _wrapAsync.isAsyncIterable)(obj)) { + return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback); + } + var nextElem = (0, _iterator2.default)(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + function iterateeCallback(err, value) { + if (canceled) return; + running -= 1; if (err) { - return callback(err); + done = true; + callback(err); + } else if (err === false) { + done = true; + canceled = true; + } else if (value === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); + } else if (!looping) { + replenish(); } - if (typeof body === "string") { - try { - body = JSON.parse(body); - } catch (e) { - return callback(e); + } + function replenish() { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; } + running += 1; + iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); } - callback(null, body); - }); + looping = false; + } + replenish(); + }; + }; + module2.exports = exports2.default; + } +}); + +// node_modules/async/eachOfLimit.js +var require_eachOfLimit2 = __commonJS({ + "node_modules/async/eachOfLimit.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _eachOfLimit2 = require_eachOfLimit(); + var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + var _wrapAsync = require_wrapAsync(); + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + var _awaitify = require_awaitify(); + var _awaitify2 = _interopRequireDefault(_awaitify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function eachOfLimit(coll, limit, iteratee, callback) { + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); + } + exports2.default = (0, _awaitify2.default)(eachOfLimit, 4); + module2.exports = exports2.default; + } +}); + +// node_modules/async/eachOfSeries.js +var require_eachOfSeries = __commonJS({ + "node_modules/async/eachOfSeries.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _eachOfLimit = require_eachOfLimit2(); + var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + var _awaitify = require_awaitify(); + var _awaitify2 = _interopRequireDefault(_awaitify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function eachOfSeries(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); + } + exports2.default = (0, _awaitify2.default)(eachOfSeries, 3); + module2.exports = exports2.default; + } +}); + +// node_modules/async/series.js +var require_series = __commonJS({ + "node_modules/async/series.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = series; + var _parallel2 = require_parallel(); + var _parallel3 = _interopRequireDefault(_parallel2); + var _eachOfSeries = require_eachOfSeries(); + var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function series(tasks, callback) { + return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback); + } + module2.exports = exports2.default; + } +}); + +// node_modules/readable-stream/lib/_stream_transform.js +var require_stream_transform = __commonJS({ + "node_modules/readable-stream/lib/_stream_transform.js"(exports2, module2) { + "use strict"; + module2.exports = Transform; + var _require$codes = require_errors2().codes; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; + var ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING; + var ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + var Duplex = require_stream_duplex(); + require_inherits()(Transform, Duplex); + function afterTransform(er2, data) { + var ts2 = this._transformState; + ts2.transforming = false; + var cb = ts2.writecb; + if (cb === null) { + return this.emit("error", new ERR_MULTIPLE_CALLBACK()); } - /** - * Returns a log stream for this transport. Options object is optional. - * @param {Object} options - Stream options for this instance. - * @returns {Stream} - TODO: add return description - */ - stream(options = {}) { - const stream4 = new Stream(); - options = { - method: "stream", - params: options - }; - const path = options.params.path || null; - delete options.params.path; - const auth = options.params.auth || null; - delete options.params.auth; - let buff = ""; - const req = this._request(options, auth, path); - stream4.destroy = () => req.destroy(); - req.on("data", (data) => { - data = (buff + data).split(/\n+/); - const l = data.length - 1; - let i = 0; - for (; i < l; i++) { - try { - stream4.emit("log", JSON.parse(data[i])); - } catch (e) { - stream4.emit("error", e); - } - } - buff = data[l]; + ts2.writechunk = null; + ts2.writecb = null; + if (data != null) + this.push(data); + cb(er2); + var rs2 = this._readableState; + rs2.reading = false; + if (rs2.needReadable || rs2.length < rs2.highWaterMark) { + this._read(rs2.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + this._readableState.needReadable = true; + this._readableState.sync = false; + if (options) { + if (typeof options.transform === "function") this._transform = options.transform; + if (typeof options.flush === "function") this._flush = options.flush; + } + this.on("prefinish", prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === "function" && !this._readableState.destroyed) { + this._flush(function(er2, data) { + done(_this, er2, data); }); - req.on("error", (err) => stream4.emit("error", err)); - return stream4; + } else { + done(this, null, null); + } + } + Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + Transform.prototype._transform = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); + }; + Transform.prototype._write = function(chunk, encoding, cb) { + var ts2 = this._transformState; + ts2.writecb = cb; + ts2.writechunk = chunk; + ts2.writeencoding = encoding; + if (!ts2.transforming) { + var rs2 = this._readableState; + if (ts2.needTransform || rs2.needReadable || rs2.length < rs2.highWaterMark) this._read(rs2.highWaterMark); + } + }; + Transform.prototype._read = function(n) { + var ts2 = this._transformState; + if (ts2.writechunk !== null && !ts2.transforming) { + ts2.transforming = true; + this._transform(ts2.writechunk, ts2.writeencoding, ts2.afterTransform); + } else { + ts2.needTransform = true; + } + }; + Transform.prototype._destroy = function(err, cb) { + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + }); + }; + function done(stream4, er2, data) { + if (er2) return stream4.emit("error", er2); + if (data != null) + stream4.push(data); + if (stream4._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream4._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream4.push(null); + } + } +}); + +// node_modules/readable-stream/lib/_stream_passthrough.js +var require_stream_passthrough = __commonJS({ + "node_modules/readable-stream/lib/_stream_passthrough.js"(exports2, module2) { + "use strict"; + module2.exports = PassThrough; + var Transform = require_stream_transform(); + require_inherits()(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); + } + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); + }; + } +}); + +// node_modules/readable-stream/lib/internal/streams/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports2, module2) { + "use strict"; + var eos; + function once(callback) { + var called = false; + return function() { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + var _require$codes = require_errors2().codes; + var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function noop2(err) { + if (err) throw err; + } + function isRequest2(stream4) { + return stream4.setHeader && typeof stream4.abort === "function"; + } + function destroyer(stream4, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream4.on("close", function() { + closed = true; + }); + if (eos === void 0) eos = require_end_of_stream(); + eos(stream4, { + readable: reading, + writable: writing + }, function(err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function(err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + if (isRequest2(stream4)) return stream4.abort(); + if (typeof stream4.destroy === "function") return stream4.destroy(); + callback(err || new ERR_STREAM_DESTROYED("pipe")); + }; + } + function call2(fn2) { + fn2(); + } + function pipe(from5, to2) { + return from5.pipe(to2); + } + function popCallback(streams) { + if (!streams.length) return noop2; + if (typeof streams[streams.length - 1] !== "function") return noop2; + return streams.pop(); + } + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; } - /** - * Make a request to a winstond server or any http server which can - * handle json-rpc. - * @param {function} options - Options to sent the request. - * @param {Object?} auth - authentication options - * @param {string} path - request path - * @param {function} callback - Continuation to respond to when complete. - */ - _request(options, auth, path, callback) { - options = options || {}; - auth = auth || this.auth; - path = path || this.path || ""; - if (this.batch) { - this._doBatch(options, callback, auth, path); - } else { - this._doRequest(options, callback, auth, path); - } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS("streams"); } - /** - * Send or memorize the options according to batch configuration - * @param {function} options - Options to sent the request. - * @param {function} callback - Continuation to respond to when complete. - * @param {Object?} auth - authentication options - * @param {string} path - request path - */ - _doBatch(options, callback, auth, path) { - this.batchOptions.push(options); - if (this.batchOptions.length === 1) { - const me = this; - this.batchCallback = callback; - this.batchTimeoutID = setTimeout(function() { - me.batchTimeoutID = -1; - me._doBatchRequest(me.batchCallback, auth, path); - }, this.batchInterval); - } - if (this.batchOptions.length === this.batchCount) { - this._doBatchRequest(this.batchCallback, auth, path); + var error; + var destroys = streams.map(function(stream4, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream4, reading, writing, function(err) { + if (!error) error = err; + if (err) destroys.forEach(call2); + if (reading) return; + destroys.forEach(call2); + callback(error); + }); + }); + return streams.reduce(pipe); + } + module2.exports = pipeline; + } +}); + +// node_modules/readable-stream/readable.js +var require_readable = __commonJS({ + "node_modules/readable-stream/readable.js"(exports2, module2) { + var Stream = __require("stream"); + if (process.env.READABLE_STREAM === "disable" && Stream) { + module2.exports = Stream.Readable; + Object.assign(module2.exports, Stream); + module2.exports.Stream = Stream; + } else { + exports2 = module2.exports = require_stream_readable(); + exports2.Stream = Stream || exports2; + exports2.Readable = exports2; + exports2.Writable = require_stream_writable(); + exports2.Duplex = require_stream_duplex(); + exports2.Transform = require_stream_transform(); + exports2.PassThrough = require_stream_passthrough(); + exports2.finished = require_end_of_stream(); + exports2.pipeline = require_pipeline(); + } + } +}); + +// node_modules/@dabh/diagnostics/diagnostics.js +var require_diagnostics = __commonJS({ + "node_modules/@dabh/diagnostics/diagnostics.js"(exports2, module2) { + var adapters = []; + var modifiers2 = []; + var logger = function devnull() { + }; + function use(adapter) { + if (~adapters.indexOf(adapter)) return false; + adapters.push(adapter); + return true; + } + function set(custom) { + logger = custom; + } + function enabled(namespace) { + var async = []; + for (var i = 0; i < adapters.length; i++) { + if (adapters[i].async) { + async.push(adapters[i]); + continue; } + if (adapters[i](namespace)) return true; } - /** - * Initiate a request with the memorized batch options, stop the batch timeout - * @param {function} callback - Continuation to respond to when complete. - * @param {Object?} auth - authentication options - * @param {string} path - request path - */ - _doBatchRequest(callback, auth, path) { - if (this.batchTimeoutID > 0) { - clearTimeout(this.batchTimeoutID); - this.batchTimeoutID = -1; - } - const batchOptionsCopy = this.batchOptions.slice(); - this.batchOptions = []; - this._doRequest(batchOptionsCopy, callback, auth, path); + if (!async.length) return false; + return new Promise(function pinky(resolve) { + Promise.all( + async.map(function prebind(fn2) { + return fn2(namespace); + }) + ).then(function resolved(values) { + resolve(values.some(Boolean)); + }); + }); + } + function modify(fn2) { + if (~modifiers2.indexOf(fn2)) return false; + modifiers2.push(fn2); + return true; + } + function write() { + logger.apply(logger, arguments); + } + function process4(message) { + for (var i = 0; i < modifiers2.length; i++) { + message = modifiers2[i].apply(modifiers2[i], arguments); } - /** - * Make a request to a winstond server or any http server which can - * handle json-rpc. - * @param {function} options - Options to sent the request. - * @param {function} callback - Continuation to respond to when complete. - * @param {Object?} auth - authentication options - * @param {string} path - request path - */ - _doRequest(options, callback, auth, path) { - const headers = Object.assign({}, this.headers); - if (auth && auth.bearer) { - headers.Authorization = `Bearer ${auth.bearer}`; + return message; + } + function introduce(fn2, options) { + var has = Object.prototype.hasOwnProperty; + for (var key in options) { + if (has.call(options, key)) { + fn2[key] = options[key]; } - const req = (this.ssl ? https2 : http3).request({ - ...this.options, - method: "POST", - host: this.host, - port: this.port, - path: `/${path.replace(/^\//, "")}`, - headers, - auth: auth && auth.username && auth.password ? `${auth.username}:${auth.password}` : "", - agent: this.agent - }); - req.on("error", callback); - req.on("response", (res) => res.on("end", () => callback(null, res)).resume()); - const jsonStringify = configure({ - ...this.maximumDepth && { maximumDepth: this.maximumDepth } - }); - req.end(Buffer.from(jsonStringify(options, this.options.replacer), "utf8")); } + return fn2; + } + function nope(options) { + options.enabled = false; + options.modify = modify; + options.set = set; + options.use = use; + return introduce(function diagnopes() { + return false; + }, options); + } + function yep(options) { + function diagnostics() { + var args = Array.prototype.slice.call(arguments, 0); + write.call(write, options, process4(args, options)); + return true; + } + options.enabled = true; + options.modify = modify; + options.set = set; + options.use = use; + return introduce(diagnostics, options); + } + module2.exports = function create(diagnostics) { + diagnostics.introduce = introduce; + diagnostics.enabled = enabled; + diagnostics.process = process4; + diagnostics.modify = modify; + diagnostics.write = write; + diagnostics.nope = nope; + diagnostics.yep = yep; + diagnostics.set = set; + diagnostics.use = use; + return diagnostics; }; } }); -// node_modules/is-stream/index.js -var require_is_stream = __commonJS({ - "node_modules/is-stream/index.js"(exports2, module2) { +// node_modules/@dabh/diagnostics/node/production.js +var require_production = __commonJS({ + "node_modules/@dabh/diagnostics/node/production.js"(exports2, module2) { + var create = require_diagnostics(); + var diagnostics = create(function prod(namespace, options) { + options = options || {}; + options.namespace = namespace; + options.prod = true; + options.dev = false; + if (!(options.force || prod.force)) return prod.nope(options); + return prod.yep(options); + }); + module2.exports = diagnostics; + } +}); + +// node_modules/color-name/index.js +var require_color_name = __commonJS({ + "node_modules/color-name/index.js"(exports2, module2) { "use strict"; - var isStream2 = (stream4) => stream4 !== null && typeof stream4 === "object" && typeof stream4.pipe === "function"; - isStream2.writable = (stream4) => isStream2(stream4) && stream4.writable !== false && typeof stream4._write === "function" && typeof stream4._writableState === "object"; - isStream2.readable = (stream4) => isStream2(stream4) && stream4.readable !== false && typeof stream4._read === "function" && typeof stream4._readableState === "object"; - isStream2.duplex = (stream4) => isStream2.writable(stream4) && isStream2.readable(stream4); - isStream2.transform = (stream4) => isStream2.duplex(stream4) && typeof stream4._transform === "function"; - module2.exports = isStream2; + module2.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; } }); -// node_modules/winston/lib/winston/transports/stream.js -var require_stream2 = __commonJS({ - "node_modules/winston/lib/winston/transports/stream.js"(exports2, module2) { +// node_modules/simple-swizzle/node_modules/is-arrayish/index.js +var require_is_arrayish = __commonJS({ + "node_modules/simple-swizzle/node_modules/is-arrayish/index.js"(exports2, module2) { + module2.exports = function isArrayish(obj) { + if (!obj || typeof obj === "string") { + return false; + } + return obj instanceof Array || Array.isArray(obj) || obj.length >= 0 && (obj.splice instanceof Function || Object.getOwnPropertyDescriptor(obj, obj.length - 1) && obj.constructor.name !== "String"); + }; + } +}); + +// node_modules/simple-swizzle/index.js +var require_simple_swizzle = __commonJS({ + "node_modules/simple-swizzle/index.js"(exports2, module2) { "use strict"; - var isStream2 = require_is_stream(); - var { MESSAGE } = require_triple_beam(); - var os2 = __require("os"); - var TransportStream = require_winston_transport(); - module2.exports = class Stream extends TransportStream { - /** - * Constructor function for the Console transport object responsible for - * persisting log messages and metadata to a terminal or TTY. - * @param {!Object} [options={}] - Options for this instance. - */ - constructor(options = {}) { - super(options); - if (!options.stream || !isStream2(options.stream)) { - throw new Error("options.stream is required."); + var isArrayish = require_is_arrayish(); + var concat3 = Array.prototype.concat; + var slice3 = Array.prototype.slice; + var swizzle = module2.exports = function swizzle2(args) { + var results = []; + for (var i = 0, len = args.length; i < len; i++) { + var arg = args[i]; + if (isArrayish(arg)) { + results = concat3.call(results, slice3.call(arg)); + } else { + results.push(arg); + } + } + return results; + }; + swizzle.wrap = function(fn2) { + return function() { + return fn2(swizzle(arguments)); + }; + }; + } +}); + +// node_modules/color-string/index.js +var require_color_string = __commonJS({ + "node_modules/color-string/index.js"(exports2, module2) { + var colorNames = require_color_name(); + var swizzle = require_simple_swizzle(); + var hasOwnProperty2 = Object.hasOwnProperty; + var reverseNames = /* @__PURE__ */ Object.create(null); + for (name in colorNames) { + if (hasOwnProperty2.call(colorNames, name)) { + reverseNames[colorNames[name]] = name; + } + } + var name; + var cs = module2.exports = { + to: {}, + get: {} + }; + cs.get = function(string) { + var prefix = string.substring(0, 3).toLowerCase(); + var val; + var model; + switch (prefix) { + case "hsl": + val = cs.get.hsl(string); + model = "hsl"; + break; + case "hwb": + val = cs.get.hwb(string); + model = "hwb"; + break; + default: + val = cs.get.rgb(string); + model = "rgb"; + break; + } + if (!val) { + return null; + } + return { model, value: val }; + }; + cs.get.rgb = function(string) { + if (!string) { + return null; + } + var abbr = /^#([a-f0-9]{3,4})$/i; + var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i; + var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; + var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; + var keyword = /^(\w+)$/; + var rgb = [0, 0, 0, 1]; + var match; + var i; + var hexAlpha; + if (match = string.match(hex)) { + hexAlpha = match[2]; + match = match[1]; + for (i = 0; i < 3; i++) { + var i2 = i * 2; + rgb[i] = parseInt(match.slice(i2, i2 + 2), 16); } - this._stream = options.stream; - this._stream.setMaxListeners(Infinity); - this.isObjectMode = options.stream._writableState.objectMode; - this.eol = typeof options.eol === "string" ? options.eol : os2.EOL; - } - /** - * Core logging method exposed to Winston. - * @param {Object} info - TODO: add param description. - * @param {Function} callback - TODO: add param description. - * @returns {undefined} - */ - log(info, callback) { - setImmediate(() => this.emit("logged", info)); - if (this.isObjectMode) { - this._stream.write(info); - if (callback) { - callback(); + if (hexAlpha) { + rgb[3] = parseInt(hexAlpha, 16) / 255; + } + } else if (match = string.match(abbr)) { + match = match[1]; + hexAlpha = match[3]; + for (i = 0; i < 3; i++) { + rgb[i] = parseInt(match[i] + match[i], 16); + } + if (hexAlpha) { + rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255; + } + } else if (match = string.match(rgba)) { + for (i = 0; i < 3; i++) { + rgb[i] = parseInt(match[i + 1], 0); + } + if (match[4]) { + if (match[5]) { + rgb[3] = parseFloat(match[4]) * 0.01; + } else { + rgb[3] = parseFloat(match[4]); } - return; } - this._stream.write(`${info[MESSAGE]}${this.eol}`); - if (callback) { - callback(); + } else if (match = string.match(per)) { + for (i = 0; i < 3; i++) { + rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); } - return; - } - }; - } -}); - -// node_modules/winston/lib/winston/transports/index.js -var require_transports = __commonJS({ - "node_modules/winston/lib/winston/transports/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "Console", { - configurable: true, - enumerable: true, - get() { - return require_console(); + if (match[4]) { + if (match[5]) { + rgb[3] = parseFloat(match[4]) * 0.01; + } else { + rgb[3] = parseFloat(match[4]); + } + } + } else if (match = string.match(keyword)) { + if (match[1] === "transparent") { + return [0, 0, 0, 0]; + } + if (!hasOwnProperty2.call(colorNames, match[1])) { + return null; + } + rgb = colorNames[match[1]]; + rgb[3] = 1; + return rgb; + } else { + return null; } - }); - Object.defineProperty(exports2, "File", { - configurable: true, - enumerable: true, - get() { - return require_file(); + for (i = 0; i < 3; i++) { + rgb[i] = clamp(rgb[i], 0, 255); } - }); - Object.defineProperty(exports2, "Http", { - configurable: true, - enumerable: true, - get() { - return require_http(); + rgb[3] = clamp(rgb[3], 0, 1); + return rgb; + }; + cs.get.hsl = function(string) { + if (!string) { + return null; } - }); - Object.defineProperty(exports2, "Stream", { - configurable: true, - enumerable: true, - get() { - return require_stream2(); + var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; + var match = string.match(hsl); + if (match) { + var alpha = parseFloat(match[4]); + var h = (parseFloat(match[1]) % 360 + 360) % 360; + var s = clamp(parseFloat(match[2]), 0, 100); + var l = clamp(parseFloat(match[3]), 0, 100); + var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, s, l, a]; } - }); - } -}); - -// node_modules/winston/lib/winston/config/index.js -var require_config2 = __commonJS({ - "node_modules/winston/lib/winston/config/index.js"(exports2) { - "use strict"; - var logform = require_logform(); - var { configs } = require_triple_beam(); - exports2.cli = logform.levels(configs.cli); - exports2.npm = logform.levels(configs.npm); - exports2.syslog = logform.levels(configs.syslog); - exports2.addColors = logform.levels; - } -}); - -// node_modules/async/eachOf.js -var require_eachOf = __commonJS({ - "node_modules/async/eachOf.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - var _isArrayLike = require_isArrayLike(); - var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - var _breakLoop = require_breakLoop(); - var _breakLoop2 = _interopRequireDefault(_breakLoop); - var _eachOfLimit = require_eachOfLimit2(); - var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - var _once = require_once(); - var _once2 = _interopRequireDefault(_once); - var _onlyOnce = require_onlyOnce(); - var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - var _wrapAsync = require_wrapAsync(); - var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - var _awaitify = require_awaitify(); - var _awaitify2 = _interopRequireDefault(_awaitify); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function eachOfArrayLike(coll, iteratee, callback) { - callback = (0, _once2.default)(callback); - var index2 = 0, completed = 0, { length } = coll, canceled = false; - if (length === 0) { - callback(null); + return null; + }; + cs.get.hwb = function(string) { + if (!string) { + return null; } - function iteratorCallback(err, value) { - if (err === false) { - canceled = true; - } - if (canceled === true) return; - if (err) { - callback(err); - } else if (++completed === length || value === _breakLoop2.default) { - callback(null); - } + var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; + var match = string.match(hwb); + if (match) { + var alpha = parseFloat(match[4]); + var h = (parseFloat(match[1]) % 360 + 360) % 360; + var w2 = clamp(parseFloat(match[2]), 0, 100); + var b2 = clamp(parseFloat(match[3]), 0, 100); + var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, w2, b2, a]; } - for (; index2 < length; index2++) { - iteratee(coll[index2], index2, (0, _onlyOnce2.default)(iteratorCallback)); + return null; + }; + cs.to.hex = function() { + var rgba = swizzle(arguments); + return "#" + hexDouble(rgba[0]) + hexDouble(rgba[1]) + hexDouble(rgba[2]) + (rgba[3] < 1 ? hexDouble(Math.round(rgba[3] * 255)) : ""); + }; + cs.to.rgb = function() { + var rgba = swizzle(arguments); + return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ")" : "rgba(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ", " + rgba[3] + ")"; + }; + cs.to.rgb.percent = function() { + var rgba = swizzle(arguments); + var r = Math.round(rgba[0] / 255 * 100); + var g = Math.round(rgba[1] / 255 * 100); + var b2 = Math.round(rgba[2] / 255 * 100); + return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + r + "%, " + g + "%, " + b2 + "%)" : "rgba(" + r + "%, " + g + "%, " + b2 + "%, " + rgba[3] + ")"; + }; + cs.to.hsl = function() { + var hsla = swizzle(arguments); + return hsla.length < 4 || hsla[3] === 1 ? "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)" : "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + hsla[3] + ")"; + }; + cs.to.hwb = function() { + var hwba = swizzle(arguments); + var a = ""; + if (hwba.length >= 4 && hwba[3] !== 1) { + a = ", " + hwba[3]; } + return "hwb(" + hwba[0] + ", " + hwba[1] + "%, " + hwba[2] + "%" + a + ")"; + }; + cs.to.keyword = function(rgb) { + return reverseNames[rgb.slice(0, 3)]; + }; + function clamp(num2, min, max) { + return Math.min(Math.max(min, num2), max); } - function eachOfGeneric(coll, iteratee, callback) { - return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); - } - function eachOf(coll, iteratee, callback) { - var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; - return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); + function hexDouble(num2) { + var str = Math.round(num2).toString(16).toUpperCase(); + return str.length < 2 ? "0" + str : str; } - exports2.default = (0, _awaitify2.default)(eachOf, 3); - module2.exports = exports2.default; } }); -// node_modules/async/internal/withoutIndex.js -var require_withoutIndex = __commonJS({ - "node_modules/async/internal/withoutIndex.js"(exports2, module2) { +// node_modules/color/node_modules/color-convert/node_modules/color-name/index.js +var require_color_name2 = __commonJS({ + "node_modules/color/node_modules/color-convert/node_modules/color-name/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2.default = _withoutIndex; - function _withoutIndex(iteratee) { - return (value, index2, callback) => iteratee(value, callback); - } - module2.exports = exports2.default; + module2.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; } }); -// node_modules/async/forEach.js -var require_forEach = __commonJS({ - "node_modules/async/forEach.js"(exports2, module2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - var _eachOf = require_eachOf(); - var _eachOf2 = _interopRequireDefault(_eachOf); - var _withoutIndex = require_withoutIndex(); - var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - var _wrapAsync = require_wrapAsync(); - var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - var _awaitify = require_awaitify(); - var _awaitify2 = _interopRequireDefault(_awaitify); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; +// node_modules/color/node_modules/color-convert/conversions.js +var require_conversions = __commonJS({ + "node_modules/color/node_modules/color-convert/conversions.js"(exports2, module2) { + var cssKeywords = require_color_name2(); + var reverseKeywords = {}; + for (key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } } - function eachLimit(coll, iteratee, callback) { - return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); + var key; + var convert = module2.exports = { + rgb: { channels: 3, labels: "rgb" }, + hsl: { channels: 3, labels: "hsl" }, + hsv: { channels: 3, labels: "hsv" }, + hwb: { channels: 3, labels: "hwb" }, + cmyk: { channels: 4, labels: "cmyk" }, + xyz: { channels: 3, labels: "xyz" }, + lab: { channels: 3, labels: "lab" }, + lch: { channels: 3, labels: "lch" }, + hex: { channels: 1, labels: ["hex"] }, + keyword: { channels: 1, labels: ["keyword"] }, + ansi16: { channels: 1, labels: ["ansi16"] }, + ansi256: { channels: 1, labels: ["ansi256"] }, + hcg: { channels: 3, labels: ["h", "c", "g"] }, + apple: { channels: 3, labels: ["r16", "g16", "b16"] }, + gray: { channels: 1, labels: ["gray"] } + }; + for (model in convert) { + if (convert.hasOwnProperty(model)) { + if (!("channels" in convert[model])) { + throw new Error("missing channels property: " + model); + } + if (!("labels" in convert[model])) { + throw new Error("missing channel labels property: " + model); + } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error("channel and label counts mismatch: " + model); + } + channels = convert[model].channels; + labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], "channels", { value: channels }); + Object.defineProperty(convert[model], "labels", { value: labels }); + } } - exports2.default = (0, _awaitify2.default)(eachLimit, 3); - module2.exports = exports2.default; - } -}); - -// node_modules/fn.name/index.js -var require_fn = __commonJS({ - "node_modules/fn.name/index.js"(exports2, module2) { - "use strict"; - var toString3 = Object.prototype.toString; - module2.exports = function name(fn2) { - if ("string" === typeof fn2.displayName && fn2.constructor.name) { - return fn2.displayName; - } else if ("string" === typeof fn2.name && fn2.name) { - return fn2.name; + var channels; + var labels; + var model; + convert.rgb.hsl = function(rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b2 = rgb[2] / 255; + var min = Math.min(r, g, b2); + var max = Math.max(r, g, b2); + var delta = max - min; + var h; + var s; + var l; + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b2) / delta; + } else if (g === max) { + h = 2 + (b2 - r) / delta; + } else if (b2 === max) { + h = 4 + (r - g) / delta; } - if ("object" === typeof fn2 && fn2.constructor && "string" === typeof fn2.constructor.name) return fn2.constructor.name; - var named = fn2.toString(), type = toString3.call(fn2).slice(8, -1); - if ("Function" === type) { - named = named.substring(named.indexOf("(") + 1, named.indexOf(")")); + h = Math.min(h * 60, 360); + if (h < 0) { + h += 360; + } + l = (min + max) / 2; + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + return [h, s * 100, l * 100]; + }; + convert.rgb.hsv = function(rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b2 = rgb[2] / 255; + var v = Math.max(r, g, b2); + var diff = v - Math.min(r, g, b2); + var diffc = function(c) { + return (v - c) / 6 / diff + 1 / 2; + }; + if (diff === 0) { + h = s = 0; } else { - named = type; + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b2); + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = 1 / 3 + rdif - bdif; + } else if (b2 === v) { + h = 2 / 3 + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } } - return named || "anonymous"; + return [ + h * 360, + s * 100, + v * 100 + ]; }; - } -}); - -// node_modules/one-time/index.js -var require_one_time = __commonJS({ - "node_modules/one-time/index.js"(exports2, module2) { - "use strict"; - var name = require_fn(); - module2.exports = function one(fn2) { - var called = 0, value; - function onetime() { - if (called) return value; - called = 1; - value = fn2.apply(this, arguments); - fn2 = null; - return value; - } - onetime.displayName = name(fn2); - return onetime; + convert.rgb.hwb = function(rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b2 = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w2 = 1 / 255 * Math.min(r, Math.min(g, b2)); + b2 = 1 - 1 / 255 * Math.max(r, Math.max(g, b2)); + return [h, w2 * 100, b2 * 100]; }; - } -}); - -// node_modules/stack-trace/lib/stack-trace.js -var require_stack_trace = __commonJS({ - "node_modules/stack-trace/lib/stack-trace.js"(exports2) { - exports2.get = function(belowFn) { - var oldLimit = Error.stackTraceLimit; - Error.stackTraceLimit = Infinity; - var dummyObject = {}; - var v8Handler = Error.prepareStackTrace; - Error.prepareStackTrace = function(dummyObject2, v8StackTrace2) { - return v8StackTrace2; - }; - Error.captureStackTrace(dummyObject, belowFn || exports2.get); - var v8StackTrace = dummyObject.stack; - Error.prepareStackTrace = v8Handler; - Error.stackTraceLimit = oldLimit; - return v8StackTrace; + convert.rgb.cmyk = function(rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b2 = rgb[2] / 255; + var c; + var m2; + var y2; + var k2; + k2 = Math.min(1 - r, 1 - g, 1 - b2); + c = (1 - r - k2) / (1 - k2) || 0; + m2 = (1 - g - k2) / (1 - k2) || 0; + y2 = (1 - b2 - k2) / (1 - k2) || 0; + return [c * 100, m2 * 100, y2 * 100, k2 * 100]; }; - exports2.parse = function(err) { - if (!err.stack) { - return []; + function comparativeDistance(x2, y2) { + return Math.pow(x2[0] - y2[0], 2) + Math.pow(x2[1] - y2[1], 2) + Math.pow(x2[2] - y2[2], 2); + } + convert.rgb.keyword = function(rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; } - var self2 = this; - var lines = err.stack.split("\n").slice(1); - return lines.map(function(line) { - if (line.match(/^\s*[-]{4,}$/)) { - return self2._createParsedCallSite({ - fileName: line, - lineNumber: null, - functionName: null, - typeName: null, - methodName: null, - columnNumber: null, - "native": null - }); - } - var lineMatch = line.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/); - if (!lineMatch) { - return; - } - var object = null; - var method = null; - var functionName = null; - var typeName = null; - var methodName = null; - var isNative = lineMatch[5] === "native"; - if (lineMatch[1]) { - functionName = lineMatch[1]; - var methodStart = functionName.lastIndexOf("."); - if (functionName[methodStart - 1] == ".") - methodStart--; - if (methodStart > 0) { - object = functionName.substr(0, methodStart); - method = functionName.substr(methodStart + 1); - var objectEnd = object.indexOf(".Module"); - if (objectEnd > 0) { - functionName = functionName.substr(objectEnd + 1); - object = object.substr(0, objectEnd); - } + var currentClosestDistance = Infinity; + var currentClosestKeyword; + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + var distance = comparativeDistance(rgb, value); + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; } - typeName = null; } - if (method) { - typeName = object; - methodName = method; + } + return currentClosestKeyword; + }; + convert.keyword.rgb = function(keyword) { + return cssKeywords[keyword]; + }; + convert.rgb.xyz = function(rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b2 = rgb[2] / 255; + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b2 = b2 > 0.04045 ? Math.pow((b2 + 0.055) / 1.055, 2.4) : b2 / 12.92; + var x2 = r * 0.4124 + g * 0.3576 + b2 * 0.1805; + var y2 = r * 0.2126 + g * 0.7152 + b2 * 0.0722; + var z = r * 0.0193 + g * 0.1192 + b2 * 0.9505; + return [x2 * 100, y2 * 100, z * 100]; + }; + convert.rgb.lab = function(rgb) { + var xyz = convert.rgb.xyz(rgb); + var x2 = xyz[0]; + var y2 = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b2; + x2 /= 95.047; + y2 /= 100; + z /= 108.883; + x2 = x2 > 8856e-6 ? Math.pow(x2, 1 / 3) : 7.787 * x2 + 16 / 116; + y2 = y2 > 8856e-6 ? Math.pow(y2, 1 / 3) : 7.787 * y2 + 16 / 116; + z = z > 8856e-6 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y2 - 16; + a = 500 * (x2 - y2); + b2 = 200 * (y2 - z); + return [l, a, b2]; + }; + convert.hsl.rgb = function(hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + t1 = 2 * l - t2; + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; } - if (method === "") { - methodName = null; - functionName = null; + if (t3 > 1) { + t3--; } - var properties = { - fileName: lineMatch[2] || null, - lineNumber: parseInt(lineMatch[3], 10) || null, - functionName, - typeName, - methodName, - columnNumber: parseInt(lineMatch[4], 10) || null, - "native": isNative - }; - return self2._createParsedCallSite(properties); - }).filter(function(callSite) { - return !!callSite; - }); + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + rgb[i] = val * 255; + } + return rgb; }; - function CallSite(properties) { - for (var property in properties) { - this[property] = properties[property]; + convert.hsl.hsv = function(hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; + }; + convert.hsv.rgb = function(hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi2 = Math.floor(h) % 6; + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q2 = 255 * v * (1 - s * f); + var t = 255 * v * (1 - s * (1 - f)); + v *= 255; + switch (hi2) { + case 0: + return [v, t, p]; + case 1: + return [q2, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q2, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q2]; } - } - var strProperties = [ - "this", - "typeName", - "functionName", - "methodName", - "fileName", - "lineNumber", - "columnNumber", - "function", - "evalOrigin" - ]; - var boolProperties = [ - "topLevel", - "eval", - "native", - "constructor" - ]; - strProperties.forEach(function(property) { - CallSite.prototype[property] = null; - CallSite.prototype["get" + property[0].toUpperCase() + property.substr(1)] = function() { - return this[property]; - }; - }); - boolProperties.forEach(function(property) { - CallSite.prototype[property] = false; - CallSite.prototype["is" + property[0].toUpperCase() + property.substr(1)] = function() { - return this[property]; - }; - }); - exports2._createParsedCallSite = function(properties) { - return new CallSite(properties); }; - } -}); - -// node_modules/winston/lib/winston/exception-stream.js -var require_exception_stream = __commonJS({ - "node_modules/winston/lib/winston/exception-stream.js"(exports2, module2) { - "use strict"; - var { Writable } = require_readable(); - module2.exports = class ExceptionStream extends Writable { - /** - * Constructor function for the ExceptionStream responsible for wrapping a - * TransportStream; only allowing writes of `info` objects with - * `info.exception` set to true. - * @param {!TransportStream} transport - Stream to filter to exceptions - */ - constructor(transport) { - super({ objectMode: true }); - if (!transport) { - throw new Error("ExceptionStream requires a TransportStream instance."); - } - this.handleExceptions = true; - this.transport = transport; + convert.hsv.hsl = function(hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl2; + var l; + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl2 = s * vmin; + sl2 /= lmin <= 1 ? lmin : 2 - lmin; + sl2 = sl2 || 0; + l /= 2; + return [h, sl2 * 100, l * 100]; + }; + convert.hwb.rgb = function(hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl2 = hwb[2] / 100; + var ratio = wh + bl2; + var i; + var v; + var f; + var n; + if (ratio > 1) { + wh /= ratio; + bl2 /= ratio; } - /** - * Writes the info object to our transport instance if (and only if) the - * `exception` property is set on the info. - * @param {mixed} info - TODO: add param description. - * @param {mixed} enc - TODO: add param description. - * @param {mixed} callback - TODO: add param description. - * @returns {mixed} - TODO: add return description. - * @private - */ - _write(info, enc, callback) { - if (info.exception) { - return this.transport.log(info, callback); - } - callback(); - return true; + i = Math.floor(6 * h); + v = 1 - bl2; + f = 6 * h - i; + if ((i & 1) !== 0) { + f = 1 - f; + } + n = wh + f * (v - wh); + var r; + var g; + var b2; + switch (i) { + default: + case 6: + case 0: + r = v; + g = n; + b2 = wh; + break; + case 1: + r = n; + g = v; + b2 = wh; + break; + case 2: + r = wh; + g = v; + b2 = n; + break; + case 3: + r = wh; + g = n; + b2 = v; + break; + case 4: + r = n; + g = wh; + b2 = v; + break; + case 5: + r = v; + g = wh; + b2 = n; + break; + } + return [r * 255, g * 255, b2 * 255]; + }; + convert.cmyk.rgb = function(cmyk) { + var c = cmyk[0] / 100; + var m2 = cmyk[1] / 100; + var y2 = cmyk[2] / 100; + var k2 = cmyk[3] / 100; + var r; + var g; + var b2; + r = 1 - Math.min(1, c * (1 - k2) + k2); + g = 1 - Math.min(1, m2 * (1 - k2) + k2); + b2 = 1 - Math.min(1, y2 * (1 - k2) + k2); + return [r * 255, g * 255, b2 * 255]; + }; + convert.xyz.rgb = function(xyz) { + var x2 = xyz[0] / 100; + var y2 = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b2; + r = x2 * 3.2406 + y2 * -1.5372 + z * -0.4986; + g = x2 * -0.9689 + y2 * 1.8758 + z * 0.0415; + b2 = x2 * 0.0557 + y2 * -0.204 + z * 1.057; + r = r > 31308e-7 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : r * 12.92; + g = g > 31308e-7 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : g * 12.92; + b2 = b2 > 31308e-7 ? 1.055 * Math.pow(b2, 1 / 2.4) - 0.055 : b2 * 12.92; + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b2 = Math.min(Math.max(0, b2), 1); + return [r * 255, g * 255, b2 * 255]; + }; + convert.xyz.lab = function(xyz) { + var x2 = xyz[0]; + var y2 = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b2; + x2 /= 95.047; + y2 /= 100; + z /= 108.883; + x2 = x2 > 8856e-6 ? Math.pow(x2, 1 / 3) : 7.787 * x2 + 16 / 116; + y2 = y2 > 8856e-6 ? Math.pow(y2, 1 / 3) : 7.787 * y2 + 16 / 116; + z = z > 8856e-6 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y2 - 16; + a = 500 * (x2 - y2); + b2 = 200 * (y2 - z); + return [l, a, b2]; + }; + convert.lab.xyz = function(lab) { + var l = lab[0]; + var a = lab[1]; + var b2 = lab[2]; + var x2; + var y2; + var z; + y2 = (l + 16) / 116; + x2 = a / 500 + y2; + z = y2 - b2 / 200; + var y22 = Math.pow(y2, 3); + var x22 = Math.pow(x2, 3); + var z2 = Math.pow(z, 3); + y2 = y22 > 8856e-6 ? y22 : (y2 - 16 / 116) / 7.787; + x2 = x22 > 8856e-6 ? x22 : (x2 - 16 / 116) / 7.787; + z = z2 > 8856e-6 ? z2 : (z - 16 / 116) / 7.787; + x2 *= 95.047; + y2 *= 100; + z *= 108.883; + return [x2, y2, z]; + }; + convert.lab.lch = function(lab) { + var l = lab[0]; + var a = lab[1]; + var b2 = lab[2]; + var hr2; + var h; + var c; + hr2 = Math.atan2(b2, a); + h = hr2 * 360 / 2 / Math.PI; + if (h < 0) { + h += 360; } + c = Math.sqrt(a * a + b2 * b2); + return [l, c, h]; }; - } -}); - -// node_modules/winston/lib/winston/exception-handler.js -var require_exception_handler = __commonJS({ - "node_modules/winston/lib/winston/exception-handler.js"(exports2, module2) { - "use strict"; - var os2 = __require("os"); - var asyncForEach = require_forEach(); - var debug = require_node3()("winston:exception"); - var once = require_one_time(); - var stackTrace = require_stack_trace(); - var ExceptionStream = require_exception_stream(); - module2.exports = class ExceptionHandler { - /** - * TODO: add contructor description - * @param {!Logger} logger - TODO: add param description - */ - constructor(logger) { - if (!logger) { - throw new Error("Logger is required to handle exceptions"); - } - this.logger = logger; - this.handlers = /* @__PURE__ */ new Map(); - } - /** - * Handles `uncaughtException` events for the current process by adding any - * handlers passed in. - * @returns {undefined} - */ - handle(...args) { - args.forEach((arg) => { - if (Array.isArray(arg)) { - return arg.forEach((handler) => this._addHandler(handler)); - } - this._addHandler(arg); - }); - if (!this.catcher) { - this.catcher = this._uncaughtException.bind(this); - process.on("uncaughtException", this.catcher); - } + convert.lch.lab = function(lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b2; + var hr2; + hr2 = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr2); + b2 = c * Math.sin(hr2); + return [l, a, b2]; + }; + convert.rgb.ansi16 = function(args) { + var r = args[0]; + var g = args[1]; + var b2 = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; + value = Math.round(value / 50); + if (value === 0) { + return 30; } - /** - * Removes any handlers to `uncaughtException` events for the current - * process. This does not modify the state of the `this.handlers` set. - * @returns {undefined} - */ - unhandle() { - if (this.catcher) { - process.removeListener("uncaughtException", this.catcher); - this.catcher = false; - Array.from(this.handlers.values()).forEach((wrapper) => this.logger.unpipe(wrapper)); - } + var ansi = 30 + (Math.round(b2 / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); + if (value === 2) { + ansi += 60; } - /** - * TODO: add method description - * @param {Error} err - Error to get information about. - * @returns {mixed} - TODO: add return description. - */ - getAllInfo(err) { - let message = null; - if (err) { - message = typeof err === "string" ? err : err.message; + return ansi; + }; + convert.hsv.ansi16 = function(args) { + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + convert.rgb.ansi256 = function(args) { + var r = args[0]; + var g = args[1]; + var b2 = args[2]; + if (r === g && g === b2) { + if (r < 8) { + return 16; } - return { - error: err, - // TODO (indexzero): how do we configure this? - level: "error", - message: [ - `uncaughtException: ${message || "(no error message)"}`, - err && err.stack || " No stack trace" - ].join("\n"), - stack: err && err.stack, - exception: true, - date: (/* @__PURE__ */ new Date()).toString(), - process: this.getProcessInfo(), - os: this.getOsInfo(), - trace: this.getTrace(err) - }; - } - /** - * Gets all relevant process information for the currently running process. - * @returns {mixed} - TODO: add return description. - */ - getProcessInfo() { - return { - pid: process.pid, - uid: process.getuid ? process.getuid() : null, - gid: process.getgid ? process.getgid() : null, - cwd: process.cwd(), - execPath: process.execPath, - version: process.version, - argv: process.argv, - memoryUsage: process.memoryUsage() - }; - } - /** - * Gets all relevant OS information for the currently running process. - * @returns {mixed} - TODO: add return description. - */ - getOsInfo() { - return { - loadavg: os2.loadavg(), - uptime: os2.uptime() - }; - } - /** - * Gets a stack trace for the specified error. - * @param {mixed} err - TODO: add param description. - * @returns {mixed} - TODO: add return description. - */ - getTrace(err) { - const trace = err ? stackTrace.parse(err) : stackTrace.get(); - return trace.map((site) => { - return { - column: site.getColumnNumber(), - file: site.getFileName(), - function: site.getFunctionName(), - line: site.getLineNumber(), - method: site.getMethodName(), - native: site.isNative() - }; - }); - } - /** - * Helper method to add a transport as an exception handler. - * @param {Transport} handler - The transport to add as an exception handler. - * @returns {void} - */ - _addHandler(handler) { - if (!this.handlers.has(handler)) { - handler.handleExceptions = true; - const wrapper = new ExceptionStream(handler); - this.handlers.set(handler, wrapper); - this.logger.pipe(wrapper); + if (r > 248) { + return 231; } + return Math.round((r - 8) / 247 * 24) + 232; } - /** - * Logs all relevant information around the `err` and exits the current - * process. - * @param {Error} err - Error to handle - * @returns {mixed} - TODO: add return description. - * @private - */ - _uncaughtException(err) { - const info = this.getAllInfo(err); - const handlers = this._getExceptionHandlers(); - let doExit = typeof this.logger.exitOnError === "function" ? this.logger.exitOnError(err) : this.logger.exitOnError; - let timeout; - if (!handlers.length && doExit) { - console.warn("winston: exitOnError cannot be true with no exception handlers."); - console.warn("winston: not exiting process."); - doExit = false; - } - function gracefulExit() { - debug("doExit", doExit); - debug("process._exiting", process._exiting); - if (doExit && !process._exiting) { - if (timeout) { - clearTimeout(timeout); - } - process.exit(1); - } - } - if (!handlers || handlers.length === 0) { - return process.nextTick(gracefulExit); - } - asyncForEach(handlers, (handler, next) => { - const done = once(next); - const transport = handler.transport || handler; - function onDone(event) { - return () => { - debug(event); - done(); - }; - } - transport._ending = true; - transport.once("finish", onDone("finished")); - transport.once("error", onDone("error")); - }, () => doExit && gracefulExit()); - this.logger.log(info); - if (doExit) { - timeout = setTimeout(gracefulExit, 3e3); + var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b2 / 255 * 5); + return ansi; + }; + convert.ansi16.rgb = function(args) { + var color = args % 10; + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; } + color = color / 10.5 * 255; + return [color, color, color]; } - /** - * Returns the list of transports and exceptionHandlers for this instance. - * @returns {Array} - List of transports and exceptionHandlers for this - * instance. - * @private - */ - _getExceptionHandlers() { - return this.logger.transports.filter((wrap) => { - const transport = wrap.transport || wrap; - return transport.handleExceptions; - }); + var mult = (~~(args > 50) + 1) * 0.5; + var r = (color & 1) * mult * 255; + var g = (color >> 1 & 1) * mult * 255; + var b2 = (color >> 2 & 1) * mult * 255; + return [r, g, b2]; + }; + convert.ansi256.rgb = function(args) { + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; } + args -= 16; + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b2 = rem % 6 / 5 * 255; + return [r, g, b2]; }; - } -}); - -// node_modules/winston/lib/winston/rejection-stream.js -var require_rejection_stream = __commonJS({ - "node_modules/winston/lib/winston/rejection-stream.js"(exports2, module2) { - "use strict"; - var { Writable } = require_readable(); - module2.exports = class RejectionStream extends Writable { - /** - * Constructor function for the RejectionStream responsible for wrapping a - * TransportStream; only allowing writes of `info` objects with - * `info.rejection` set to true. - * @param {!TransportStream} transport - Stream to filter to rejections - */ - constructor(transport) { - super({ objectMode: true }); - if (!transport) { - throw new Error("RejectionStream requires a TransportStream instance."); - } - this.handleRejections = true; - this.transport = transport; + convert.rgb.hex = function(args) { + var integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255); + var string = integer.toString(16).toUpperCase(); + return "000000".substring(string.length) + string; + }; + convert.hex.rgb = function(args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; } - /** - * Writes the info object to our transport instance if (and only if) the - * `rejection` property is set on the info. - * @param {mixed} info - TODO: add param description. - * @param {mixed} enc - TODO: add param description. - * @param {mixed} callback - TODO: add param description. - * @returns {mixed} - TODO: add return description. - * @private - */ - _write(info, enc, callback) { - if (info.rejection) { - return this.transport.log(info, callback); - } - callback(); - return true; + var colorString = match[0]; + if (match[0].length === 3) { + colorString = colorString.split("").map(function(char) { + return char + char; + }).join(""); } + var integer = parseInt(colorString, 16); + var r = integer >> 16 & 255; + var g = integer >> 8 & 255; + var b2 = integer & 255; + return [r, g, b2]; }; - } -}); - -// node_modules/winston/lib/winston/rejection-handler.js -var require_rejection_handler = __commonJS({ - "node_modules/winston/lib/winston/rejection-handler.js"(exports2, module2) { - "use strict"; - var os2 = __require("os"); - var asyncForEach = require_forEach(); - var debug = require_node3()("winston:rejection"); - var once = require_one_time(); - var stackTrace = require_stack_trace(); - var RejectionStream = require_rejection_stream(); - module2.exports = class RejectionHandler { - /** - * TODO: add contructor description - * @param {!Logger} logger - TODO: add param description - */ - constructor(logger) { - if (!logger) { - throw new Error("Logger is required to handle rejections"); - } - this.logger = logger; - this.handlers = /* @__PURE__ */ new Map(); + convert.rgb.hcg = function(rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b2 = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b2); + var min = Math.min(Math.min(r, g), b2); + var chroma = max - min; + var grayscale; + var hue; + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; } - /** - * Handles `unhandledRejection` events for the current process by adding any - * handlers passed in. - * @returns {undefined} - */ - handle(...args) { - args.forEach((arg) => { - if (Array.isArray(arg)) { - return arg.forEach((handler) => this._addHandler(handler)); - } - this._addHandler(arg); - }); - if (!this.catcher) { - this.catcher = this._unhandledRejection.bind(this); - process.on("unhandledRejection", this.catcher); - } + if (chroma <= 0) { + hue = 0; + } else if (max === r) { + hue = (g - b2) / chroma % 6; + } else if (max === g) { + hue = 2 + (b2 - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; } - /** - * Removes any handlers to `unhandledRejection` events for the current - * process. This does not modify the state of the `this.handlers` set. - * @returns {undefined} - */ - unhandle() { - if (this.catcher) { - process.removeListener("unhandledRejection", this.catcher); - this.catcher = false; - Array.from(this.handlers.values()).forEach( - (wrapper) => this.logger.unpipe(wrapper) - ); - } + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; + }; + convert.hsl.hcg = function(hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + if (l < 0.5) { + c = 2 * s * l; + } else { + c = 2 * s * (1 - l); } - /** - * TODO: add method description - * @param {Error} err - Error to get information about. - * @returns {mixed} - TODO: add return description. - */ - getAllInfo(err) { - let message = null; - if (err) { - message = typeof err === "string" ? err : err.message; - } - return { - error: err, - // TODO (indexzero): how do we configure this? - level: "error", - message: [ - `unhandledRejection: ${message || "(no error message)"}`, - err && err.stack || " No stack trace" - ].join("\n"), - stack: err && err.stack, - rejection: true, - date: (/* @__PURE__ */ new Date()).toString(), - process: this.getProcessInfo(), - os: this.getOsInfo(), - trace: this.getTrace(err) - }; + if (c < 1) { + f = (l - 0.5 * c) / (1 - c); } - /** - * Gets all relevant process information for the currently running process. - * @returns {mixed} - TODO: add return description. - */ - getProcessInfo() { - return { - pid: process.pid, - uid: process.getuid ? process.getuid() : null, - gid: process.getgid ? process.getgid() : null, - cwd: process.cwd(), - execPath: process.execPath, - version: process.version, - argv: process.argv, - memoryUsage: process.memoryUsage() - }; + return [hsl[0], c * 100, f * 100]; + }; + convert.hsv.hcg = function(hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var c = s * v; + var f = 0; + if (c < 1) { + f = (v - c) / (1 - c); } - /** - * Gets all relevant OS information for the currently running process. - * @returns {mixed} - TODO: add return description. - */ - getOsInfo() { - return { - loadavg: os2.loadavg(), - uptime: os2.uptime() - }; + return [hsv[0], c * 100, f * 100]; + }; + convert.hcg.rgb = function(hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + if (c === 0) { + return [g * 255, g * 255, g * 255]; } - /** - * Gets a stack trace for the specified error. - * @param {mixed} err - TODO: add param description. - * @returns {mixed} - TODO: add return description. - */ - getTrace(err) { - const trace = err ? stackTrace.parse(err) : stackTrace.get(); - return trace.map((site) => { - return { - column: site.getColumnNumber(), - file: site.getFileName(), - function: site.getFunctionName(), - line: site.getLineNumber(), - method: site.getMethodName(), - native: site.isNative() - }; - }); + var pure = [0, 0, 0]; + var hi2 = h % 1 * 6; + var v = hi2 % 1; + var w2 = 1 - v; + var mg = 0; + switch (Math.floor(hi2)) { + case 0: + pure[0] = 1; + pure[1] = v; + pure[2] = 0; + break; + case 1: + pure[0] = w2; + pure[1] = 1; + pure[2] = 0; + break; + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v; + break; + case 3: + pure[0] = 0; + pure[1] = w2; + pure[2] = 1; + break; + case 4: + pure[0] = v; + pure[1] = 0; + pure[2] = 1; + break; + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w2; } - /** - * Helper method to add a transport as an exception handler. - * @param {Transport} handler - The transport to add as an exception handler. - * @returns {void} - */ - _addHandler(handler) { - if (!this.handlers.has(handler)) { - handler.handleRejections = true; - const wrapper = new RejectionStream(handler); - this.handlers.set(handler, wrapper); - this.logger.pipe(wrapper); - } + mg = (1 - c) * g; + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; + }; + convert.hcg.hsv = function(hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1 - c); + var f = 0; + if (v > 0) { + f = c / v; } - /** - * Logs all relevant information around the `err` and exits the current - * process. - * @param {Error} err - Error to handle - * @returns {mixed} - TODO: add return description. - * @private - */ - _unhandledRejection(err) { - const info = this.getAllInfo(err); - const handlers = this._getRejectionHandlers(); - let doExit = typeof this.logger.exitOnError === "function" ? this.logger.exitOnError(err) : this.logger.exitOnError; - let timeout; - if (!handlers.length && doExit) { - console.warn("winston: exitOnError cannot be true with no rejection handlers."); - console.warn("winston: not exiting process."); - doExit = false; - } - function gracefulExit() { - debug("doExit", doExit); - debug("process._exiting", process._exiting); - if (doExit && !process._exiting) { - if (timeout) { - clearTimeout(timeout); - } - process.exit(1); - } - } - if (!handlers || handlers.length === 0) { - return process.nextTick(gracefulExit); - } - asyncForEach( - handlers, - (handler, next) => { - const done = once(next); - const transport = handler.transport || handler; - function onDone(event) { - return () => { - debug(event); - done(); - }; - } - transport._ending = true; - transport.once("finish", onDone("finished")); - transport.once("error", onDone("error")); - }, - () => doExit && gracefulExit() - ); - this.logger.log(info); - if (doExit) { - timeout = setTimeout(gracefulExit, 3e3); - } + return [hcg[0], f * 100, v * 100]; + }; + convert.hcg.hsl = function(hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var l = g * (1 - c) + 0.5 * c; + var s = 0; + if (l > 0 && l < 0.5) { + s = c / (2 * l); + } else if (l >= 0.5 && l < 1) { + s = c / (2 * (1 - l)); } - /** - * Returns the list of transports and exceptionHandlers for this instance. - * @returns {Array} - List of transports and exceptionHandlers for this - * instance. - * @private - */ - _getRejectionHandlers() { - return this.logger.transports.filter((wrap) => { - const transport = wrap.transport || wrap; - return transport.handleRejections; - }); + return [hcg[0], s * 100, l * 100]; + }; + convert.hcg.hwb = function(hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + convert.hwb.hcg = function(hwb) { + var w2 = hwb[1] / 100; + var b2 = hwb[2] / 100; + var v = 1 - b2; + var c = v - w2; + var g = 0; + if (c < 1) { + g = (v - c) / (1 - c); } + return [hwb[0], c * 100, g * 100]; + }; + convert.apple.rgb = function(apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; + }; + convert.rgb.apple = function(rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; + }; + convert.gray.rgb = function(args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + convert.gray.hsl = convert.gray.hsv = function(args) { + return [0, 0, args[0]]; + }; + convert.gray.hwb = function(gray) { + return [0, 100, gray[0]]; + }; + convert.gray.cmyk = function(gray) { + return [0, 0, 0, gray[0]]; + }; + convert.gray.lab = function(gray) { + return [gray[0], 0, 0]; + }; + convert.gray.hex = function(gray) { + var val = Math.round(gray[0] / 100 * 255) & 255; + var integer = (val << 16) + (val << 8) + val; + var string = integer.toString(16).toUpperCase(); + return "000000".substring(string.length) + string; + }; + convert.rgb.gray = function(rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; }; } }); -// node_modules/winston/lib/winston/profiler.js -var require_profiler = __commonJS({ - "node_modules/winston/lib/winston/profiler.js"(exports2, module2) { - "use strict"; - var Profiler = class { - /** - * Constructor function for the Profiler instance used by - * `Logger.prototype.startTimer`. When done is called the timer will finish - * and log the duration. - * @param {!Logger} logger - TODO: add param description. - * @private - */ - constructor(logger) { - const Logger2 = require_logger(); - if (typeof logger !== "object" || Array.isArray(logger) || !(logger instanceof Logger2)) { - throw new Error("Logger is required for profiling"); - } else { - this.logger = logger; - this.start = Date.now(); +// node_modules/color/node_modules/color-convert/route.js +var require_route = __commonJS({ + "node_modules/color/node_modules/color-convert/route.js"(exports2, module2) { + var conversions = require_conversions(); + function buildGraph() { + var graph = {}; + var models = Object.keys(conversions); + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + return graph; + } + function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; + graph[fromModel].distance = 0; + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } } } - /** - * Ends the current timer (i.e. Profiler) instance and logs the `msg` along - * with the duration since creation. - * @returns {mixed} - TODO: add return description. - * @private - */ - done(...args) { - if (typeof args[args.length - 1] === "function") { - console.warn("Callback function no longer supported as of winston@3.0.0"); - args.pop(); + return graph; + } + function link(from5, to2) { + return function(args) { + return to2(from5(args)); + }; + } + function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn2 = conversions[graph[toModel].parent][toModel]; + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn2 = link(conversions[graph[cur].parent][cur], fn2); + cur = graph[cur].parent; + } + fn2.conversion = path; + return fn2; + } + module2.exports = function(fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + if (node.parent === null) { + continue; } - const info = typeof args[args.length - 1] === "object" ? args.pop() : {}; - info.level = info.level || "info"; - info.durationMs = Date.now() - this.start; - return this.logger.write(info); + conversion[toModel] = wrapConversion(toModel, graph); } + return conversion; }; - module2.exports = Profiler; } }); -// node_modules/winston/lib/winston/logger.js -var require_logger = __commonJS({ - "node_modules/winston/lib/winston/logger.js"(exports2, module2) { - "use strict"; - var { Stream, Transform } = require_readable(); - var asyncForEach = require_forEach(); - var { LEVEL, SPLAT } = require_triple_beam(); - var isStream2 = require_is_stream(); - var ExceptionHandler = require_exception_handler(); - var RejectionHandler = require_rejection_handler(); - var LegacyTransportStream = require_legacy(); - var Profiler = require_profiler(); - var { warn } = require_common2(); - var config3 = require_config2(); - var formatRegExp = /%[scdjifoO%]/g; - var Logger2 = class extends Transform { - /** - * Constructor function for the Logger object responsible for persisting log - * messages and metadata to one or more transports. - * @param {!Object} options - foo - */ - constructor(options) { - super({ objectMode: true }); - this.configure(options); - } - child(defaultRequestMetadata) { - const logger = this; - return Object.create(logger, { - write: { - value: function(info) { - const infoClone = Object.assign( - {}, - defaultRequestMetadata, - info - ); - if (info instanceof Error) { - infoClone.stack = info.stack; - infoClone.message = info.message; - } - logger.write(infoClone); - } - } - }); - } - /** - * This will wholesale reconfigure this instance by: - * 1. Resetting all transports. Older transports will be removed implicitly. - * 2. Set all other options including levels, colors, rewriters, filters, - * exceptionHandlers, etc. - * @param {!Object} options - TODO: add param description. - * @returns {undefined} - */ - configure({ - silent, - format, - defaultMeta, - levels, - level = "info", - exitOnError = true, - transports, - colors, - emitErrs, - formatters, - padLevels, - rewriters, - stripColors, - exceptionHandlers, - rejectionHandlers - } = {}) { - if (this.transports.length) { - this.clear(); - } - this.silent = silent; - this.format = format || this.format || require_json()(); - this.defaultMeta = defaultMeta || null; - this.levels = levels || this.levels || config3.npm.levels; - this.level = level; - if (this.exceptions) { - this.exceptions.unhandle(); - } - if (this.rejections) { - this.rejections.unhandle(); - } - this.exceptions = new ExceptionHandler(this); - this.rejections = new RejectionHandler(this); - this.profilers = {}; - this.exitOnError = exitOnError; - if (transports) { - transports = Array.isArray(transports) ? transports : [transports]; - transports.forEach((transport) => this.add(transport)); - } - if (colors || emitErrs || formatters || padLevels || rewriters || stripColors) { - throw new Error( - [ - "{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.", - "Use a custom winston.format(function) instead.", - "See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md" - ].join("\n") - ); - } - if (exceptionHandlers) { - this.exceptions.handle(exceptionHandlers); +// node_modules/color/node_modules/color-convert/index.js +var require_color_convert = __commonJS({ + "node_modules/color/node_modules/color-convert/index.js"(exports2, module2) { + var conversions = require_conversions(); + var route = require_route(); + var convert = {}; + var models = Object.keys(conversions); + function wrapRaw(fn2) { + var wrappedFn = function(args) { + if (args === void 0 || args === null) { + return args; } - if (rejectionHandlers) { - this.rejections.handle(rejectionHandlers); + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); } + return fn2(args); + }; + if ("conversion" in fn2) { + wrappedFn.conversion = fn2.conversion; } - isLevelEnabled(level) { - const givenLevelValue = getLevelValue(this.levels, level); - if (givenLevelValue === null) { - return false; - } - const configuredLevelValue = getLevelValue(this.levels, this.level); - if (configuredLevelValue === null) { - return false; + return wrappedFn; + } + function wrapRounded(fn2) { + var wrappedFn = function(args) { + if (args === void 0 || args === null) { + return args; } - if (!this.transports || this.transports.length === 0) { - return configuredLevelValue >= givenLevelValue; + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); } - const index2 = this.transports.findIndex((transport) => { - let transportLevelValue = getLevelValue(this.levels, transport.level); - if (transportLevelValue === null) { - transportLevelValue = configuredLevelValue; + var result = fn2(args); + if (typeof result === "object") { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); } - return transportLevelValue >= givenLevelValue; - }); - return index2 !== -1; + } + return result; + }; + if ("conversion" in fn2) { + wrappedFn.conversion = fn2.conversion; } - /* eslint-disable valid-jsdoc */ - /** - * Ensure backwards compatibility with a `log` method - * @param {mixed} level - Level the log message is written at. - * @param {mixed} msg - TODO: add param description. - * @param {mixed} meta - TODO: add param description. - * @returns {Logger} - TODO: add return description. - * - * @example - * // Supports the existing API: - * logger.log('info', 'Hello world', { custom: true }); - * logger.log('info', new Error('Yo, it\'s on fire')); - * - * // Requires winston.format.splat() - * logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true }); - * - * // And the new API with a single JSON literal: - * logger.log({ level: 'info', message: 'Hello world', custom: true }); - * logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') }); - * - * // Also requires winston.format.splat() - * logger.log({ - * level: 'info', - * message: '%s %d%%', - * [SPLAT]: ['A string', 50], - * meta: { thisIsMeta: true } - * }); - * - */ - /* eslint-enable valid-jsdoc */ - log(level, msg, ...splat) { - if (arguments.length === 1) { - level[LEVEL] = level.level; - this._addDefaultMeta(level); - this.write(level); - return this; + return wrappedFn; + } + models.forEach(function(fromModel) { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], "channels", { value: conversions[fromModel].channels }); + Object.defineProperty(convert[fromModel], "labels", { value: conversions[fromModel].labels }); + var routes = route(fromModel); + var routeModels = Object.keys(routes); + routeModels.forEach(function(toModel) { + var fn2 = routes[toModel]; + convert[fromModel][toModel] = wrapRounded(fn2); + convert[fromModel][toModel].raw = wrapRaw(fn2); + }); + }); + module2.exports = convert; + } +}); + +// node_modules/color/index.js +var require_color = __commonJS({ + "node_modules/color/index.js"(exports2, module2) { + "use strict"; + var colorString = require_color_string(); + var convert = require_color_convert(); + var _slice = [].slice; + var skippedModels = [ + // to be honest, I don't really feel like keyword belongs in color convert, but eh. + "keyword", + // gray conflicts with some method names, and has its own method defined. + "gray", + // shouldn't really be in color-convert either... + "hex" + ]; + var hashedModelKeys = {}; + Object.keys(convert).forEach(function(model) { + hashedModelKeys[_slice.call(convert[model].labels).sort().join("")] = model; + }); + var limiters = {}; + function Color(obj, model) { + if (!(this instanceof Color)) { + return new Color(obj, model); + } + if (model && model in skippedModels) { + model = null; + } + if (model && !(model in convert)) { + throw new Error("Unknown model: " + model); + } + var i; + var channels; + if (obj == null) { + this.model = "rgb"; + this.color = [0, 0, 0]; + this.valpha = 1; + } else if (obj instanceof Color) { + this.model = obj.model; + this.color = obj.color.slice(); + this.valpha = obj.valpha; + } else if (typeof obj === "string") { + var result = colorString.get(obj); + if (result === null) { + throw new Error("Unable to parse color from string: " + obj); + } + this.model = result.model; + channels = convert[this.model].channels; + this.color = result.value.slice(0, channels); + this.valpha = typeof result.value[channels] === "number" ? result.value[channels] : 1; + } else if (obj.length) { + this.model = model || "rgb"; + channels = convert[this.model].channels; + var newArr = _slice.call(obj, 0, channels); + this.color = zeroArray(newArr, channels); + this.valpha = typeof obj[channels] === "number" ? obj[channels] : 1; + } else if (typeof obj === "number") { + obj &= 16777215; + this.model = "rgb"; + this.color = [ + obj >> 16 & 255, + obj >> 8 & 255, + obj & 255 + ]; + this.valpha = 1; + } else { + this.valpha = 1; + var keys = Object.keys(obj); + if ("alpha" in obj) { + keys.splice(keys.indexOf("alpha"), 1); + this.valpha = typeof obj.alpha === "number" ? obj.alpha : 0; } - if (arguments.length === 2) { - if (msg && typeof msg === "object") { - msg[LEVEL] = msg.level = level; - this._addDefaultMeta(msg); - this.write(msg); - return this; - } - msg = { [LEVEL]: level, level, message: msg }; - this._addDefaultMeta(msg); - this.write(msg); - return this; + var hashedKeys = keys.sort().join(""); + if (!(hashedKeys in hashedModelKeys)) { + throw new Error("Unable to parse color from object: " + JSON.stringify(obj)); } - const [meta] = splat; - if (typeof meta === "object" && meta !== null) { - const tokens = msg && msg.match && msg.match(formatRegExp); - if (!tokens) { - const info = Object.assign({}, this.defaultMeta, meta, { - [LEVEL]: level, - [SPLAT]: splat, - level, - message: msg - }); - if (meta.message) info.message = `${info.message} ${meta.message}`; - if (meta.stack) info.stack = meta.stack; - if (meta.cause) info.cause = meta.cause; - this.write(info); - return this; - } + this.model = hashedModelKeys[hashedKeys]; + var labels = convert[this.model].labels; + var color = []; + for (i = 0; i < labels.length; i++) { + color.push(obj[labels[i]]); } - this.write(Object.assign({}, this.defaultMeta, { - [LEVEL]: level, - [SPLAT]: splat, - level, - message: msg - })); - return this; + this.color = zeroArray(color); } - /** - * Pushes data so that it can be picked up by all of our pipe targets. - * @param {mixed} info - TODO: add param description. - * @param {mixed} enc - TODO: add param description. - * @param {mixed} callback - Continues stream processing. - * @returns {undefined} - * @private - */ - _transform(info, enc, callback) { - if (this.silent) { - return callback(); + if (limiters[this.model]) { + channels = convert[this.model].channels; + for (i = 0; i < channels; i++) { + var limit = limiters[this.model][i]; + if (limit) { + this.color[i] = limit(this.color[i]); + } } - if (!info[LEVEL]) { - info[LEVEL] = info.level; + } + this.valpha = Math.max(0, Math.min(1, this.valpha)); + if (Object.freeze) { + Object.freeze(this); + } + } + Color.prototype = { + toString: function() { + return this.string(); + }, + toJSON: function() { + return this[this.model](); + }, + string: function(places) { + var self2 = this.model in colorString.to ? this : this.rgb(); + self2 = self2.round(typeof places === "number" ? places : 1); + var args = self2.valpha === 1 ? self2.color : self2.color.concat(this.valpha); + return colorString.to[self2.model](args); + }, + percentString: function(places) { + var self2 = this.rgb().round(typeof places === "number" ? places : 1); + var args = self2.valpha === 1 ? self2.color : self2.color.concat(this.valpha); + return colorString.to.rgb.percent(args); + }, + array: function() { + return this.valpha === 1 ? this.color.slice() : this.color.concat(this.valpha); + }, + object: function() { + var result = {}; + var channels = convert[this.model].channels; + var labels = convert[this.model].labels; + for (var i = 0; i < channels; i++) { + result[labels[i]] = this.color[i]; } - if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) { - console.error("[winston] Unknown logger level: %s", info[LEVEL]); + if (this.valpha !== 1) { + result.alpha = this.valpha; } - if (!this._readableState.pipes) { - console.error( - "[winston] Attempt to write logs with no transports, which can increase memory usage: %j", - info - ); + return result; + }, + unitArray: function() { + var rgb = this.rgb().color; + rgb[0] /= 255; + rgb[1] /= 255; + rgb[2] /= 255; + if (this.valpha !== 1) { + rgb.push(this.valpha); } - try { - this.push(this.format.transform(info, this.format.options)); - } finally { - this._writableState.sync = false; - callback(); + return rgb; + }, + unitObject: function() { + var rgb = this.rgb().object(); + rgb.r /= 255; + rgb.g /= 255; + rgb.b /= 255; + if (this.valpha !== 1) { + rgb.alpha = this.valpha; } - } - /** - * Delays the 'finish' event until all transport pipe targets have - * also emitted 'finish' or are already finished. - * @param {mixed} callback - Continues stream processing. - */ - _final(callback) { - const transports = this.transports.slice(); - asyncForEach( - transports, - (transport, next) => { - if (!transport || transport.finished) return setImmediate(next); - transport.once("finish", next); - transport.end(); - }, - callback - ); - } - /** - * Adds the transport to this logger instance by piping to it. - * @param {mixed} transport - TODO: add param description. - * @returns {Logger} - TODO: add return description. - */ - add(transport) { - const target = !isStream2(transport) || transport.log.length > 2 ? new LegacyTransportStream({ transport }) : transport; - if (!target._writableState || !target._writableState.objectMode) { - throw new Error( - "Transports must WritableStreams in objectMode. Set { objectMode: true }." - ); + return rgb; + }, + round: function(places) { + places = Math.max(places || 0, 0); + return new Color(this.color.map(roundToPlace(places)).concat(this.valpha), this.model); + }, + alpha: function(val) { + if (arguments.length) { + return new Color(this.color.concat(Math.max(0, Math.min(1, val))), this.model); } - this._onEvent("error", target); - this._onEvent("warn", target); - this.pipe(target); - if (transport.handleExceptions) { - this.exceptions.handle(); + return this.valpha; + }, + // rgb + red: getset("rgb", 0, maxfn(255)), + green: getset("rgb", 1, maxfn(255)), + blue: getset("rgb", 2, maxfn(255)), + hue: getset(["hsl", "hsv", "hsl", "hwb", "hcg"], 0, function(val) { + return (val % 360 + 360) % 360; + }), + // eslint-disable-line brace-style + saturationl: getset("hsl", 1, maxfn(100)), + lightness: getset("hsl", 2, maxfn(100)), + saturationv: getset("hsv", 1, maxfn(100)), + value: getset("hsv", 2, maxfn(100)), + chroma: getset("hcg", 1, maxfn(100)), + gray: getset("hcg", 2, maxfn(100)), + white: getset("hwb", 1, maxfn(100)), + wblack: getset("hwb", 2, maxfn(100)), + cyan: getset("cmyk", 0, maxfn(100)), + magenta: getset("cmyk", 1, maxfn(100)), + yellow: getset("cmyk", 2, maxfn(100)), + black: getset("cmyk", 3, maxfn(100)), + x: getset("xyz", 0, maxfn(100)), + y: getset("xyz", 1, maxfn(100)), + z: getset("xyz", 2, maxfn(100)), + l: getset("lab", 0, maxfn(100)), + a: getset("lab", 1), + b: getset("lab", 2), + keyword: function(val) { + if (arguments.length) { + return new Color(val); } - if (transport.handleRejections) { - this.rejections.handle(); + return convert[this.model].keyword(this.color); + }, + hex: function(val) { + if (arguments.length) { + return new Color(val); } - return this; - } - /** - * Removes the transport from this logger instance by unpiping from it. - * @param {mixed} transport - TODO: add param description. - * @returns {Logger} - TODO: add return description. - */ - remove(transport) { - if (!transport) return this; - let target = transport; - if (!isStream2(transport) || transport.log.length > 2) { - target = this.transports.filter( - (match) => match.transport === transport - )[0]; + return colorString.to.hex(this.rgb().round().color); + }, + rgbNumber: function() { + var rgb = this.rgb().color; + return (rgb[0] & 255) << 16 | (rgb[1] & 255) << 8 | rgb[2] & 255; + }, + luminosity: function() { + var rgb = this.rgb().color; + var lum = []; + for (var i = 0; i < rgb.length; i++) { + var chan = rgb[i] / 255; + lum[i] = chan <= 0.03928 ? chan / 12.92 : Math.pow((chan + 0.055) / 1.055, 2.4); } - if (target) { - this.unpipe(target); + return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; + }, + contrast: function(color2) { + var lum1 = this.luminosity(); + var lum2 = color2.luminosity(); + if (lum1 > lum2) { + return (lum1 + 0.05) / (lum2 + 0.05); } - return this; - } - /** - * Removes all transports from this logger instance. - * @returns {Logger} - TODO: add return description. - */ - clear() { - this.unpipe(); - return this; - } - /** - * Cleans up resources (streams, event listeners) for all transports - * associated with this instance (if necessary). - * @returns {Logger} - TODO: add return description. - */ - close() { - this.exceptions.unhandle(); - this.rejections.unhandle(); - this.clear(); - this.emit("close"); - return this; - } - /** - * Sets the `target` levels specified on this instance. - * @param {Object} Target levels to use on this instance. - */ - setLevels() { - warn.deprecated("setLevels"); - } - /** - * Queries the all transports for this instance with the specified `options`. - * This will aggregate each transport's results into one object containing - * a property per transport. - * @param {Object} options - Query options for this instance. - * @param {function} callback - Continuation to respond to when complete. - */ - query(options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; + return (lum2 + 0.05) / (lum1 + 0.05); + }, + level: function(color2) { + var contrastRatio = this.contrast(color2); + if (contrastRatio >= 7.1) { + return "AAA"; } - options = options || {}; - const results = {}; - const queryObject = Object.assign({}, options.query || {}); - function queryTransport(transport, next) { - if (options.query && typeof transport.formatQuery === "function") { - options.query = transport.formatQuery(queryObject); - } - transport.query(options, (err, res) => { - if (err) { - return next(err); - } - if (typeof transport.formatResults === "function") { - res = transport.formatResults(res, options.format); - } - next(null, res); - }); + return contrastRatio >= 4.5 ? "AA" : ""; + }, + isDark: function() { + var rgb = this.rgb().color; + var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1e3; + return yiq < 128; + }, + isLight: function() { + return !this.isDark(); + }, + negate: function() { + var rgb = this.rgb(); + for (var i = 0; i < 3; i++) { + rgb.color[i] = 255 - rgb.color[i]; } - function addResults(transport, next) { - queryTransport(transport, (err, result) => { - if (next) { - result = err || result; - if (result) { - results[transport.name] = result; - } - next(); - } - next = null; - }); + return rgb; + }, + lighten: function(ratio) { + var hsl = this.hsl(); + hsl.color[2] += hsl.color[2] * ratio; + return hsl; + }, + darken: function(ratio) { + var hsl = this.hsl(); + hsl.color[2] -= hsl.color[2] * ratio; + return hsl; + }, + saturate: function(ratio) { + var hsl = this.hsl(); + hsl.color[1] += hsl.color[1] * ratio; + return hsl; + }, + desaturate: function(ratio) { + var hsl = this.hsl(); + hsl.color[1] -= hsl.color[1] * ratio; + return hsl; + }, + whiten: function(ratio) { + var hwb = this.hwb(); + hwb.color[1] += hwb.color[1] * ratio; + return hwb; + }, + blacken: function(ratio) { + var hwb = this.hwb(); + hwb.color[2] += hwb.color[2] * ratio; + return hwb; + }, + grayscale: function() { + var rgb = this.rgb().color; + var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; + return Color.rgb(val, val, val); + }, + fade: function(ratio) { + return this.alpha(this.valpha - this.valpha * ratio); + }, + opaquer: function(ratio) { + return this.alpha(this.valpha + this.valpha * ratio); + }, + rotate: function(degrees) { + var hsl = this.hsl(); + var hue = hsl.color[0]; + hue = (hue + degrees) % 360; + hue = hue < 0 ? 360 + hue : hue; + hsl.color[0] = hue; + return hsl; + }, + mix: function(mixinColor, weight) { + if (!mixinColor || !mixinColor.rgb) { + throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor); } - asyncForEach( - this.transports.filter((transport) => !!transport.query), - addResults, - () => callback(null, results) + var color1 = mixinColor.rgb(); + var color2 = this.rgb(); + var p = weight === void 0 ? 0.5 : weight; + var w2 = 2 * p - 1; + var a = color1.alpha() - color2.alpha(); + var w1 = ((w2 * a === -1 ? w2 : (w2 + a) / (1 + w2 * a)) + 1) / 2; + var w22 = 1 - w1; + return Color.rgb( + w1 * color1.red() + w22 * color2.red(), + w1 * color1.green() + w22 * color2.green(), + w1 * color1.blue() + w22 * color2.blue(), + color1.alpha() * p + color2.alpha() * (1 - p) ); } - /** - * Returns a log stream for all transports. Options object is optional. - * @param{Object} options={} - Stream options for this instance. - * @returns {Stream} - TODO: add return description. - */ - stream(options = {}) { - const out = new Stream(); - const streams = []; - out._streams = streams; - out.destroy = () => { - let i = streams.length; - while (i--) { - streams[i].destroy(); - } - }; - this.transports.filter((transport) => !!transport.stream).forEach((transport) => { - const str = transport.stream(options); - if (!str) { - return; - } - streams.push(str); - str.on("log", (log) => { - log.transport = log.transport || []; - log.transport.push(transport.name); - out.emit("log", log); - }); - str.on("error", (err) => { - err.transport = err.transport || []; - err.transport.push(transport.name); - out.emit("error", err); - }); - }); - return out; - } - /** - * Returns an object corresponding to a specific timing. When done is called - * the timer will finish and log the duration. e.g.: - * @returns {Profile} - TODO: add return description. - * @example - * const timer = winston.startTimer() - * setTimeout(() => { - * timer.done({ - * message: 'Logging message' - * }); - * }, 1000); - */ - startTimer() { - return new Profiler(this); + }; + Object.keys(convert).forEach(function(model) { + if (skippedModels.indexOf(model) !== -1) { + return; } - /** - * Tracks the time inbetween subsequent calls to this method with the same - * `id` parameter. The second call to this method will log the difference in - * milliseconds along with the message. - * @param {string} id Unique id of the profiler - * @returns {Logger} - TODO: add return description. - */ - profile(id2, ...args) { - const time = Date.now(); - if (this.profilers[id2]) { - const timeEnd = this.profilers[id2]; - delete this.profilers[id2]; - if (typeof args[args.length - 2] === "function") { - console.warn( - "Callback function no longer supported as of winston@3.0.0" - ); - args.pop(); + var channels = convert[model].channels; + Color.prototype[model] = function() { + if (this.model === model) { + return new Color(this); + } + if (arguments.length) { + return new Color(arguments, model); + } + var newAlpha = typeof arguments[channels] === "number" ? channels : this.valpha; + return new Color(assertArray(convert[this.model][model].raw(this.color)).concat(newAlpha), model); + }; + Color[model] = function(color) { + if (typeof color === "number") { + color = zeroArray(_slice.call(arguments), channels); + } + return new Color(color, model); + }; + }); + function roundTo(num2, places) { + return Number(num2.toFixed(places)); + } + function roundToPlace(places) { + return function(num2) { + return roundTo(num2, places); + }; + } + function getset(model, channel, modifier) { + model = Array.isArray(model) ? model : [model]; + model.forEach(function(m2) { + (limiters[m2] || (limiters[m2] = []))[channel] = modifier; + }); + model = model[0]; + return function(val) { + var result; + if (arguments.length) { + if (modifier) { + val = modifier(val); } - const info = typeof args[args.length - 1] === "object" ? args.pop() : {}; - info.level = info.level || "info"; - info.durationMs = time - timeEnd; - info.message = info.message || id2; - return this.write(info); + result = this[model](); + result.color[channel] = val; + return result; + } + result = this[model]().color[channel]; + if (modifier) { + result = modifier(result); + } + return result; + }; + } + function maxfn(max) { + return function(v) { + return Math.max(0, Math.min(max, v)); + }; + } + function assertArray(val) { + return Array.isArray(val) ? val : [val]; + } + function zeroArray(arr, length) { + for (var i = 0; i < length; i++) { + if (typeof arr[i] !== "number") { + arr[i] = 0; } - this.profilers[id2] = time; - return this; - } - /** - * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. - * @returns {undefined} - * @deprecated - */ - handleExceptions(...args) { - console.warn( - "Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()" - ); - this.exceptions.handle(...args); } - /** - * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. - * @returns {undefined} - * @deprecated - */ - unhandleExceptions(...args) { - console.warn( - "Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()" - ); - this.exceptions.unhandle(...args); + return arr; + } + module2.exports = Color; + } +}); + +// node_modules/text-hex/index.js +var require_text_hex = __commonJS({ + "node_modules/text-hex/index.js"(exports2, module2) { + "use strict"; + module2.exports = function hex(str) { + for (var i = 0, hash2 = 0; i < str.length; hash2 = str.charCodeAt(i++) + ((hash2 << 5) - hash2)) ; + var color = Math.floor( + Math.abs( + Math.sin(hash2) * 1e4 % 1 * 16777216 + ) + ).toString(16); + return "#" + Array(6 - color.length + 1).join("0") + color; + }; + } +}); + +// node_modules/colorspace/index.js +var require_colorspace = __commonJS({ + "node_modules/colorspace/index.js"(exports2, module2) { + "use strict"; + var color = require_color(); + var hex = require_text_hex(); + module2.exports = function colorspace(namespace, delimiter) { + var split3 = namespace.split(delimiter || ":"); + var base = hex(split3[0]); + if (!split3.length) return base; + for (var i = 0, l = split3.length - 1; i < l; i++) { + base = color(base).mix(color(hex(split3[i + 1]))).saturate(1).hex(); } - /** - * Throw a more meaningful deprecation notice - * @throws {Error} - TODO: add throws description. - */ - cli() { - throw new Error( - [ - "Logger.cli() was removed in winston@3.0.0", - "Use a custom winston.formats.cli() instead.", - "See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md" - ].join("\n") - ); + return base; + }; + } +}); + +// node_modules/kuler/index.js +var require_kuler = __commonJS({ + "node_modules/kuler/index.js"(exports2, module2) { + "use strict"; + function Kuler(text, color) { + if (color) return new Kuler(text).style(color); + if (!(this instanceof Kuler)) return new Kuler(text); + this.text = text; + } + Kuler.prototype.prefix = "\x1B["; + Kuler.prototype.suffix = "m"; + Kuler.prototype.hex = function hex(color) { + color = color[0] === "#" ? color.substring(1) : color; + if (color.length === 3) { + color = color.split(""); + color[5] = color[2]; + color[4] = color[2]; + color[3] = color[1]; + color[2] = color[1]; + color[1] = color[0]; + color = color.join(""); } - /** - * Bubbles the `event` that occured on the specified `transport` up - * from this instance. - * @param {string} event - The event that occured - * @param {Object} transport - Transport on which the event occured - * @private - */ - _onEvent(event, transport) { - function transportEvent(err) { - if (event === "error" && !this.transports.includes(transport)) { - this.add(transport); + var r = color.substring(0, 2), g = color.substring(2, 4), b2 = color.substring(4, 6); + return [parseInt(r, 16), parseInt(g, 16), parseInt(b2, 16)]; + }; + Kuler.prototype.rgb = function rgb(r, g, b2) { + var red = r / 255 * 5, green = g / 255 * 5, blue = b2 / 255 * 5; + return this.ansi(red, green, blue); + }; + Kuler.prototype.ansi = function ansi(r, g, b2) { + var red = Math.round(r), green = Math.round(g), blue = Math.round(b2); + return 16 + red * 36 + green * 6 + blue; + }; + Kuler.prototype.reset = function reset() { + return this.prefix + "39;49" + this.suffix; + }; + Kuler.prototype.style = function style(color) { + return this.prefix + "38;5;" + this.rgb.apply(this, this.hex(color)) + this.suffix + this.text + this.reset(); + }; + module2.exports = Kuler; + } +}); + +// node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js +var require_namespace_ansi = __commonJS({ + "node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js"(exports2, module2) { + var colorspace = require_colorspace(); + var kuler = require_kuler(); + module2.exports = function ansiModifier(args, options) { + var namespace = options.namespace; + var ansi = options.colors !== false ? kuler(namespace + ":", colorspace(namespace)) : namespace + ":"; + args[0] = ansi + " " + args[0]; + return args; + }; + } +}); + +// node_modules/enabled/index.js +var require_enabled = __commonJS({ + "node_modules/enabled/index.js"(exports2, module2) { + "use strict"; + module2.exports = function enabled(name, variable) { + if (!variable) return false; + var variables = variable.split(/[\s,]+/), i = 0; + for (; i < variables.length; i++) { + variable = variables[i].replace("*", ".*?"); + if ("-" === variable.charAt(0)) { + if (new RegExp("^" + variable.substr(1) + "$").test(name)) { + return false; } - this.emit(event, err, transport); + continue; } - if (!transport["__winston" + event]) { - transport["__winston" + event] = transportEvent.bind(this); - transport.on(event, transport["__winston" + event]); + if (new RegExp("^" + variable + "$").test(name)) { + return true; } } - _addDefaultMeta(msg) { - if (this.defaultMeta) { - Object.assign(msg, this.defaultMeta); + return false; + }; + } +}); + +// node_modules/@dabh/diagnostics/adapters/index.js +var require_adapters = __commonJS({ + "node_modules/@dabh/diagnostics/adapters/index.js"(exports2, module2) { + var enabled = require_enabled(); + module2.exports = function create(fn2) { + return function adapter(namespace) { + try { + return enabled(namespace, fn2()); + } catch (e) { } - } + return false; + }; }; - function getLevelValue(levels, level) { - const value = levels[level]; - if (!value && value !== 0) { - return null; + } +}); + +// node_modules/@dabh/diagnostics/adapters/process.env.js +var require_process_env = __commonJS({ + "node_modules/@dabh/diagnostics/adapters/process.env.js"(exports2, module2) { + var adapter = require_adapters(); + module2.exports = adapter(function processenv() { + return process.env.DEBUG || process.env.DIAGNOSTICS; + }); + } +}); + +// node_modules/@dabh/diagnostics/logger/console.js +var require_console2 = __commonJS({ + "node_modules/@dabh/diagnostics/logger/console.js"(exports2, module2) { + module2.exports = function(meta, messages) { + try { + Function.prototype.apply.call(console.log, console, messages); + } catch (e) { } - return value; - } - Object.defineProperty(Logger2.prototype, "transports", { - configurable: false, - enumerable: true, - get() { - const { pipes } = this._readableState; - return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes; + }; + } +}); + +// node_modules/@dabh/diagnostics/node/development.js +var require_development = __commonJS({ + "node_modules/@dabh/diagnostics/node/development.js"(exports2, module2) { + var create = require_diagnostics(); + var tty = __require("tty").isatty(1); + var diagnostics = create(function dev(namespace, options) { + options = options || {}; + options.colors = "colors" in options ? options.colors : tty; + options.namespace = namespace; + options.prod = false; + options.dev = true; + if (!dev.enabled(namespace) && !(options.force || dev.force)) { + return dev.nope(options); } + return dev.yep(options); }); - module2.exports = Logger2; + diagnostics.modify(require_namespace_ansi()); + diagnostics.use(require_process_env()); + diagnostics.set(require_console2()); + module2.exports = diagnostics; } }); -// node_modules/winston/lib/winston/create-logger.js -var require_create_logger = __commonJS({ - "node_modules/winston/lib/winston/create-logger.js"(exports2, module2) { +// node_modules/@dabh/diagnostics/node/index.js +var require_node2 = __commonJS({ + "node_modules/@dabh/diagnostics/node/index.js"(exports2, module2) { + if (process.env.NODE_ENV === "production") { + module2.exports = require_production(); + } else { + module2.exports = require_development(); + } + } +}); + +// node_modules/winston/lib/winston/tail-file.js +var require_tail_file = __commonJS({ + "node_modules/winston/lib/winston/tail-file.js"(exports2, module2) { "use strict"; - var { LEVEL } = require_triple_beam(); - var config3 = require_config2(); - var Logger2 = require_logger(); - var debug = require_node3()("winston:create-logger"); - function isLevelEnabledFunctionName(level) { - return "is" + level.charAt(0).toUpperCase() + level.slice(1) + "Enabled"; + var fs2 = __require("fs"); + var { StringDecoder } = __require("string_decoder"); + var { Stream } = require_readable(); + function noop2() { } - module2.exports = function(opts = {}) { - opts.levels = opts.levels || config3.npm.levels; - class DerivedLogger extends Logger2 { - /** - * Create a new class derived logger for which the levels can be attached to - * the prototype of. This is a V8 optimization that is well know to increase - * performance of prototype functions. - * @param {!Object} options - Options for the created logger. - */ - constructor(options) { - super(options); - } + module2.exports = (options, iter) => { + const buffer2 = Buffer.alloc(64 * 1024); + const decode2 = new StringDecoder("utf8"); + const stream4 = new Stream(); + let buff = ""; + let pos = 0; + let row = 0; + if (options.start === -1) { + delete options.start; } - const logger = new DerivedLogger(opts); - Object.keys(opts.levels).forEach(function(level) { - debug('Define prototype method for "%s"', level); - if (level === "log") { - console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.'); + stream4.readable = true; + stream4.destroy = () => { + stream4.destroyed = true; + stream4.emit("end"); + stream4.emit("close"); + }; + fs2.open(options.file, "a+", "0644", (err, fd2) => { + if (err) { + if (!iter) { + stream4.emit("error", err); + } else { + iter(err); + } + stream4.destroy(); return; } - DerivedLogger.prototype[level] = function(...args) { - const self2 = this || logger; - if (args.length === 1) { - const [msg] = args; - const info = msg && msg.message && msg || { message: msg }; - info.level = info[LEVEL] = level; - self2._addDefaultMeta(info); - self2.write(info); - return this || logger; - } - if (args.length === 0) { - self2.log(level, ""); - return self2; + (function read() { + if (stream4.destroyed) { + fs2.close(fd2, noop2); + return; } - return self2.log(level, ...args); - }; - DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function() { - return (this || logger).isLevelEnabled(level); - }; + return fs2.read(fd2, buffer2, 0, buffer2.length, pos, (error, bytes) => { + if (error) { + if (!iter) { + stream4.emit("error", error); + } else { + iter(error); + } + stream4.destroy(); + return; + } + if (!bytes) { + if (buff) { + if (options.start == null || row > options.start) { + if (!iter) { + stream4.emit("line", buff); + } else { + iter(null, buff); + } + } + row++; + buff = ""; + } + return setTimeout(read, 1e3); + } + let data = decode2.write(buffer2.slice(0, bytes)); + if (!iter) { + stream4.emit("data", data); + } + data = (buff + data).split(/\n+/); + const l = data.length - 1; + let i = 0; + for (; i < l; i++) { + if (options.start == null || row > options.start) { + if (!iter) { + stream4.emit("line", data[i]); + } else { + iter(null, data[i]); + } + } + row++; + } + buff = data[l]; + pos += bytes; + return read(); + }); + })(); }); - return logger; + if (!iter) { + return stream4; + } + return stream4.destroy; }; } }); -// node_modules/winston/lib/winston/container.js -var require_container = __commonJS({ - "node_modules/winston/lib/winston/container.js"(exports2, module2) { +// node_modules/winston/lib/winston/transports/file.js +var require_file = __commonJS({ + "node_modules/winston/lib/winston/transports/file.js"(exports2, module2) { "use strict"; - var createLogger = require_create_logger(); - module2.exports = class Container { + var fs2 = __require("fs"); + var path = __require("path"); + var asyncSeries = require_series(); + var zlib2 = __require("zlib"); + var { MESSAGE } = require_triple_beam(); + var { Stream, PassThrough } = require_readable(); + var TransportStream = require_winston_transport(); + var debug = require_node2()("winston:file"); + var os2 = __require("os"); + var tailFile = require_tail_file(); + module2.exports = class File extends TransportStream { /** - * Constructor function for the Container object responsible for managing a - * set of `winston.Logger` instances based on string ids. - * @param {!Object} [options={}] - Default pass-thru options for Loggers. + * Constructor function for the File transport object responsible for + * persisting log messages and metadata to one or more files. + * @param {Object} options - Options for this instance. */ constructor(options = {}) { - this.loggers = /* @__PURE__ */ new Map(); - this.options = options; - } - /** - * Retrieves a `winston.Logger` instance for the specified `id`. If an - * instance does not exist, one is created. - * @param {!string} id - The id of the Logger to get. - * @param {?Object} [options] - Options for the Logger instance. - * @returns {Logger} - A configured Logger instance with a specified id. - */ - add(id2, options) { - if (!this.loggers.has(id2)) { - options = Object.assign({}, options || this.options); - const existing = options.transports || this.options.transports; - if (existing) { - options.transports = Array.isArray(existing) ? existing.slice() : [existing]; - } else { - options.transports = []; - } - const logger = createLogger(options); - logger.on("close", () => this._delete(id2)); - this.loggers.set(id2, logger); + super(options); + this.name = options.name || "file"; + function throwIf(target, ...args) { + args.slice(1).forEach((name) => { + if (options[name]) { + throw new Error(`Cannot set ${name} and ${target} together`); + } + }); } - return this.loggers.get(id2); - } - /** - * Retreives a `winston.Logger` instance for the specified `id`. If - * an instance does not exist, one is created. - * @param {!string} id - The id of the Logger to get. - * @param {?Object} [options] - Options for the Logger instance. - * @returns {Logger} - A configured Logger instance with a specified id. - */ - get(id2, options) { - return this.add(id2, options); - } - /** - * Check if the container has a logger with the id. - * @param {?string} id - The id of the Logger instance to find. - * @returns {boolean} - Boolean value indicating if this instance has a - * logger with the specified `id`. - */ - has(id2) { - return !!this.loggers.has(id2); + this._stream = new PassThrough(); + this._stream.setMaxListeners(30); + this._onError = this._onError.bind(this); + if (options.filename || options.dirname) { + throwIf("filename or dirname", "stream"); + this._basename = this.filename = options.filename ? path.basename(options.filename) : "winston.log"; + this.dirname = options.dirname || path.dirname(options.filename); + this.options = options.options || { flags: "a" }; + } else if (options.stream) { + console.warn("options.stream will be removed in winston@4. Use winston.transports.Stream"); + throwIf("stream", "filename", "maxsize"); + this._dest = this._stream.pipe(this._setupStream(options.stream)); + this.dirname = path.dirname(this._dest.path); + } else { + throw new Error("Cannot log to file without filename or stream."); + } + this.maxsize = options.maxsize || null; + this.rotationFormat = options.rotationFormat || false; + this.zippedArchive = options.zippedArchive || false; + this.maxFiles = options.maxFiles || null; + this.eol = typeof options.eol === "string" ? options.eol : os2.EOL; + this.tailable = options.tailable || false; + this.lazy = options.lazy || false; + this._size = 0; + this._pendingSize = 0; + this._created = 0; + this._drain = false; + this._opening = false; + this._ending = false; + this._fileExist = false; + if (this.dirname) this._createLogDirIfNotExist(this.dirname); + if (!this.lazy) this.open(); } - /** - * Closes a `Logger` instance with the specified `id` if it exists. - * If no `id` is supplied then all Loggers are closed. - * @param {?string} id - The id of the Logger instance to close. - * @returns {undefined} - */ - close(id2) { - if (id2) { - return this._removeLogger(id2); + finishIfEnding() { + if (this._ending) { + if (this._opening) { + this.once("open", () => { + this._stream.once("finish", () => this.emit("finish")); + setImmediate(() => this._stream.end()); + }); + } else { + this._stream.once("finish", () => this.emit("finish")); + setImmediate(() => this._stream.end()); + } } - this.loggers.forEach((val, key) => this._removeLogger(key)); } /** - * Remove a logger based on the id. - * @param {!string} id - The id of the logger to remove. + * Core logging method exposed to Winston. Metadata is optional. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. * @returns {undefined} - * @private */ - _removeLogger(id2) { - if (!this.loggers.has(id2)) { + log(info, callback = () => { + }) { + if (this.silent) { + callback(); + return true; + } + if (this._drain) { + this._stream.once("drain", () => { + this._drain = false; + this.log(info, callback); + }); return; } - const logger = this.loggers.get(id2); - logger.close(); - this._delete(id2); - } - /** - * Deletes a `Logger` instance with the specified `id`. - * @param {!string} id - The id of the Logger instance to delete from - * container. - * @returns {undefined} - * @private - */ - _delete(id2) { - this.loggers.delete(id2); - } - }; - } -}); - -// node_modules/winston/lib/winston.js -var require_winston = __commonJS({ - "node_modules/winston/lib/winston.js"(exports2) { - "use strict"; - var logform = require_logform(); - var { warn } = require_common2(); - exports2.version = require_package2().version; - exports2.transports = require_transports(); - exports2.config = require_config2(); - exports2.addColors = logform.levels; - exports2.format = logform.format; - exports2.createLogger = require_create_logger(); - exports2.Logger = require_logger(); - exports2.ExceptionHandler = require_exception_handler(); - exports2.RejectionHandler = require_rejection_handler(); - exports2.Container = require_container(); - exports2.Transport = require_winston_transport(); - exports2.loggers = new exports2.Container(); - var defaultLogger = exports2.createLogger(); - Object.keys(exports2.config.npm.levels).concat([ - "log", - "query", - "stream", - "add", - "remove", - "clear", - "profile", - "startTimer", - "handleExceptions", - "unhandleExceptions", - "handleRejections", - "unhandleRejections", - "configure", - "child" - ]).forEach( - (method) => exports2[method] = (...args) => defaultLogger[method](...args) - ); - Object.defineProperty(exports2, "level", { - get() { - return defaultLogger.level; - }, - set(val) { - defaultLogger.level = val; - } - }); - Object.defineProperty(exports2, "exceptions", { - get() { - return defaultLogger.exceptions; - } - }); - Object.defineProperty(exports2, "rejections", { - get() { - return defaultLogger.rejections; - } - }); - ["exitOnError"].forEach((prop) => { - Object.defineProperty(exports2, prop, { - get() { - return defaultLogger[prop]; - }, - set(val) { - defaultLogger[prop] = val; + if (this._rotate) { + this._stream.once("rotate", () => { + this._rotate = false; + this.log(info, callback); + }); + return; } - }); - }); - Object.defineProperty(exports2, "default", { - get() { - return { - exceptionHandlers: defaultLogger.exceptionHandlers, - rejectionHandlers: defaultLogger.rejectionHandlers, - transports: defaultLogger.transports - }; - } - }); - warn.deprecated(exports2, "setLevels"); - warn.forFunctions(exports2, "useFormat", ["cli"]); - warn.forProperties(exports2, "useFormat", ["padLevels", "stripColors"]); - warn.forFunctions(exports2, "deprecated", [ - "addRewriter", - "addFilter", - "clone", - "extend" - ]); - warn.forProperties(exports2, "deprecated", ["emitErrs", "levelLength"]); - } -}); - -// node_modules/object-hash/index.js -var require_object_hash = __commonJS({ - "node_modules/object-hash/index.js"(exports2, module2) { - "use strict"; - var crypto4 = __require("crypto"); - exports2 = module2.exports = objectHash; - function objectHash(object, options) { - options = applyDefaults(object, options); - return hash2(object, options); - } - exports2.sha1 = function(object) { - return objectHash(object); - }; - exports2.keys = function(object) { - return objectHash(object, { excludeValues: true, algorithm: "sha1", encoding: "hex" }); - }; - exports2.MD5 = function(object) { - return objectHash(object, { algorithm: "md5", encoding: "hex" }); - }; - exports2.keysMD5 = function(object) { - return objectHash(object, { algorithm: "md5", encoding: "hex", excludeValues: true }); - }; - var hashes = crypto4.getHashes ? crypto4.getHashes().slice() : ["sha1", "md5"]; - hashes.push("passthrough"); - var encodings = ["buffer", "hex", "binary", "base64"]; - function applyDefaults(object, sourceOptions) { - sourceOptions = sourceOptions || {}; - var options = {}; - options.algorithm = sourceOptions.algorithm || "sha1"; - options.encoding = sourceOptions.encoding || "hex"; - options.excludeValues = sourceOptions.excludeValues ? true : false; - options.algorithm = options.algorithm.toLowerCase(); - options.encoding = options.encoding.toLowerCase(); - options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; - options.respectType = sourceOptions.respectType === false ? false : true; - options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; - options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; - options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; - options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; - options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; - options.replacer = sourceOptions.replacer || void 0; - options.excludeKeys = sourceOptions.excludeKeys || void 0; - if (typeof object === "undefined") { - throw new Error("Object argument required."); - } - for (var i = 0; i < hashes.length; ++i) { - if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { - options.algorithm = hashes[i]; + if (this.lazy) { + if (!this._fileExist) { + if (!this._opening) { + this.open(); + } + this.once("open", () => { + this._fileExist = true; + this.log(info, callback); + return; + }); + return; + } + if (this._needsNewFile(this._pendingSize)) { + this._dest.once("close", () => { + if (!this._opening) { + this.open(); + } + this.once("open", () => { + this.log(info, callback); + return; + }); + return; + }); + return; + } } - } - if (hashes.indexOf(options.algorithm) === -1) { - throw new Error('Algorithm "' + options.algorithm + '" not supported. supported values: ' + hashes.join(", ")); - } - if (encodings.indexOf(options.encoding) === -1 && options.algorithm !== "passthrough") { - throw new Error('Encoding "' + options.encoding + '" not supported. supported values: ' + encodings.join(", ")); - } - return options; - } - function isNativeFunction(f) { - if (typeof f !== "function") { - return false; - } - var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; - return exp.exec(Function.prototype.toString.call(f)) != null; - } - function hash2(object, options) { - var hashingStream; - if (options.algorithm !== "passthrough") { - hashingStream = crypto4.createHash(options.algorithm); - } else { - hashingStream = new PassThrough(); - } - if (typeof hashingStream.write === "undefined") { - hashingStream.write = hashingStream.update; - hashingStream.end = hashingStream.update; - } - var hasher = typeHasher(options, hashingStream); - hasher.dispatch(object); - if (!hashingStream.update) { - hashingStream.end(""); - } - if (hashingStream.digest) { - return hashingStream.digest(options.encoding === "buffer" ? void 0 : options.encoding); - } - var buf = hashingStream.read(); - if (options.encoding === "buffer") { - return buf; - } - return buf.toString(options.encoding); - } - exports2.writeToStream = function(object, options, stream4) { - if (typeof stream4 === "undefined") { - stream4 = options; - options = {}; - } - options = applyDefaults(object, options); - return typeHasher(options, stream4).dispatch(object); - }; - function typeHasher(options, writeTo, context) { - context = context || []; - var write = function(str) { - if (writeTo.update) { - return writeTo.update(str, "utf8"); + const output = `${info[MESSAGE]}${this.eol}`; + const bytes = Buffer.byteLength(output); + function logged() { + this._size += bytes; + this._pendingSize -= bytes; + debug("logged %s %s", this._size, output); + this.emit("logged", info); + if (this._rotate) { + return; + } + if (this._opening) { + return; + } + if (!this._needsNewFile()) { + return; + } + if (this.lazy) { + this._endStream(() => { + this.emit("fileclosed"); + }); + return; + } + this._rotate = true; + this._endStream(() => this._rotateFile()); + } + this._pendingSize += bytes; + if (this._opening && !this.rotatedWhileOpening && this._needsNewFile(this._size + this._pendingSize)) { + this.rotatedWhileOpening = true; + } + const written = this._stream.write(output, logged.bind(this)); + if (!written) { + this._drain = true; + this._stream.once("drain", () => { + this._drain = false; + callback(); + }); } else { - return writeTo.write(str, "utf8"); + callback(); } - }; - return { - dispatch: function(value) { - if (options.replacer) { - value = options.replacer(value); + debug("written", written, this._drain); + this.finishIfEnding(); + return written; + } + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * TODO: Refactor me. + */ + query(options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } + options = normalizeQuery(options); + const file = path.join(this.dirname, this.filename); + let buff = ""; + let results = []; + let row = 0; + const stream4 = fs2.createReadStream(file, { + encoding: "utf8" + }); + stream4.on("error", (err) => { + if (stream4.readable) { + stream4.destroy(); } - var type = typeof value; - if (value === null) { - type = "null"; + if (!callback) { + return; } - return this["_" + type](value); - }, - _object: function(object) { - var pattern = /\[object (.*)\]/i; - var objString = Object.prototype.toString.call(object); - var objType = pattern.exec(objString); - if (!objType) { - objType = "unknown:[" + objString + "]"; - } else { - objType = objType[1]; + return err.code !== "ENOENT" ? callback(err) : callback(null, results); + }); + stream4.on("data", (data) => { + data = (buff + data).split(/\n+/); + const l = data.length - 1; + let i = 0; + for (; i < l; i++) { + if (!options.start || row >= options.start) { + add(data[i]); + } + row++; } - objType = objType.toLowerCase(); - var objectNumber = null; - if ((objectNumber = context.indexOf(object)) >= 0) { - return this.dispatch("[CIRCULAR:" + objectNumber + "]"); - } else { - context.push(object); + buff = data[l]; + }); + stream4.on("close", () => { + if (buff) { + add(buff, true); } - if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) { - write("buffer:"); - return write(object); + if (options.order === "desc") { + results = results.reverse(); } - if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") { - if (this["_" + objType]) { - this["_" + objType](object); - } else if (options.ignoreUnknown) { - return write("[" + objType + "]"); - } else { - throw new Error('Unknown object type "' + objType + '"'); + if (callback) callback(null, results); + }); + function add(buff2, attempt) { + try { + const log = JSON.parse(buff2); + if (check(log)) { + push(log); } - } else { - var keys = Object.keys(object); - if (options.unorderedObjects) { - keys = keys.sort(); + } catch (e) { + if (!attempt) { + stream4.emit("error", e); } - if (options.respectType !== false && !isNativeFunction(object)) { - keys.splice(0, 0, "prototype", "__proto__", "constructor"); + } + } + function push(log) { + if (options.rows && results.length >= options.rows && options.order !== "desc") { + if (stream4.readable) { + stream4.destroy(); } - if (options.excludeKeys) { - keys = keys.filter(function(key) { - return !options.excludeKeys(key); - }); + return; + } + if (options.fields) { + log = options.fields.reduce((obj, key) => { + obj[key] = log[key]; + return obj; + }, {}); + } + if (options.order === "desc") { + if (results.length >= options.rows) { + results.shift(); } - write("object:" + keys.length + ":"); - var self2 = this; - return keys.forEach(function(key) { - self2.dispatch(key); - write(":"); - if (!options.excludeValues) { - self2.dispatch(object[key]); - } - write(","); - }); } - }, - _array: function(arr, unordered) { - unordered = typeof unordered !== "undefined" ? unordered : options.unorderedArrays !== false; - var self2 = this; - write("array:" + arr.length + ":"); - if (!unordered || arr.length <= 1) { - return arr.forEach(function(entry) { - return self2.dispatch(entry); - }); + results.push(log); + } + function check(log) { + if (!log) { + return; + } + if (typeof log !== "object") { + return; + } + const time = new Date(log.timestamp); + if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) { + return; + } + return true; + } + function normalizeQuery(options2) { + options2 = options2 || {}; + options2.rows = options2.rows || options2.limit || 10; + options2.start = options2.start || 0; + options2.until = options2.until || /* @__PURE__ */ new Date(); + if (typeof options2.until !== "object") { + options2.until = new Date(options2.until); + } + options2.from = options2.from || options2.until - 24 * 60 * 60 * 1e3; + if (typeof options2.from !== "object") { + options2.from = new Date(options2.from); + } + options2.order = options2.order || "desc"; + return options2; + } + } + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + * TODO: Refactor me. + */ + stream(options = {}) { + const file = path.join(this.dirname, this.filename); + const stream4 = new Stream(); + const tail = { + file, + start: options.start + }; + stream4.destroy = tailFile(tail, (err, line) => { + if (err) { + return stream4.emit("error", err); + } + try { + stream4.emit("data", line); + line = JSON.parse(line); + stream4.emit("log", line); + } catch (e) { + stream4.emit("error", e); + } + }); + return stream4; + } + /** + * Checks to see the filesize of. + * @returns {undefined} + */ + open() { + if (!this.filename) return; + if (this._opening) return; + this._opening = true; + this.stat((err, size5) => { + if (err) { + return this.emit("error", err); } - var contextAdditions = []; - var entries = arr.map(function(entry) { - var strm = new PassThrough(); - var localContext = context.slice(); - var hasher = typeHasher(options, strm, localContext); - hasher.dispatch(entry); - contextAdditions = contextAdditions.concat(localContext.slice(context.length)); - return strm.read().toString(); + debug("stat done: %s { size: %s }", this.filename, size5); + this._size = size5; + this._dest = this._createStream(this._stream); + this._opening = false; + this.once("open", () => { + if (!this._stream.emit("rotate")) { + this._rotate = false; + } }); - context = context.concat(contextAdditions); - entries.sort(); - return this._array(entries, false); - }, - _date: function(date) { - return write("date:" + date.toJSON()); - }, - _symbol: function(sym) { - return write("symbol:" + sym.toString()); - }, - _error: function(err) { - return write("error:" + err.toString()); - }, - _boolean: function(bool) { - return write("bool:" + bool.toString()); - }, - _string: function(string) { - write("string:" + string.length + ":"); - write(string.toString()); - }, - _function: function(fn2) { - write("fn:"); - if (isNativeFunction(fn2)) { - this.dispatch("[native]"); - } else { - this.dispatch(fn2.toString()); - } - if (options.respectFunctionNames !== false) { - this.dispatch("function-name:" + String(fn2.name)); + }); + } + /** + * Stat the file and assess information in order to create the proper stream. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + stat(callback) { + const target = this._getFile(); + const fullpath = path.join(this.dirname, target); + fs2.stat(fullpath, (err, stat) => { + if (err && err.code === "ENOENT") { + debug("ENOENT\xA0ok", fullpath); + this.filename = target; + return callback(null, 0); } - if (options.respectFunctionProperties) { - this._object(fn2); + if (err) { + debug(`err ${err.code} ${fullpath}`); + return callback(err); } - }, - _number: function(number) { - return write("number:" + number.toString()); - }, - _xml: function(xml) { - return write("xml:" + xml.toString()); - }, - _null: function() { - return write("Null"); - }, - _undefined: function() { - return write("Undefined"); - }, - _regexp: function(regex) { - return write("regex:" + regex.toString()); - }, - _uint8array: function(arr) { - write("uint8array:"); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _uint8clampedarray: function(arr) { - write("uint8clampedarray:"); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _int8array: function(arr) { - write("int8array:"); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _uint16array: function(arr) { - write("uint16array:"); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _int16array: function(arr) { - write("int16array:"); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _uint32array: function(arr) { - write("uint32array:"); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _int32array: function(arr) { - write("int32array:"); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _float32array: function(arr) { - write("float32array:"); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _float64array: function(arr) { - write("float64array:"); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _arraybuffer: function(arr) { - write("arraybuffer:"); - return this.dispatch(new Uint8Array(arr)); - }, - _url: function(url2) { - return write("url:" + url2.toString(), "utf8"); - }, - _map: function(map) { - write("map:"); - var arr = Array.from(map); - return this._array(arr, options.unorderedSets !== false); - }, - _set: function(set) { - write("set:"); - var arr = Array.from(set); - return this._array(arr, options.unorderedSets !== false); - }, - _file: function(file) { - write("file:"); - return this.dispatch([file.name, file.size, file.type, file.lastModfied]); - }, - _blob: function() { - if (options.ignoreUnknown) { - return write("[blob]"); + if (!stat || this._needsNewFile(stat.size)) { + return this._incFile(() => this.stat(callback)); } - throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n'); - }, - _domwindow: function() { - return write("domwindow"); - }, - _bigint: function(number) { - return write("bigint:" + number.toString()); - }, - /* Node.js standard native objects */ - _process: function() { - return write("process"); - }, - _timer: function() { - return write("timer"); - }, - _pipe: function() { - return write("pipe"); - }, - _tcp: function() { - return write("tcp"); - }, - _udp: function() { - return write("udp"); - }, - _tty: function() { - return write("tty"); - }, - _statwatcher: function() { - return write("statwatcher"); - }, - _securecontext: function() { - return write("securecontext"); - }, - _connection: function() { - return write("connection"); - }, - _zlib: function() { - return write("zlib"); - }, - _context: function() { - return write("context"); - }, - _nodescript: function() { - return write("nodescript"); - }, - _httpparser: function() { - return write("httpparser"); - }, - _dataview: function() { - return write("dataview"); - }, - _signal: function() { - return write("signal"); - }, - _fsevent: function() { - return write("fsevent"); - }, - _tlswrap: function() { - return write("tlswrap"); - } - }; - } - function PassThrough() { - return { - buf: "", - write: function(b2) { - this.buf += b2; - }, - end: function(b2) { - this.buf += b2; - }, - read: function() { - return this.buf; + this.filename = target; + callback(null, stat.size); + }); + } + /** + * Closes the stream associated with this instance. + * @param {function} cb - TODO: add param description. + * @returns {undefined} + */ + close(cb) { + if (!this._stream) { + return; } - }; - } - } -}); - -// node_modules/moment/moment.js -var require_moment = __commonJS({ - "node_modules/moment/moment.js"(exports2, module2) { - (function(global2, factory) { - typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global2.moment = factory(); - })(exports2, function() { - "use strict"; - var hookCallback; - function hooks() { - return hookCallback.apply(null, arguments); + this._stream.end(() => { + if (cb) { + cb(); + } + this.emit("flush"); + this.emit("closed"); + }); } - function setHookCallback(callback) { - hookCallback = callback; + /** + * TODO: add method description. + * @param {number} size - TODO: add param description. + * @returns {undefined} + */ + _needsNewFile(size5) { + size5 = size5 || this._size; + return this.maxsize && size5 >= this.maxsize; } - function isArray2(input) { - return input instanceof Array || Object.prototype.toString.call(input) === "[object Array]"; + /** + * TODO: add method description. + * @param {Error} err - TODO: add param description. + * @returns {undefined} + */ + _onError(err) { + this.emit("error", err); } - function isObject2(input) { - return input != null && Object.prototype.toString.call(input) === "[object Object]"; + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + _setupStream(stream4) { + stream4.on("error", this._onError); + return stream4; } - function hasOwnProp(a, b2) { - return Object.prototype.hasOwnProperty.call(a, b2); + /** + * TODO: add method description. + * @param {Stream} stream - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + _cleanupStream(stream4) { + stream4.removeListener("error", this._onError); + stream4.destroy(); + return stream4; } - function isObjectEmpty(obj) { - if (Object.getOwnPropertyNames) { - return Object.getOwnPropertyNames(obj).length === 0; + /** + * TODO: add method description. + */ + _rotateFile() { + this._incFile(() => this.open()); + } + /** + * Unpipe from the stream that has been marked as full and end it so it + * flushes to disk. + * + * @param {function} callback - Callback for when the current file has closed. + * @private + */ + _endStream(callback = () => { + }) { + if (this._dest) { + this._stream.unpipe(this._dest); + this._dest.end(() => { + this._cleanupStream(this._dest); + callback(); + }); } else { - var k2; - for (k2 in obj) { - if (hasOwnProp(obj, k2)) { - return false; - } + callback(); + } + } + /** + * Returns the WritableStream for the active file on this instance. If we + * should gzip the file then a zlib stream is returned. + * + * @param {ReadableStream} source –PassThrough to pipe to the file when open. + * @returns {WritableStream} Stream that writes to disk for the active file. + */ + _createStream(source) { + const fullpath = path.join(this.dirname, this.filename); + debug("create stream start", fullpath, this.options); + const dest = fs2.createWriteStream(fullpath, this.options).on("error", (err) => debug(err)).on("close", () => debug("close", dest.path, dest.bytesWritten)).on("open", () => { + debug("file open ok", fullpath); + this.emit("open", fullpath); + source.pipe(dest); + if (this.rotatedWhileOpening) { + this._stream = new PassThrough(); + this._stream.setMaxListeners(30); + this._rotateFile(); + this.rotatedWhileOpening = false; + this._cleanupStream(dest); + source.end(); } - return true; + }); + debug("create stream ok", fullpath); + return dest; + } + /** + * TODO: add method description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + _incFile(callback) { + debug("_incFile", this.filename); + const ext = path.extname(this._basename); + const basename = path.basename(this._basename, ext); + const tasks = []; + if (this.zippedArchive) { + tasks.push( + function(cb) { + const num2 = this._created > 0 && !this.tailable ? this._created : ""; + this._compressFile( + path.join(this.dirname, `${basename}${num2}${ext}`), + path.join(this.dirname, `${basename}${num2}${ext}.gz`), + cb + ); + }.bind(this) + ); + } + tasks.push( + function(cb) { + if (!this.tailable) { + this._created += 1; + this._checkMaxFilesIncrementing(ext, basename, cb); + } else { + this._checkMaxFilesTailable(ext, basename, cb); + } + }.bind(this) + ); + asyncSeries(tasks, callback); + } + /** + * Gets the next filename to use for this instance in the case that log + * filesizes are being capped. + * @returns {string} - TODO: add return description. + * @private + */ + _getFile() { + const ext = path.extname(this._basename); + const basename = path.basename(this._basename, ext); + const isRotation = this.rotationFormat ? this.rotationFormat() : this._created; + return !this.tailable && this._created ? `${basename}${isRotation}${ext}` : `${basename}${ext}`; + } + /** + * Increment the number of files created or checked by this instance. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + _checkMaxFilesIncrementing(ext, basename, callback) { + if (!this.maxFiles || this._created < this.maxFiles) { + return setImmediate(callback); } + const oldest = this._created - this.maxFiles; + const isOldest = oldest !== 0 ? oldest : ""; + const isZipped = this.zippedArchive ? ".gz" : ""; + const filePath = `${basename}${isOldest}${ext}${isZipped}`; + const target = path.join(this.dirname, filePath); + fs2.unlink(target, callback); } - function isUndefined2(input) { - return input === void 0; + /** + * Roll files forward based on integer, up to maxFiles. e.g. if base if + * file.log and it becomes oversized, roll to file1.log, and allow file.log + * to be re-used. If file is oversized again, roll file1.log to file2.log, + * roll file.log to file1.log, and so on. + * @param {mixed} ext - TODO: add param description. + * @param {mixed} basename - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {undefined} + * @private + */ + _checkMaxFilesTailable(ext, basename, callback) { + const tasks = []; + if (!this.maxFiles) { + return; + } + const isZipped = this.zippedArchive ? ".gz" : ""; + for (let x2 = this.maxFiles - 1; x2 > 1; x2--) { + tasks.push(function(i, cb) { + let fileName = `${basename}${i - 1}${ext}${isZipped}`; + const tmppath = path.join(this.dirname, fileName); + fs2.exists(tmppath, (exists) => { + if (!exists) { + return cb(null); + } + fileName = `${basename}${i}${ext}${isZipped}`; + fs2.rename(tmppath, path.join(this.dirname, fileName), cb); + }); + }.bind(this, x2)); + } + asyncSeries(tasks, () => { + fs2.rename( + path.join(this.dirname, `${basename}${ext}${isZipped}`), + path.join(this.dirname, `${basename}1${ext}${isZipped}`), + callback + ); + }); } - function isNumber2(input) { - return typeof input === "number" || Object.prototype.toString.call(input) === "[object Number]"; + /** + * Compresses src to dest with gzip and unlinks src + * @param {string} src - path to source file. + * @param {string} dest - path to zipped destination file. + * @param {Function} callback - callback called after file has been compressed. + * @returns {undefined} + * @private + */ + _compressFile(src, dest, callback) { + fs2.access(src, fs2.F_OK, (err) => { + if (err) { + return callback(); + } + var gzip = zlib2.createGzip(); + var inp = fs2.createReadStream(src); + var out = fs2.createWriteStream(dest); + out.on("finish", () => { + fs2.unlink(src, callback); + }); + inp.pipe(gzip).pipe(out); + }); } - function isDate2(input) { - return input instanceof Date || Object.prototype.toString.call(input) === "[object Date]"; + _createLogDirIfNotExist(dirPath) { + if (!fs2.existsSync(dirPath)) { + fs2.mkdirSync(dirPath, { recursive: true }); + } } - function map(arr, fn2) { - var res = [], i, arrLen = arr.length; - for (i = 0; i < arrLen; ++i) { - res.push(fn2(arr[i], i)); + }; + } +}); + +// node_modules/winston/lib/winston/transports/http.js +var require_http = __commonJS({ + "node_modules/winston/lib/winston/transports/http.js"(exports2, module2) { + "use strict"; + var http3 = __require("http"); + var https2 = __require("https"); + var { Stream } = require_readable(); + var TransportStream = require_winston_transport(); + var { configure } = require_safe_stable_stringify(); + module2.exports = class Http extends TransportStream { + /** + * Constructor function for the Http transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + // eslint-disable-next-line max-statements + constructor(options = {}) { + super(options); + this.options = options; + this.name = options.name || "http"; + this.ssl = !!options.ssl; + this.host = options.host || "localhost"; + this.port = options.port; + this.auth = options.auth; + this.path = options.path || ""; + this.maximumDepth = options.maximumDepth; + this.agent = options.agent; + this.headers = options.headers || {}; + this.headers["content-type"] = "application/json"; + this.batch = options.batch || false; + this.batchInterval = options.batchInterval || 5e3; + this.batchCount = options.batchCount || 10; + this.batchOptions = []; + this.batchTimeoutID = -1; + this.batchCallback = {}; + if (!this.port) { + this.port = this.ssl ? 443 : 80; } - return res; } - function extend2(a, b2) { - for (var i in b2) { - if (hasOwnProp(b2, i)) { - a[i] = b2[i]; + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + this._request(info, null, null, (err, res) => { + if (res && res.statusCode !== 200) { + err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`); } + if (err) { + this.emit("warn", err); + } else { + this.emit("logged", info); + } + }); + if (callback) { + setImmediate(callback); } - if (hasOwnProp(b2, "toString")) { - a.toString = b2.toString; - } - if (hasOwnProp(b2, "valueOf")) { - a.valueOf = b2.valueOf; - } - return a; - } - function createUTC(input, format2, locale2, strict) { - return createLocalOrUTC(input, format2, locale2, strict, true).utc(); - } - function defaultParsingFlags() { - return { - empty: false, - unusedTokens: [], - unusedInput: [], - overflow: -2, - charsLeftOver: 0, - nullInput: false, - invalidEra: null, - invalidMonth: null, - invalidFormat: false, - userInvalidated: false, - iso: false, - parsedDateParts: [], - era: null, - meridiem: null, - rfc2822: false, - weekdayMismatch: false - }; } - function getParsingFlags(m2) { - if (m2._pf == null) { - m2._pf = defaultParsingFlags(); + /** + * Query the transport. Options object is optional. + * @param {Object} options - Loggly-like query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + * @returns {undefined} + */ + query(options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; } - return m2._pf; - } - var some; - if (Array.prototype.some) { - some = Array.prototype.some; - } else { - some = function(fun) { - var t = Object(this), len = t.length >>> 0, i; - for (i = 0; i < len; i++) { - if (i in t && fun.call(this, t[i], i, t)) { - return true; + options = { + method: "query", + params: this.normalizeQuery(options) + }; + const auth = options.params.auth || null; + delete options.params.auth; + const path = options.params.path || null; + delete options.params.path; + this._request(options, auth, path, (err, res, body) => { + if (res && res.statusCode !== 200) { + err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`); + } + if (err) { + return callback(err); + } + if (typeof body === "string") { + try { + body = JSON.parse(body); + } catch (e) { + return callback(e); } } - return false; - }; + callback(null, body); + }); } - function isValid(m2) { - var flags = null, parsedParts = false, isNowValid = m2._d && !isNaN(m2._d.getTime()); - if (isNowValid) { - flags = getParsingFlags(m2); - parsedParts = some.call(flags.parsedDateParts, function(i) { - return i != null; - }); - isNowValid = flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts); - if (m2._strict) { - isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === void 0; + /** + * Returns a log stream for this transport. Options object is optional. + * @param {Object} options - Stream options for this instance. + * @returns {Stream} - TODO: add return description + */ + stream(options = {}) { + const stream4 = new Stream(); + options = { + method: "stream", + params: options + }; + const path = options.params.path || null; + delete options.params.path; + const auth = options.params.auth || null; + delete options.params.auth; + let buff = ""; + const req = this._request(options, auth, path); + stream4.destroy = () => req.destroy(); + req.on("data", (data) => { + data = (buff + data).split(/\n+/); + const l = data.length - 1; + let i = 0; + for (; i < l; i++) { + try { + stream4.emit("log", JSON.parse(data[i])); + } catch (e) { + stream4.emit("error", e); + } } - } - if (Object.isFrozen == null || !Object.isFrozen(m2)) { - m2._isValid = isNowValid; - } else { - return isNowValid; - } - return m2._isValid; + buff = data[l]; + }); + req.on("error", (err) => stream4.emit("error", err)); + return stream4; } - function createInvalid(flags) { - var m2 = createUTC(NaN); - if (flags != null) { - extend2(getParsingFlags(m2), flags); + /** + * Make a request to a winstond server or any http server which can + * handle json-rpc. + * @param {function} options - Options to sent the request. + * @param {Object?} auth - authentication options + * @param {string} path - request path + * @param {function} callback - Continuation to respond to when complete. + */ + _request(options, auth, path, callback) { + options = options || {}; + auth = auth || this.auth; + path = path || this.path || ""; + if (this.batch) { + this._doBatch(options, callback, auth, path); } else { - getParsingFlags(m2).userInvalidated = true; + this._doRequest(options, callback, auth, path); } - return m2; } - var momentProperties = hooks.momentProperties = [], updateInProgress = false; - function copyConfig(to3, from6) { - var i, prop, val, momentPropertiesLen = momentProperties.length; - if (!isUndefined2(from6._isAMomentObject)) { - to3._isAMomentObject = from6._isAMomentObject; - } - if (!isUndefined2(from6._i)) { - to3._i = from6._i; - } - if (!isUndefined2(from6._f)) { - to3._f = from6._f; - } - if (!isUndefined2(from6._l)) { - to3._l = from6._l; - } - if (!isUndefined2(from6._strict)) { - to3._strict = from6._strict; - } - if (!isUndefined2(from6._tzm)) { - to3._tzm = from6._tzm; - } - if (!isUndefined2(from6._isUTC)) { - to3._isUTC = from6._isUTC; - } - if (!isUndefined2(from6._offset)) { - to3._offset = from6._offset; - } - if (!isUndefined2(from6._pf)) { - to3._pf = getParsingFlags(from6); - } - if (!isUndefined2(from6._locale)) { - to3._locale = from6._locale; + /** + * Send or memorize the options according to batch configuration + * @param {function} options - Options to sent the request. + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + _doBatch(options, callback, auth, path) { + this.batchOptions.push(options); + if (this.batchOptions.length === 1) { + const me = this; + this.batchCallback = callback; + this.batchTimeoutID = setTimeout(function() { + me.batchTimeoutID = -1; + me._doBatchRequest(me.batchCallback, auth, path); + }, this.batchInterval); } - if (momentPropertiesLen > 0) { - for (i = 0; i < momentPropertiesLen; i++) { - prop = momentProperties[i]; - val = from6[prop]; - if (!isUndefined2(val)) { - to3[prop] = val; - } - } + if (this.batchOptions.length === this.batchCount) { + this._doBatchRequest(this.batchCallback, auth, path); } - return to3; } - function Moment(config3) { - copyConfig(this, config3); - this._d = new Date(config3._d != null ? config3._d.getTime() : NaN); - if (!this.isValid()) { - this._d = /* @__PURE__ */ new Date(NaN); - } - if (updateInProgress === false) { - updateInProgress = true; - hooks.updateOffset(this); - updateInProgress = false; + /** + * Initiate a request with the memorized batch options, stop the batch timeout + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + _doBatchRequest(callback, auth, path) { + if (this.batchTimeoutID > 0) { + clearTimeout(this.batchTimeoutID); + this.batchTimeoutID = -1; } + const batchOptionsCopy = this.batchOptions.slice(); + this.batchOptions = []; + this._doRequest(batchOptionsCopy, callback, auth, path); } - function isMoment(obj) { - return obj instanceof Moment || obj != null && obj._isAMomentObject != null; + /** + * Make a request to a winstond server or any http server which can + * handle json-rpc. + * @param {function} options - Options to sent the request. + * @param {function} callback - Continuation to respond to when complete. + * @param {Object?} auth - authentication options + * @param {string} path - request path + */ + _doRequest(options, callback, auth, path) { + const headers = Object.assign({}, this.headers); + if (auth && auth.bearer) { + headers.Authorization = `Bearer ${auth.bearer}`; + } + const req = (this.ssl ? https2 : http3).request({ + ...this.options, + method: "POST", + host: this.host, + port: this.port, + path: `/${path.replace(/^\//, "")}`, + headers, + auth: auth && auth.username && auth.password ? `${auth.username}:${auth.password}` : "", + agent: this.agent + }); + req.on("error", callback); + req.on("response", (res) => res.on("end", () => callback(null, res)).resume()); + const jsonStringify = configure({ + ...this.maximumDepth && { maximumDepth: this.maximumDepth } + }); + req.end(Buffer.from(jsonStringify(options, this.options.replacer), "utf8")); } - function warn(msg) { - if (hooks.suppressDeprecationWarnings === false && typeof console !== "undefined" && console.warn) { - console.warn("Deprecation warning: " + msg); + }; + } +}); + +// node_modules/is-stream/index.js +var require_is_stream = __commonJS({ + "node_modules/is-stream/index.js"(exports2, module2) { + "use strict"; + var isStream2 = (stream4) => stream4 !== null && typeof stream4 === "object" && typeof stream4.pipe === "function"; + isStream2.writable = (stream4) => isStream2(stream4) && stream4.writable !== false && typeof stream4._write === "function" && typeof stream4._writableState === "object"; + isStream2.readable = (stream4) => isStream2(stream4) && stream4.readable !== false && typeof stream4._read === "function" && typeof stream4._readableState === "object"; + isStream2.duplex = (stream4) => isStream2.writable(stream4) && isStream2.readable(stream4); + isStream2.transform = (stream4) => isStream2.duplex(stream4) && typeof stream4._transform === "function"; + module2.exports = isStream2; + } +}); + +// node_modules/winston/lib/winston/transports/stream.js +var require_stream2 = __commonJS({ + "node_modules/winston/lib/winston/transports/stream.js"(exports2, module2) { + "use strict"; + var isStream2 = require_is_stream(); + var { MESSAGE } = require_triple_beam(); + var os2 = __require("os"); + var TransportStream = require_winston_transport(); + module2.exports = class Stream extends TransportStream { + /** + * Constructor function for the Console transport object responsible for + * persisting log messages and metadata to a terminal or TTY. + * @param {!Object} [options={}] - Options for this instance. + */ + constructor(options = {}) { + super(options); + if (!options.stream || !isStream2(options.stream)) { + throw new Error("options.stream is required."); } + this._stream = options.stream; + this._stream.setMaxListeners(Infinity); + this.isObjectMode = options.stream._writableState.objectMode; + this.eol = typeof options.eol === "string" ? options.eol : os2.EOL; } - function deprecate(msg, fn2) { - var firstTime = true; - return extend2(function() { - if (hooks.deprecationHandler != null) { - hooks.deprecationHandler(null, msg); - } - if (firstTime) { - var args = [], arg, i, key, argLen = arguments.length; - for (i = 0; i < argLen; i++) { - arg = ""; - if (typeof arguments[i] === "object") { - arg += "\n[" + i + "] "; - for (key in arguments[0]) { - if (hasOwnProp(arguments[0], key)) { - arg += key + ": " + arguments[0][key] + ", "; - } - } - arg = arg.slice(0, -2); - } else { - arg = arguments[i]; - } - args.push(arg); - } - warn( - msg + "\nArguments: " + Array.prototype.slice.call(args).join("") + "\n" + new Error().stack - ); - firstTime = false; + /** + * Core logging method exposed to Winston. + * @param {Object} info - TODO: add param description. + * @param {Function} callback - TODO: add param description. + * @returns {undefined} + */ + log(info, callback) { + setImmediate(() => this.emit("logged", info)); + if (this.isObjectMode) { + this._stream.write(info); + if (callback) { + callback(); } - return fn2.apply(this, arguments); - }, fn2); - } - var deprecations = {}; - function deprecateSimple(name, msg) { - if (hooks.deprecationHandler != null) { - hooks.deprecationHandler(name, msg); + return; } - if (!deprecations[name]) { - warn(msg); - deprecations[name] = true; + this._stream.write(`${info[MESSAGE]}${this.eol}`); + if (callback) { + callback(); } + return; } - hooks.suppressDeprecationWarnings = false; - hooks.deprecationHandler = null; - function isFunction2(input) { - return typeof Function !== "undefined" && input instanceof Function || Object.prototype.toString.call(input) === "[object Function]"; + }; + } +}); + +// node_modules/winston/lib/winston/transports/index.js +var require_transports = __commonJS({ + "node_modules/winston/lib/winston/transports/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "Console", { + configurable: true, + enumerable: true, + get() { + return require_console(); } - function set(config3) { - var prop, i; - for (i in config3) { - if (hasOwnProp(config3, i)) { - prop = config3[i]; - if (isFunction2(prop)) { - this[i] = prop; - } else { - this["_" + i] = prop; - } - } - } - this._config = config3; - this._dayOfMonthOrdinalParseLenient = new RegExp( - (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + "|" + /\d{1,2}/.source - ); + }); + Object.defineProperty(exports2, "File", { + configurable: true, + enumerable: true, + get() { + return require_file(); } - function mergeConfigs(parentConfig, childConfig) { - var res = extend2({}, parentConfig), prop; - for (prop in childConfig) { - if (hasOwnProp(childConfig, prop)) { - if (isObject2(parentConfig[prop]) && isObject2(childConfig[prop])) { - res[prop] = {}; - extend2(res[prop], parentConfig[prop]); - extend2(res[prop], childConfig[prop]); - } else if (childConfig[prop] != null) { - res[prop] = childConfig[prop]; - } else { - delete res[prop]; - } - } + }); + Object.defineProperty(exports2, "Http", { + configurable: true, + enumerable: true, + get() { + return require_http(); + } + }); + Object.defineProperty(exports2, "Stream", { + configurable: true, + enumerable: true, + get() { + return require_stream2(); + } + }); + } +}); + +// node_modules/winston/lib/winston/config/index.js +var require_config2 = __commonJS({ + "node_modules/winston/lib/winston/config/index.js"(exports2) { + "use strict"; + var logform = require_logform(); + var { configs } = require_triple_beam(); + exports2.cli = logform.levels(configs.cli); + exports2.npm = logform.levels(configs.npm); + exports2.syslog = logform.levels(configs.syslog); + exports2.addColors = logform.levels; + } +}); + +// node_modules/async/eachOf.js +var require_eachOf = __commonJS({ + "node_modules/async/eachOf.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _isArrayLike = require_isArrayLike(); + var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + var _breakLoop = require_breakLoop(); + var _breakLoop2 = _interopRequireDefault(_breakLoop); + var _eachOfLimit = require_eachOfLimit2(); + var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + var _once = require_once(); + var _once2 = _interopRequireDefault(_once); + var _onlyOnce = require_onlyOnce(); + var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + var _wrapAsync = require_wrapAsync(); + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + var _awaitify = require_awaitify(); + var _awaitify2 = _interopRequireDefault(_awaitify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback); + var index2 = 0, completed = 0, { length } = coll, canceled = false; + if (length === 0) { + callback(null); + } + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; } - for (prop in parentConfig) { - if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject2(parentConfig[prop])) { - res[prop] = extend2({}, res[prop]); - } + if (canceled === true) return; + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); } - return res; } - function Locale(config3) { - if (config3 != null) { - this.set(config3); - } + for (; index2 < length; index2++) { + iteratee(coll[index2], index2, (0, _onlyOnce2.default)(iteratorCallback)); } - var keys; - if (Object.keys) { - keys = Object.keys; - } else { - keys = function(obj) { - var i, res = []; - for (i in obj) { - if (hasOwnProp(obj, i)) { - res.push(i); - } - } - return res; - }; + } + function eachOfGeneric(coll, iteratee, callback) { + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback); + } + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); + } + exports2.default = (0, _awaitify2.default)(eachOf, 3); + module2.exports = exports2.default; + } +}); + +// node_modules/async/internal/withoutIndex.js +var require_withoutIndex = __commonJS({ + "node_modules/async/internal/withoutIndex.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = _withoutIndex; + function _withoutIndex(iteratee) { + return (value, index2, callback) => iteratee(value, callback); + } + module2.exports = exports2.default; + } +}); + +// node_modules/async/forEach.js +var require_forEach = __commonJS({ + "node_modules/async/forEach.js"(exports2, module2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { + value: true + }); + var _eachOf = require_eachOf(); + var _eachOf2 = _interopRequireDefault(_eachOf); + var _withoutIndex = require_withoutIndex(); + var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + var _wrapAsync = require_wrapAsync(); + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + var _awaitify = require_awaitify(); + var _awaitify2 = _interopRequireDefault(_awaitify); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function eachLimit(coll, iteratee, callback) { + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); + } + exports2.default = (0, _awaitify2.default)(eachLimit, 3); + module2.exports = exports2.default; + } +}); + +// node_modules/fn.name/index.js +var require_fn = __commonJS({ + "node_modules/fn.name/index.js"(exports2, module2) { + "use strict"; + var toString3 = Object.prototype.toString; + module2.exports = function name(fn2) { + if ("string" === typeof fn2.displayName && fn2.constructor.name) { + return fn2.displayName; + } else if ("string" === typeof fn2.name && fn2.name) { + return fn2.name; } - var defaultCalendar = { - sameDay: "[Today at] LT", - nextDay: "[Tomorrow at] LT", - nextWeek: "dddd [at] LT", - lastDay: "[Yesterday at] LT", - lastWeek: "[Last] dddd [at] LT", - sameElse: "L" - }; - function calendar(key, mom, now2) { - var output = this._calendar[key] || this._calendar["sameElse"]; - return isFunction2(output) ? output.call(mom, now2) : output; + if ("object" === typeof fn2 && fn2.constructor && "string" === typeof fn2.constructor.name) return fn2.constructor.name; + var named = fn2.toString(), type = toString3.call(fn2).slice(8, -1); + if ("Function" === type) { + named = named.substring(named.indexOf("(") + 1, named.indexOf(")")); + } else { + named = type; } - function zeroFill(number, targetLength, forceSign) { - var absNumber = "" + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign3 = number >= 0; - return (sign3 ? forceSign ? "+" : "" : "-") + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; + return named || "anonymous"; + }; + } +}); + +// node_modules/one-time/index.js +var require_one_time = __commonJS({ + "node_modules/one-time/index.js"(exports2, module2) { + "use strict"; + var name = require_fn(); + module2.exports = function one(fn2) { + var called = 0, value; + function onetime() { + if (called) return value; + called = 1; + value = fn2.apply(this, arguments); + fn2 = null; + return value; } - var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, formatFunctions = {}, formatTokenFunctions = {}; - function addFormatToken(token2, padded, ordinal2, callback) { - var func = callback; - if (typeof callback === "string") { - func = function() { - return this[callback](); - }; - } - if (token2) { - formatTokenFunctions[token2] = func; - } - if (padded) { - formatTokenFunctions[padded[0]] = function() { - return zeroFill(func.apply(this, arguments), padded[1], padded[2]); - }; - } - if (ordinal2) { - formatTokenFunctions[ordinal2] = function() { - return this.localeData().ordinal( - func.apply(this, arguments), - token2 - ); - }; - } + onetime.displayName = name(fn2); + return onetime; + }; + } +}); + +// node_modules/stack-trace/lib/stack-trace.js +var require_stack_trace = __commonJS({ + "node_modules/stack-trace/lib/stack-trace.js"(exports2) { + exports2.get = function(belowFn) { + var oldLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Infinity; + var dummyObject = {}; + var v8Handler = Error.prepareStackTrace; + Error.prepareStackTrace = function(dummyObject2, v8StackTrace2) { + return v8StackTrace2; + }; + Error.captureStackTrace(dummyObject, belowFn || exports2.get); + var v8StackTrace = dummyObject.stack; + Error.prepareStackTrace = v8Handler; + Error.stackTraceLimit = oldLimit; + return v8StackTrace; + }; + exports2.parse = function(err) { + if (!err.stack) { + return []; } - function removeFormattingTokens(input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|\]$/g, ""); + var self2 = this; + var lines = err.stack.split("\n").slice(1); + return lines.map(function(line) { + if (line.match(/^\s*[-]{4,}$/)) { + return self2._createParsedCallSite({ + fileName: line, + lineNumber: null, + functionName: null, + typeName: null, + methodName: null, + columnNumber: null, + "native": null + }); } - return input.replace(/\\/g, ""); - } - function makeFormatFunction(format2) { - var array = format2.match(formattingTokens), i, length; - for (i = 0, length = array.length; i < length; i++) { - if (formatTokenFunctions[array[i]]) { - array[i] = formatTokenFunctions[array[i]]; - } else { - array[i] = removeFormattingTokens(array[i]); - } + var lineMatch = line.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/); + if (!lineMatch) { + return; } - return function(mom) { - var output = "", i2; - for (i2 = 0; i2 < length; i2++) { - output += isFunction2(array[i2]) ? array[i2].call(mom, format2) : array[i2]; + var object = null; + var method = null; + var functionName = null; + var typeName = null; + var methodName = null; + var isNative = lineMatch[5] === "native"; + if (lineMatch[1]) { + functionName = lineMatch[1]; + var methodStart = functionName.lastIndexOf("."); + if (functionName[methodStart - 1] == ".") + methodStart--; + if (methodStart > 0) { + object = functionName.substr(0, methodStart); + method = functionName.substr(methodStart + 1); + var objectEnd = object.indexOf(".Module"); + if (objectEnd > 0) { + functionName = functionName.substr(objectEnd + 1); + object = object.substr(0, objectEnd); + } } - return output; - }; - } - function formatMoment(m2, format2) { - if (!m2.isValid()) { - return m2.localeData().invalidDate(); - } - format2 = expandFormat(format2, m2.localeData()); - formatFunctions[format2] = formatFunctions[format2] || makeFormatFunction(format2); - return formatFunctions[format2](m2); - } - function expandFormat(format2, locale2) { - var i = 5; - function replaceLongDateFormatTokens(input) { - return locale2.longDateFormat(input) || input; + typeName = null; } - localFormattingTokens.lastIndex = 0; - while (i >= 0 && localFormattingTokens.test(format2)) { - format2 = format2.replace( - localFormattingTokens, - replaceLongDateFormatTokens - ); - localFormattingTokens.lastIndex = 0; - i -= 1; + if (method) { + typeName = object; + methodName = method; } - return format2; - } - var defaultLongDateFormat = { - LTS: "h:mm:ss A", - LT: "h:mm A", - L: "MM/DD/YYYY", - LL: "MMMM D, YYYY", - LLL: "MMMM D, YYYY h:mm A", - LLLL: "dddd, MMMM D, YYYY h:mm A" - }; - function longDateFormat(key) { - var format2 = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()]; - if (format2 || !formatUpper) { - return format2; + if (method === "") { + methodName = null; + functionName = null; } - this._longDateFormat[key] = formatUpper.match(formattingTokens).map(function(tok) { - if (tok === "MMMM" || tok === "MM" || tok === "DD" || tok === "dddd") { - return tok.slice(1); - } - return tok; - }).join(""); - return this._longDateFormat[key]; - } - var defaultInvalidDate = "Invalid date"; - function invalidDate() { - return this._invalidDate; - } - var defaultOrdinal = "%d", defaultDayOfMonthOrdinalParse = /\d{1,2}/; - function ordinal(number) { - return this._ordinal.replace("%d", number); + var properties = { + fileName: lineMatch[2] || null, + lineNumber: parseInt(lineMatch[3], 10) || null, + functionName, + typeName, + methodName, + columnNumber: parseInt(lineMatch[4], 10) || null, + "native": isNative + }; + return self2._createParsedCallSite(properties); + }).filter(function(callSite) { + return !!callSite; + }); + }; + function CallSite(properties) { + for (var property in properties) { + this[property] = properties[property]; } - var defaultRelativeTime = { - future: "in %s", - past: "%s ago", - s: "a few seconds", - ss: "%d seconds", - m: "a minute", - mm: "%d minutes", - h: "an hour", - hh: "%d hours", - d: "a day", - dd: "%d days", - w: "a week", - ww: "%d weeks", - M: "a month", - MM: "%d months", - y: "a year", - yy: "%d years" + } + var strProperties = [ + "this", + "typeName", + "functionName", + "methodName", + "fileName", + "lineNumber", + "columnNumber", + "function", + "evalOrigin" + ]; + var boolProperties = [ + "topLevel", + "eval", + "native", + "constructor" + ]; + strProperties.forEach(function(property) { + CallSite.prototype[property] = null; + CallSite.prototype["get" + property[0].toUpperCase() + property.substr(1)] = function() { + return this[property]; }; - function relativeTime(number, withoutSuffix, string, isFuture) { - var output = this._relativeTime[string]; - return isFunction2(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); - } - function pastFuture(diff2, output) { - var format2 = this._relativeTime[diff2 > 0 ? "future" : "past"]; - return isFunction2(format2) ? format2(output) : format2.replace(/%s/i, output); - } - var aliases = { - D: "date", - dates: "date", - date: "date", - d: "day", - days: "day", - day: "day", - e: "weekday", - weekdays: "weekday", - weekday: "weekday", - E: "isoWeekday", - isoweekdays: "isoWeekday", - isoweekday: "isoWeekday", - DDD: "dayOfYear", - dayofyears: "dayOfYear", - dayofyear: "dayOfYear", - h: "hour", - hours: "hour", - hour: "hour", - ms: "millisecond", - milliseconds: "millisecond", - millisecond: "millisecond", - m: "minute", - minutes: "minute", - minute: "minute", - M: "month", - months: "month", - month: "month", - Q: "quarter", - quarters: "quarter", - quarter: "quarter", - s: "second", - seconds: "second", - second: "second", - gg: "weekYear", - weekyears: "weekYear", - weekyear: "weekYear", - GG: "isoWeekYear", - isoweekyears: "isoWeekYear", - isoweekyear: "isoWeekYear", - w: "week", - weeks: "week", - week: "week", - W: "isoWeek", - isoweeks: "isoWeek", - isoweek: "isoWeek", - y: "year", - years: "year", - year: "year" + }); + boolProperties.forEach(function(property) { + CallSite.prototype[property] = false; + CallSite.prototype["is" + property[0].toUpperCase() + property.substr(1)] = function() { + return this[property]; }; - function normalizeUnits(units) { - return typeof units === "string" ? aliases[units] || aliases[units.toLowerCase()] : void 0; + }); + exports2._createParsedCallSite = function(properties) { + return new CallSite(properties); + }; + } +}); + +// node_modules/winston/lib/winston/exception-stream.js +var require_exception_stream = __commonJS({ + "node_modules/winston/lib/winston/exception-stream.js"(exports2, module2) { + "use strict"; + var { Writable } = require_readable(); + module2.exports = class ExceptionStream extends Writable { + /** + * Constructor function for the ExceptionStream responsible for wrapping a + * TransportStream; only allowing writes of `info` objects with + * `info.exception` set to true. + * @param {!TransportStream} transport - Stream to filter to exceptions + */ + constructor(transport) { + super({ objectMode: true }); + if (!transport) { + throw new Error("ExceptionStream requires a TransportStream instance."); + } + this.handleExceptions = true; + this.transport = transport; } - function normalizeObjectUnits(inputObject) { - var normalizedInput = {}, normalizedProp, prop; - for (prop in inputObject) { - if (hasOwnProp(inputObject, prop)) { - normalizedProp = normalizeUnits(prop); - if (normalizedProp) { - normalizedInput[normalizedProp] = inputObject[prop]; - } - } + /** + * Writes the info object to our transport instance if (and only if) the + * `exception` property is set on the info. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {mixed} - TODO: add return description. + * @private + */ + _write(info, enc, callback) { + if (info.exception) { + return this.transport.log(info, callback); } - return normalizedInput; + callback(); + return true; } - var priorities = { - date: 9, - day: 11, - weekday: 11, - isoWeekday: 11, - dayOfYear: 4, - hour: 13, - millisecond: 16, - minute: 14, - month: 8, - quarter: 7, - second: 15, - weekYear: 1, - isoWeekYear: 1, - week: 5, - isoWeek: 5, - year: 1 - }; - function getPrioritizedUnits(unitsObj) { - var units = [], u; - for (u in unitsObj) { - if (hasOwnProp(unitsObj, u)) { - units.push({ unit: u, priority: priorities[u] }); - } + }; + } +}); + +// node_modules/winston/lib/winston/exception-handler.js +var require_exception_handler = __commonJS({ + "node_modules/winston/lib/winston/exception-handler.js"(exports2, module2) { + "use strict"; + var os2 = __require("os"); + var asyncForEach = require_forEach(); + var debug = require_node2()("winston:exception"); + var once = require_one_time(); + var stackTrace = require_stack_trace(); + var ExceptionStream = require_exception_stream(); + module2.exports = class ExceptionHandler { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + constructor(logger) { + if (!logger) { + throw new Error("Logger is required to handle exceptions"); } - units.sort(function(a, b2) { - return a.priority - b2.priority; + this.logger = logger; + this.handlers = /* @__PURE__ */ new Map(); + } + /** + * Handles `uncaughtException` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + handle(...args) { + args.forEach((arg) => { + if (Array.isArray(arg)) { + return arg.forEach((handler) => this._addHandler(handler)); + } + this._addHandler(arg); }); - return units; + if (!this.catcher) { + this.catcher = this._uncaughtException.bind(this); + process.on("uncaughtException", this.catcher); + } } - var match1 = /\d/, match2 = /\d\d/, match3 = /\d{3}/, match4 = /\d{4}/, match6 = /[+-]?\d{6}/, match1to2 = /\d\d?/, match3to4 = /\d\d\d\d?/, match5to6 = /\d\d\d\d\d\d?/, match1to3 = /\d{1,3}/, match1to4 = /\d{1,4}/, match1to6 = /[+-]?\d{1,6}/, matchUnsigned = /\d+/, matchSigned = /[+-]?\d+/, matchOffset = /Z|[+-]\d\d:?\d\d/gi, matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, match1to2NoLeadingZero = /^[1-9]\d?/, match1to2HasZero = /^([1-9]\d|\d)/, regexes; - regexes = {}; - function addRegexToken(token2, regex, strictRegex) { - regexes[token2] = isFunction2(regex) ? regex : function(isStrict, localeData2) { - return isStrict && strictRegex ? strictRegex : regex; - }; + /** + * Removes any handlers to `uncaughtException` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + unhandle() { + if (this.catcher) { + process.removeListener("uncaughtException", this.catcher); + this.catcher = false; + Array.from(this.handlers.values()).forEach((wrapper) => this.logger.unpipe(wrapper)); + } } - function getParseRegexForToken(token2, config3) { - if (!hasOwnProp(regexes, token2)) { - return new RegExp(unescapeFormat(token2)); + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + getAllInfo(err) { + let message = null; + if (err) { + message = typeof err === "string" ? err : err.message; } - return regexes[token2](config3._strict, config3._locale); + return { + error: err, + // TODO (indexzero): how do we configure this? + level: "error", + message: [ + `uncaughtException: ${message || "(no error message)"}`, + err && err.stack || " No stack trace" + ].join("\n"), + stack: err && err.stack, + exception: true, + date: (/* @__PURE__ */ new Date()).toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; } - function unescapeFormat(s) { - return regexEscape( - s.replace("\\", "").replace( - /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, - function(matched, p1, p2, p3, p4) { - return p1 || p2 || p3 || p4; - } - ) - ); + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; } - function regexEscape(s) { - return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getOsInfo() { + return { + loadavg: os2.loadavg(), + uptime: os2.uptime() + }; } - function absFloor(number) { - if (number < 0) { - return Math.ceil(number) || 0; - } else { - return Math.floor(number); - } + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + getTrace(err) { + const trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map((site) => { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + function: site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + native: site.isNative() + }; + }); } - function toInt(argumentForCoercion) { - var coercedNumber = +argumentForCoercion, value = 0; - if (coercedNumber !== 0 && isFinite(coercedNumber)) { - value = absFloor(coercedNumber); + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleExceptions = true; + const wrapper = new ExceptionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); } - return value; } - var tokens = {}; - function addParseToken(token2, callback) { - var i, func = callback, tokenLen; - if (typeof token2 === "string") { - token2 = [token2]; + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + _uncaughtException(err) { + const info = this.getAllInfo(err); + const handlers = this._getExceptionHandlers(); + let doExit = typeof this.logger.exitOnError === "function" ? this.logger.exitOnError(err) : this.logger.exitOnError; + let timeout; + if (!handlers.length && doExit) { + console.warn("winston: exitOnError cannot be true with no exception handlers."); + console.warn("winston: not exiting process."); + doExit = false; } - if (isNumber2(callback)) { - func = function(input, array) { - array[callback] = toInt(input); - }; + function gracefulExit() { + debug("doExit", doExit); + debug("process._exiting", process._exiting); + if (doExit && !process._exiting) { + if (timeout) { + clearTimeout(timeout); + } + process.exit(1); + } } - tokenLen = token2.length; - for (i = 0; i < tokenLen; i++) { - tokens[token2[i]] = func; + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); + } + asyncForEach(handlers, (handler, next) => { + const done = once(next); + const transport = handler.transport || handler; + function onDone(event) { + return () => { + debug(event); + done(); + }; + } + transport._ending = true; + transport.once("finish", onDone("finished")); + transport.once("error", onDone("error")); + }, () => doExit && gracefulExit()); + this.logger.log(info); + if (doExit) { + timeout = setTimeout(gracefulExit, 3e3); } } - function addWeekParseToken(token2, callback) { - addParseToken(token2, function(input, array, config3, token3) { - config3._w = config3._w || {}; - callback(input, config3._w, config3, token3); + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + _getExceptionHandlers() { + return this.logger.transports.filter((wrap) => { + const transport = wrap.transport || wrap; + return transport.handleExceptions; }); } - function addTimeToArrayFromToken(token2, input, config3) { - if (input != null && hasOwnProp(tokens, token2)) { - tokens[token2](input, config3._a, config3, token2); + }; + } +}); + +// node_modules/winston/lib/winston/rejection-stream.js +var require_rejection_stream = __commonJS({ + "node_modules/winston/lib/winston/rejection-stream.js"(exports2, module2) { + "use strict"; + var { Writable } = require_readable(); + module2.exports = class RejectionStream extends Writable { + /** + * Constructor function for the RejectionStream responsible for wrapping a + * TransportStream; only allowing writes of `info` objects with + * `info.rejection` set to true. + * @param {!TransportStream} transport - Stream to filter to rejections + */ + constructor(transport) { + super({ objectMode: true }); + if (!transport) { + throw new Error("RejectionStream requires a TransportStream instance."); } + this.handleRejections = true; + this.transport = transport; } - function isLeapYear(year) { - return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0; - } - var YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, WEEK = 7, WEEKDAY = 8; - addFormatToken("Y", 0, 0, function() { - var y2 = this.year(); - return y2 <= 9999 ? zeroFill(y2, 4) : "+" + y2; - }); - addFormatToken(0, ["YY", 2], 0, function() { - return this.year() % 100; - }); - addFormatToken(0, ["YYYY", 4], 0, "year"); - addFormatToken(0, ["YYYYY", 5], 0, "year"); - addFormatToken(0, ["YYYYYY", 6, true], 0, "year"); - addRegexToken("Y", matchSigned); - addRegexToken("YY", match1to2, match2); - addRegexToken("YYYY", match1to4, match4); - addRegexToken("YYYYY", match1to6, match6); - addRegexToken("YYYYYY", match1to6, match6); - addParseToken(["YYYYY", "YYYYYY"], YEAR); - addParseToken("YYYY", function(input, array) { - array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); - }); - addParseToken("YY", function(input, array) { - array[YEAR] = hooks.parseTwoDigitYear(input); - }); - addParseToken("Y", function(input, array) { - array[YEAR] = parseInt(input, 10); - }); - function daysInYear(year) { - return isLeapYear(year) ? 366 : 365; + /** + * Writes the info object to our transport instance if (and only if) the + * `rejection` property is set on the info. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - TODO: add param description. + * @returns {mixed} - TODO: add return description. + * @private + */ + _write(info, enc, callback) { + if (info.rejection) { + return this.transport.log(info, callback); + } + callback(); + return true; } - hooks.parseTwoDigitYear = function(input) { - return toInt(input) + (toInt(input) > 68 ? 1900 : 2e3); - }; - var getSetYear = makeGetSet("FullYear", true); - function getIsLeapYear() { - return isLeapYear(this.year()); + }; + } +}); + +// node_modules/winston/lib/winston/rejection-handler.js +var require_rejection_handler = __commonJS({ + "node_modules/winston/lib/winston/rejection-handler.js"(exports2, module2) { + "use strict"; + var os2 = __require("os"); + var asyncForEach = require_forEach(); + var debug = require_node2()("winston:rejection"); + var once = require_one_time(); + var stackTrace = require_stack_trace(); + var RejectionStream = require_rejection_stream(); + module2.exports = class RejectionHandler { + /** + * TODO: add contructor description + * @param {!Logger} logger - TODO: add param description + */ + constructor(logger) { + if (!logger) { + throw new Error("Logger is required to handle rejections"); + } + this.logger = logger; + this.handlers = /* @__PURE__ */ new Map(); } - function makeGetSet(unit, keepTime) { - return function(value) { - if (value != null) { - set$1(this, unit, value); - hooks.updateOffset(this, keepTime); - return this; - } else { - return get(this, unit); + /** + * Handles `unhandledRejection` events for the current process by adding any + * handlers passed in. + * @returns {undefined} + */ + handle(...args) { + args.forEach((arg) => { + if (Array.isArray(arg)) { + return arg.forEach((handler) => this._addHandler(handler)); } - }; - } - function get(mom, unit) { - if (!mom.isValid()) { - return NaN; - } - var d = mom._d, isUTC = mom._isUTC; - switch (unit) { - case "Milliseconds": - return isUTC ? d.getUTCMilliseconds() : d.getMilliseconds(); - case "Seconds": - return isUTC ? d.getUTCSeconds() : d.getSeconds(); - case "Minutes": - return isUTC ? d.getUTCMinutes() : d.getMinutes(); - case "Hours": - return isUTC ? d.getUTCHours() : d.getHours(); - case "Date": - return isUTC ? d.getUTCDate() : d.getDate(); - case "Day": - return isUTC ? d.getUTCDay() : d.getDay(); - case "Month": - return isUTC ? d.getUTCMonth() : d.getMonth(); - case "FullYear": - return isUTC ? d.getUTCFullYear() : d.getFullYear(); - default: - return NaN; + this._addHandler(arg); + }); + if (!this.catcher) { + this.catcher = this._unhandledRejection.bind(this); + process.on("unhandledRejection", this.catcher); } } - function set$1(mom, unit, value) { - var d, isUTC, year, month, date; - if (!mom.isValid() || isNaN(value)) { - return; + /** + * Removes any handlers to `unhandledRejection` events for the current + * process. This does not modify the state of the `this.handlers` set. + * @returns {undefined} + */ + unhandle() { + if (this.catcher) { + process.removeListener("unhandledRejection", this.catcher); + this.catcher = false; + Array.from(this.handlers.values()).forEach( + (wrapper) => this.logger.unpipe(wrapper) + ); } - d = mom._d; - isUTC = mom._isUTC; - switch (unit) { - case "Milliseconds": - return void (isUTC ? d.setUTCMilliseconds(value) : d.setMilliseconds(value)); - case "Seconds": - return void (isUTC ? d.setUTCSeconds(value) : d.setSeconds(value)); - case "Minutes": - return void (isUTC ? d.setUTCMinutes(value) : d.setMinutes(value)); - case "Hours": - return void (isUTC ? d.setUTCHours(value) : d.setHours(value)); - case "Date": - return void (isUTC ? d.setUTCDate(value) : d.setDate(value)); - // case 'Day': // Not real - // return void (isUTC ? d.setUTCDay(value) : d.setDay(value)); - // case 'Month': // Not used because we need to pass two variables - // return void (isUTC ? d.setUTCMonth(value) : d.setMonth(value)); - case "FullYear": - break; - // See below ... - default: - return; + } + /** + * TODO: add method description + * @param {Error} err - Error to get information about. + * @returns {mixed} - TODO: add return description. + */ + getAllInfo(err) { + let message = null; + if (err) { + message = typeof err === "string" ? err : err.message; } - year = value; - month = mom.month(); - date = mom.date(); - date = date === 29 && month === 1 && !isLeapYear(year) ? 28 : date; - void (isUTC ? d.setUTCFullYear(year, month, date) : d.setFullYear(year, month, date)); + return { + error: err, + // TODO (indexzero): how do we configure this? + level: "error", + message: [ + `unhandledRejection: ${message || "(no error message)"}`, + err && err.stack || " No stack trace" + ].join("\n"), + stack: err && err.stack, + rejection: true, + date: (/* @__PURE__ */ new Date()).toString(), + process: this.getProcessInfo(), + os: this.getOsInfo(), + trace: this.getTrace(err) + }; } - function stringGet(units) { - units = normalizeUnits(units); - if (isFunction2(this[units])) { - return this[units](); + /** + * Gets all relevant process information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getProcessInfo() { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; + } + /** + * Gets all relevant OS information for the currently running process. + * @returns {mixed} - TODO: add return description. + */ + getOsInfo() { + return { + loadavg: os2.loadavg(), + uptime: os2.uptime() + }; + } + /** + * Gets a stack trace for the specified error. + * @param {mixed} err - TODO: add param description. + * @returns {mixed} - TODO: add return description. + */ + getTrace(err) { + const trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map((site) => { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + function: site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + native: site.isNative() + }; + }); + } + /** + * Helper method to add a transport as an exception handler. + * @param {Transport} handler - The transport to add as an exception handler. + * @returns {void} + */ + _addHandler(handler) { + if (!this.handlers.has(handler)) { + handler.handleRejections = true; + const wrapper = new RejectionStream(handler); + this.handlers.set(handler, wrapper); + this.logger.pipe(wrapper); } - return this; } - function stringSet(units, value) { - if (typeof units === "object") { - units = normalizeObjectUnits(units); - var prioritized = getPrioritizedUnits(units), i, prioritizedLen = prioritized.length; - for (i = 0; i < prioritizedLen; i++) { - this[prioritized[i].unit](units[prioritized[i].unit]); - } - } else { - units = normalizeUnits(units); - if (isFunction2(this[units])) { - return this[units](value); - } + /** + * Logs all relevant information around the `err` and exits the current + * process. + * @param {Error} err - Error to handle + * @returns {mixed} - TODO: add return description. + * @private + */ + _unhandledRejection(err) { + const info = this.getAllInfo(err); + const handlers = this._getRejectionHandlers(); + let doExit = typeof this.logger.exitOnError === "function" ? this.logger.exitOnError(err) : this.logger.exitOnError; + let timeout; + if (!handlers.length && doExit) { + console.warn("winston: exitOnError cannot be true with no rejection handlers."); + console.warn("winston: not exiting process."); + doExit = false; } - return this; - } - function mod2(n, x2) { - return (n % x2 + x2) % x2; - } - var indexOf; - if (Array.prototype.indexOf) { - indexOf = Array.prototype.indexOf; - } else { - indexOf = function(o) { - var i; - for (i = 0; i < this.length; ++i) { - if (this[i] === o) { - return i; + function gracefulExit() { + debug("doExit", doExit); + debug("process._exiting", process._exiting); + if (doExit && !process._exiting) { + if (timeout) { + clearTimeout(timeout); } + process.exit(1); } - return -1; - }; - } - function daysInMonth(year, month) { - if (isNaN(year) || isNaN(month)) { - return NaN; } - var modMonth = mod2(month, 12); - year += (month - modMonth) / 12; - return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2; - } - addFormatToken("M", ["MM", 2], "Mo", function() { - return this.month() + 1; - }); - addFormatToken("MMM", 0, 0, function(format2) { - return this.localeData().monthsShort(this, format2); - }); - addFormatToken("MMMM", 0, 0, function(format2) { - return this.localeData().months(this, format2); - }); - addRegexToken("M", match1to2, match1to2NoLeadingZero); - addRegexToken("MM", match1to2, match2); - addRegexToken("MMM", function(isStrict, locale2) { - return locale2.monthsShortRegex(isStrict); - }); - addRegexToken("MMMM", function(isStrict, locale2) { - return locale2.monthsRegex(isStrict); - }); - addParseToken(["M", "MM"], function(input, array) { - array[MONTH] = toInt(input) - 1; - }); - addParseToken(["MMM", "MMMM"], function(input, array, config3, token2) { - var month = config3._locale.monthsParse(input, token2, config3._strict); - if (month != null) { - array[MONTH] = month; - } else { - getParsingFlags(config3).invalidMonth = input; + if (!handlers || handlers.length === 0) { + return process.nextTick(gracefulExit); } - }); - var defaultLocaleMonths = "January_February_March_April_May_June_July_August_September_October_November_December".split( - "_" - ), defaultLocaleMonthsShort = "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, defaultMonthsShortRegex = matchWord, defaultMonthsRegex = matchWord; - function localeMonths(m2, format2) { - if (!m2) { - return isArray2(this._months) ? this._months : this._months["standalone"]; + asyncForEach( + handlers, + (handler, next) => { + const done = once(next); + const transport = handler.transport || handler; + function onDone(event) { + return () => { + debug(event); + done(); + }; + } + transport._ending = true; + transport.once("finish", onDone("finished")); + transport.once("error", onDone("error")); + }, + () => doExit && gracefulExit() + ); + this.logger.log(info); + if (doExit) { + timeout = setTimeout(gracefulExit, 3e3); } - return isArray2(this._months) ? this._months[m2.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format2) ? "format" : "standalone"][m2.month()]; } - function localeMonthsShort(m2, format2) { - if (!m2) { - return isArray2(this._monthsShort) ? this._monthsShort : this._monthsShort["standalone"]; + /** + * Returns the list of transports and exceptionHandlers for this instance. + * @returns {Array} - List of transports and exceptionHandlers for this + * instance. + * @private + */ + _getRejectionHandlers() { + return this.logger.transports.filter((wrap) => { + const transport = wrap.transport || wrap; + return transport.handleRejections; + }); + } + }; + } +}); + +// node_modules/winston/lib/winston/profiler.js +var require_profiler = __commonJS({ + "node_modules/winston/lib/winston/profiler.js"(exports2, module2) { + "use strict"; + var Profiler = class { + /** + * Constructor function for the Profiler instance used by + * `Logger.prototype.startTimer`. When done is called the timer will finish + * and log the duration. + * @param {!Logger} logger - TODO: add param description. + * @private + */ + constructor(logger) { + const Logger2 = require_logger(); + if (typeof logger !== "object" || Array.isArray(logger) || !(logger instanceof Logger2)) { + throw new Error("Logger is required for profiling"); + } else { + this.logger = logger; + this.start = Date.now(); } - return isArray2(this._monthsShort) ? this._monthsShort[m2.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format2) ? "format" : "standalone"][m2.month()]; } - function handleStrictParse(monthName, format2, strict) { - var i, ii2, mom, llc = monthName.toLocaleLowerCase(); - if (!this._monthsParse) { - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - for (i = 0; i < 12; ++i) { - mom = createUTC([2e3, i]); - this._shortMonthsParse[i] = this.monthsShort( - mom, - "" - ).toLocaleLowerCase(); - this._longMonthsParse[i] = this.months(mom, "").toLocaleLowerCase(); - } + /** + * Ends the current timer (i.e. Profiler) instance and logs the `msg` along + * with the duration since creation. + * @returns {mixed} - TODO: add return description. + * @private + */ + done(...args) { + if (typeof args[args.length - 1] === "function") { + console.warn("Callback function no longer supported as of winston@3.0.0"); + args.pop(); } - if (strict) { - if (format2 === "MMM") { - ii2 = indexOf.call(this._shortMonthsParse, llc); - return ii2 !== -1 ? ii2 : null; - } else { - ii2 = indexOf.call(this._longMonthsParse, llc); - return ii2 !== -1 ? ii2 : null; - } - } else { - if (format2 === "MMM") { - ii2 = indexOf.call(this._shortMonthsParse, llc); - if (ii2 !== -1) { - return ii2; - } - ii2 = indexOf.call(this._longMonthsParse, llc); - return ii2 !== -1 ? ii2 : null; - } else { - ii2 = indexOf.call(this._longMonthsParse, llc); - if (ii2 !== -1) { - return ii2; + const info = typeof args[args.length - 1] === "object" ? args.pop() : {}; + info.level = info.level || "info"; + info.durationMs = Date.now() - this.start; + return this.logger.write(info); + } + }; + module2.exports = Profiler; + } +}); + +// node_modules/winston/lib/winston/logger.js +var require_logger = __commonJS({ + "node_modules/winston/lib/winston/logger.js"(exports2, module2) { + "use strict"; + var { Stream, Transform } = require_readable(); + var asyncForEach = require_forEach(); + var { LEVEL, SPLAT } = require_triple_beam(); + var isStream2 = require_is_stream(); + var ExceptionHandler = require_exception_handler(); + var RejectionHandler = require_rejection_handler(); + var LegacyTransportStream = require_legacy(); + var Profiler = require_profiler(); + var { warn } = require_common(); + var config3 = require_config2(); + var formatRegExp = /%[scdjifoO%]/g; + var Logger2 = class extends Transform { + /** + * Constructor function for the Logger object responsible for persisting log + * messages and metadata to one or more transports. + * @param {!Object} options - foo + */ + constructor(options) { + super({ objectMode: true }); + this.configure(options); + } + child(defaultRequestMetadata) { + const logger = this; + return Object.create(logger, { + write: { + value: function(info) { + const infoClone = Object.assign( + {}, + defaultRequestMetadata, + info + ); + if (info instanceof Error) { + infoClone.stack = info.stack; + infoClone.message = info.message; + } + logger.write(infoClone); } - ii2 = indexOf.call(this._shortMonthsParse, llc); - return ii2 !== -1 ? ii2 : null; } - } + }); } - function localeMonthsParse(monthName, format2, strict) { - var i, mom, regex; - if (this._monthsParseExact) { - return handleStrictParse.call(this, monthName, format2, strict); + /** + * This will wholesale reconfigure this instance by: + * 1. Resetting all transports. Older transports will be removed implicitly. + * 2. Set all other options including levels, colors, rewriters, filters, + * exceptionHandlers, etc. + * @param {!Object} options - TODO: add param description. + * @returns {undefined} + */ + configure({ + silent, + format, + defaultMeta, + levels, + level = "info", + exitOnError = true, + transports, + colors, + emitErrs, + formatters, + padLevels, + rewriters, + stripColors, + exceptionHandlers, + rejectionHandlers + } = {}) { + if (this.transports.length) { + this.clear(); } - if (!this._monthsParse) { - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; + this.silent = silent; + this.format = format || this.format || require_json()(); + this.defaultMeta = defaultMeta || null; + this.levels = levels || this.levels || config3.npm.levels; + this.level = level; + if (this.exceptions) { + this.exceptions.unhandle(); } - for (i = 0; i < 12; i++) { - mom = createUTC([2e3, i]); - if (strict && !this._longMonthsParse[i]) { - this._longMonthsParse[i] = new RegExp( - "^" + this.months(mom, "").replace(".", "") + "$", - "i" - ); - this._shortMonthsParse[i] = new RegExp( - "^" + this.monthsShort(mom, "").replace(".", "") + "$", - "i" - ); - } - if (!strict && !this._monthsParse[i]) { - regex = "^" + this.months(mom, "") + "|^" + this.monthsShort(mom, ""); - this._monthsParse[i] = new RegExp(regex.replace(".", ""), "i"); - } - if (strict && format2 === "MMMM" && this._longMonthsParse[i].test(monthName)) { - return i; - } else if (strict && format2 === "MMM" && this._shortMonthsParse[i].test(monthName)) { - return i; - } else if (!strict && this._monthsParse[i].test(monthName)) { - return i; - } + if (this.rejections) { + this.rejections.unhandle(); } - } - function setMonth(mom, value) { - if (!mom.isValid()) { - return mom; + this.exceptions = new ExceptionHandler(this); + this.rejections = new RejectionHandler(this); + this.profilers = {}; + this.exitOnError = exitOnError; + if (transports) { + transports = Array.isArray(transports) ? transports : [transports]; + transports.forEach((transport) => this.add(transport)); } - if (typeof value === "string") { - if (/^\d+$/.test(value)) { - value = toInt(value); - } else { - value = mom.localeData().monthsParse(value); - if (!isNumber2(value)) { - return mom; - } - } + if (colors || emitErrs || formatters || padLevels || rewriters || stripColors) { + throw new Error( + [ + "{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.", + "Use a custom winston.format(function) instead.", + "See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md" + ].join("\n") + ); } - var month = value, date = mom.date(); - date = date < 29 ? date : Math.min(date, daysInMonth(mom.year(), month)); - void (mom._isUTC ? mom._d.setUTCMonth(month, date) : mom._d.setMonth(month, date)); - return mom; - } - function getSetMonth(value) { - if (value != null) { - setMonth(this, value); - hooks.updateOffset(this, true); - return this; - } else { - return get(this, "Month"); + if (exceptionHandlers) { + this.exceptions.handle(exceptionHandlers); } - } - function getDaysInMonth() { - return daysInMonth(this.year(), this.month()); - } - function monthsShortRegex(isStrict) { - if (this._monthsParseExact) { - if (!hasOwnProp(this, "_monthsRegex")) { - computeMonthsParse.call(this); - } - if (isStrict) { - return this._monthsShortStrictRegex; - } else { - return this._monthsShortRegex; - } - } else { - if (!hasOwnProp(this, "_monthsShortRegex")) { - this._monthsShortRegex = defaultMonthsShortRegex; - } - return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex; + if (rejectionHandlers) { + this.rejections.handle(rejectionHandlers); } } - function monthsRegex(isStrict) { - if (this._monthsParseExact) { - if (!hasOwnProp(this, "_monthsRegex")) { - computeMonthsParse.call(this); - } - if (isStrict) { - return this._monthsStrictRegex; - } else { - return this._monthsRegex; - } - } else { - if (!hasOwnProp(this, "_monthsRegex")) { - this._monthsRegex = defaultMonthsRegex; - } - return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex; + isLevelEnabled(level) { + const givenLevelValue = getLevelValue(this.levels, level); + if (givenLevelValue === null) { + return false; } - } - function computeMonthsParse() { - function cmpLenRev(a, b2) { - return b2.length - a.length; + const configuredLevelValue = getLevelValue(this.levels, this.level); + if (configuredLevelValue === null) { + return false; } - var shortPieces = [], longPieces = [], mixedPieces = [], i, mom, shortP, longP; - for (i = 0; i < 12; i++) { - mom = createUTC([2e3, i]); - shortP = regexEscape(this.monthsShort(mom, "")); - longP = regexEscape(this.months(mom, "")); - shortPieces.push(shortP); - longPieces.push(longP); - mixedPieces.push(longP); - mixedPieces.push(shortP); + if (!this.transports || this.transports.length === 0) { + return configuredLevelValue >= givenLevelValue; } - shortPieces.sort(cmpLenRev); - longPieces.sort(cmpLenRev); - mixedPieces.sort(cmpLenRev); - this._monthsRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); - this._monthsShortRegex = this._monthsRegex; - this._monthsStrictRegex = new RegExp( - "^(" + longPieces.join("|") + ")", - "i" - ); - this._monthsShortStrictRegex = new RegExp( - "^(" + shortPieces.join("|") + ")", - "i" - ); - } - function createDate(y2, m2, d, h, M2, s, ms) { - var date; - if (y2 < 100 && y2 >= 0) { - date = new Date(y2 + 400, m2, d, h, M2, s, ms); - if (isFinite(date.getFullYear())) { - date.setFullYear(y2); + const index2 = this.transports.findIndex((transport) => { + let transportLevelValue = getLevelValue(this.levels, transport.level); + if (transportLevelValue === null) { + transportLevelValue = configuredLevelValue; } - } else { - date = new Date(y2, m2, d, h, M2, s, ms); - } - return date; + return transportLevelValue >= givenLevelValue; + }); + return index2 !== -1; } - function createUTCDate(y2) { - var date, args; - if (y2 < 100 && y2 >= 0) { - args = Array.prototype.slice.call(arguments); - args[0] = y2 + 400; - date = new Date(Date.UTC.apply(null, args)); - if (isFinite(date.getUTCFullYear())) { - date.setUTCFullYear(y2); + /* eslint-disable valid-jsdoc */ + /** + * Ensure backwards compatibility with a `log` method + * @param {mixed} level - Level the log message is written at. + * @param {mixed} msg - TODO: add param description. + * @param {mixed} meta - TODO: add param description. + * @returns {Logger} - TODO: add return description. + * + * @example + * // Supports the existing API: + * logger.log('info', 'Hello world', { custom: true }); + * logger.log('info', new Error('Yo, it\'s on fire')); + * + * // Requires winston.format.splat() + * logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true }); + * + * // And the new API with a single JSON literal: + * logger.log({ level: 'info', message: 'Hello world', custom: true }); + * logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') }); + * + * // Also requires winston.format.splat() + * logger.log({ + * level: 'info', + * message: '%s %d%%', + * [SPLAT]: ['A string', 50], + * meta: { thisIsMeta: true } + * }); + * + */ + /* eslint-enable valid-jsdoc */ + log(level, msg, ...splat) { + if (arguments.length === 1) { + level[LEVEL] = level.level; + this._addDefaultMeta(level); + this.write(level); + return this; + } + if (arguments.length === 2) { + if (msg && typeof msg === "object") { + msg[LEVEL] = msg.level = level; + this._addDefaultMeta(msg); + this.write(msg); + return this; } - } else { - date = new Date(Date.UTC.apply(null, arguments)); + msg = { [LEVEL]: level, level, message: msg }; + this._addDefaultMeta(msg); + this.write(msg); + return this; } - return date; - } - function firstWeekOffset(year, dow, doy) { - var fwd = 7 + dow - doy, fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; - return -fwdlw + fwd - 1; - } - function dayOfYearFromWeeks(year, week, weekday, dow, doy) { - var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear; - if (dayOfYear <= 0) { - resYear = year - 1; - resDayOfYear = daysInYear(resYear) + dayOfYear; - } else if (dayOfYear > daysInYear(year)) { - resYear = year + 1; - resDayOfYear = dayOfYear - daysInYear(year); - } else { - resYear = year; - resDayOfYear = dayOfYear; + const [meta] = splat; + if (typeof meta === "object" && meta !== null) { + const tokens = msg && msg.match && msg.match(formatRegExp); + if (!tokens) { + const info = Object.assign({}, this.defaultMeta, meta, { + [LEVEL]: level, + [SPLAT]: splat, + level, + message: msg + }); + if (meta.message) info.message = `${info.message} ${meta.message}`; + if (meta.stack) info.stack = meta.stack; + if (meta.cause) info.cause = meta.cause; + this.write(info); + return this; + } } - return { - year: resYear, - dayOfYear: resDayOfYear - }; + this.write(Object.assign({}, this.defaultMeta, { + [LEVEL]: level, + [SPLAT]: splat, + level, + message: msg + })); + return this; } - function weekOfYear(mom, dow, doy) { - var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear; - if (week < 1) { - resYear = mom.year() - 1; - resWeek = week + weeksInYear(resYear, dow, doy); - } else if (week > weeksInYear(mom.year(), dow, doy)) { - resWeek = week - weeksInYear(mom.year(), dow, doy); - resYear = mom.year() + 1; - } else { - resYear = mom.year(); - resWeek = week; + /** + * Pushes data so that it can be picked up by all of our pipe targets. + * @param {mixed} info - TODO: add param description. + * @param {mixed} enc - TODO: add param description. + * @param {mixed} callback - Continues stream processing. + * @returns {undefined} + * @private + */ + _transform(info, enc, callback) { + if (this.silent) { + return callback(); } - return { - week: resWeek, - year: resYear - }; - } - function weeksInYear(year, dow, doy) { - var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy); - return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; - } - addFormatToken("w", ["ww", 2], "wo", "week"); - addFormatToken("W", ["WW", 2], "Wo", "isoWeek"); - addRegexToken("w", match1to2, match1to2NoLeadingZero); - addRegexToken("ww", match1to2, match2); - addRegexToken("W", match1to2, match1to2NoLeadingZero); - addRegexToken("WW", match1to2, match2); - addWeekParseToken( - ["w", "ww", "W", "WW"], - function(input, week, config3, token2) { - week[token2.substr(0, 1)] = toInt(input); + if (!info[LEVEL]) { + info[LEVEL] = info.level; + } + if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) { + console.error("[winston] Unknown logger level: %s", info[LEVEL]); + } + if (!this._readableState.pipes) { + console.error( + "[winston] Attempt to write logs with no transports, which can increase memory usage: %j", + info + ); + } + try { + this.push(this.format.transform(info, this.format.options)); + } finally { + this._writableState.sync = false; + callback(); } - ); - function localeWeek(mom) { - return weekOfYear(mom, this._week.dow, this._week.doy).week; - } - var defaultLocaleWeek = { - dow: 0, - // Sunday is the first day of the week. - doy: 6 - // The week that contains Jan 6th is the first week of the year. - }; - function localeFirstDayOfWeek() { - return this._week.dow; - } - function localeFirstDayOfYear() { - return this._week.doy; - } - function getSetWeek(input) { - var week = this.localeData().week(this); - return input == null ? week : this.add((input - week) * 7, "d"); } - function getSetISOWeek(input) { - var week = weekOfYear(this, 1, 4).week; - return input == null ? week : this.add((input - week) * 7, "d"); + /** + * Delays the 'finish' event until all transport pipe targets have + * also emitted 'finish' or are already finished. + * @param {mixed} callback - Continues stream processing. + */ + _final(callback) { + const transports = this.transports.slice(); + asyncForEach( + transports, + (transport, next) => { + if (!transport || transport.finished) return setImmediate(next); + transport.once("finish", next); + transport.end(); + }, + callback + ); } - addFormatToken("d", 0, "do", "day"); - addFormatToken("dd", 0, 0, function(format2) { - return this.localeData().weekdaysMin(this, format2); - }); - addFormatToken("ddd", 0, 0, function(format2) { - return this.localeData().weekdaysShort(this, format2); - }); - addFormatToken("dddd", 0, 0, function(format2) { - return this.localeData().weekdays(this, format2); - }); - addFormatToken("e", 0, 0, "weekday"); - addFormatToken("E", 0, 0, "isoWeekday"); - addRegexToken("d", match1to2); - addRegexToken("e", match1to2); - addRegexToken("E", match1to2); - addRegexToken("dd", function(isStrict, locale2) { - return locale2.weekdaysMinRegex(isStrict); - }); - addRegexToken("ddd", function(isStrict, locale2) { - return locale2.weekdaysShortRegex(isStrict); - }); - addRegexToken("dddd", function(isStrict, locale2) { - return locale2.weekdaysRegex(isStrict); - }); - addWeekParseToken(["dd", "ddd", "dddd"], function(input, week, config3, token2) { - var weekday = config3._locale.weekdaysParse(input, token2, config3._strict); - if (weekday != null) { - week.d = weekday; - } else { - getParsingFlags(config3).invalidWeekday = input; - } - }); - addWeekParseToken(["d", "e", "E"], function(input, week, config3, token2) { - week[token2] = toInt(input); - }); - function parseWeekday(input, locale2) { - if (typeof input !== "string") { - return input; + /** + * Adds the transport to this logger instance by piping to it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + add(transport) { + const target = !isStream2(transport) || transport.log.length > 2 ? new LegacyTransportStream({ transport }) : transport; + if (!target._writableState || !target._writableState.objectMode) { + throw new Error( + "Transports must WritableStreams in objectMode. Set { objectMode: true }." + ); } - if (!isNaN(input)) { - return parseInt(input, 10); + this._onEvent("error", target); + this._onEvent("warn", target); + this.pipe(target); + if (transport.handleExceptions) { + this.exceptions.handle(); } - input = locale2.weekdaysParse(input); - if (typeof input === "number") { - return input; + if (transport.handleRejections) { + this.rejections.handle(); } - return null; + return this; } - function parseIsoWeekday(input, locale2) { - if (typeof input === "string") { - return locale2.weekdaysParse(input) % 7 || 7; + /** + * Removes the transport from this logger instance by unpiping from it. + * @param {mixed} transport - TODO: add param description. + * @returns {Logger} - TODO: add return description. + */ + remove(transport) { + if (!transport) return this; + let target = transport; + if (!isStream2(transport) || transport.log.length > 2) { + target = this.transports.filter( + (match) => match.transport === transport + )[0]; } - return isNaN(input) ? null : input; - } - function shiftWeekdays(ws2, n) { - return ws2.slice(n, 7).concat(ws2.slice(0, n)); + if (target) { + this.unpipe(target); + } + return this; } - var defaultLocaleWeekdays = "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), defaultLocaleWeekdaysShort = "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), defaultLocaleWeekdaysMin = "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), defaultWeekdaysRegex = matchWord, defaultWeekdaysShortRegex = matchWord, defaultWeekdaysMinRegex = matchWord; - function localeWeekdays(m2, format2) { - var weekdays = isArray2(this._weekdays) ? this._weekdays : this._weekdays[m2 && m2 !== true && this._weekdays.isFormat.test(format2) ? "format" : "standalone"]; - return m2 === true ? shiftWeekdays(weekdays, this._week.dow) : m2 ? weekdays[m2.day()] : weekdays; + /** + * Removes all transports from this logger instance. + * @returns {Logger} - TODO: add return description. + */ + clear() { + this.unpipe(); + return this; } - function localeWeekdaysShort(m2) { - return m2 === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m2 ? this._weekdaysShort[m2.day()] : this._weekdaysShort; + /** + * Cleans up resources (streams, event listeners) for all transports + * associated with this instance (if necessary). + * @returns {Logger} - TODO: add return description. + */ + close() { + this.exceptions.unhandle(); + this.rejections.unhandle(); + this.clear(); + this.emit("close"); + return this; } - function localeWeekdaysMin(m2) { - return m2 === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m2 ? this._weekdaysMin[m2.day()] : this._weekdaysMin; + /** + * Sets the `target` levels specified on this instance. + * @param {Object} Target levels to use on this instance. + */ + setLevels() { + warn.deprecated("setLevels"); } - function handleStrictParse$1(weekdayName, format2, strict) { - var i, ii2, mom, llc = weekdayName.toLocaleLowerCase(); - if (!this._weekdaysParse) { - this._weekdaysParse = []; - this._shortWeekdaysParse = []; - this._minWeekdaysParse = []; - for (i = 0; i < 7; ++i) { - mom = createUTC([2e3, 1]).day(i); - this._minWeekdaysParse[i] = this.weekdaysMin( - mom, - "" - ).toLocaleLowerCase(); - this._shortWeekdaysParse[i] = this.weekdaysShort( - mom, - "" - ).toLocaleLowerCase(); - this._weekdaysParse[i] = this.weekdays(mom, "").toLocaleLowerCase(); - } + /** + * Queries the all transports for this instance with the specified `options`. + * This will aggregate each transport's results into one object containing + * a property per transport. + * @param {Object} options - Query options for this instance. + * @param {function} callback - Continuation to respond to when complete. + */ + query(options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; } - if (strict) { - if (format2 === "dddd") { - ii2 = indexOf.call(this._weekdaysParse, llc); - return ii2 !== -1 ? ii2 : null; - } else if (format2 === "ddd") { - ii2 = indexOf.call(this._shortWeekdaysParse, llc); - return ii2 !== -1 ? ii2 : null; - } else { - ii2 = indexOf.call(this._minWeekdaysParse, llc); - return ii2 !== -1 ? ii2 : null; + options = options || {}; + const results = {}; + const queryObject = Object.assign({}, options.query || {}); + function queryTransport(transport, next) { + if (options.query && typeof transport.formatQuery === "function") { + options.query = transport.formatQuery(queryObject); } - } else { - if (format2 === "dddd") { - ii2 = indexOf.call(this._weekdaysParse, llc); - if (ii2 !== -1) { - return ii2; - } - ii2 = indexOf.call(this._shortWeekdaysParse, llc); - if (ii2 !== -1) { - return ii2; - } - ii2 = indexOf.call(this._minWeekdaysParse, llc); - return ii2 !== -1 ? ii2 : null; - } else if (format2 === "ddd") { - ii2 = indexOf.call(this._shortWeekdaysParse, llc); - if (ii2 !== -1) { - return ii2; - } - ii2 = indexOf.call(this._weekdaysParse, llc); - if (ii2 !== -1) { - return ii2; + transport.query(options, (err, res) => { + if (err) { + return next(err); } - ii2 = indexOf.call(this._minWeekdaysParse, llc); - return ii2 !== -1 ? ii2 : null; - } else { - ii2 = indexOf.call(this._minWeekdaysParse, llc); - if (ii2 !== -1) { - return ii2; + if (typeof transport.formatResults === "function") { + res = transport.formatResults(res, options.format); } - ii2 = indexOf.call(this._weekdaysParse, llc); - if (ii2 !== -1) { - return ii2; + next(null, res); + }); + } + function addResults(transport, next) { + queryTransport(transport, (err, result) => { + if (next) { + result = err || result; + if (result) { + results[transport.name] = result; + } + next(); } - ii2 = indexOf.call(this._shortWeekdaysParse, llc); - return ii2 !== -1 ? ii2 : null; - } + next = null; + }); } + asyncForEach( + this.transports.filter((transport) => !!transport.query), + addResults, + () => callback(null, results) + ); } - function localeWeekdaysParse(weekdayName, format2, strict) { - var i, mom, regex; - if (this._weekdaysParseExact) { - return handleStrictParse$1.call(this, weekdayName, format2, strict); - } - if (!this._weekdaysParse) { - this._weekdaysParse = []; - this._minWeekdaysParse = []; - this._shortWeekdaysParse = []; - this._fullWeekdaysParse = []; - } - for (i = 0; i < 7; i++) { - mom = createUTC([2e3, 1]).day(i); - if (strict && !this._fullWeekdaysParse[i]) { - this._fullWeekdaysParse[i] = new RegExp( - "^" + this.weekdays(mom, "").replace(".", "\\.?") + "$", - "i" - ); - this._shortWeekdaysParse[i] = new RegExp( - "^" + this.weekdaysShort(mom, "").replace(".", "\\.?") + "$", - "i" - ); - this._minWeekdaysParse[i] = new RegExp( - "^" + this.weekdaysMin(mom, "").replace(".", "\\.?") + "$", - "i" - ); + /** + * Returns a log stream for all transports. Options object is optional. + * @param{Object} options={} - Stream options for this instance. + * @returns {Stream} - TODO: add return description. + */ + stream(options = {}) { + const out = new Stream(); + const streams = []; + out._streams = streams; + out.destroy = () => { + let i = streams.length; + while (i--) { + streams[i].destroy(); } - if (!this._weekdaysParse[i]) { - regex = "^" + this.weekdays(mom, "") + "|^" + this.weekdaysShort(mom, "") + "|^" + this.weekdaysMin(mom, ""); - this._weekdaysParse[i] = new RegExp(regex.replace(".", ""), "i"); + }; + this.transports.filter((transport) => !!transport.stream).forEach((transport) => { + const str = transport.stream(options); + if (!str) { + return; } - if (strict && format2 === "dddd" && this._fullWeekdaysParse[i].test(weekdayName)) { - return i; - } else if (strict && format2 === "ddd" && this._shortWeekdaysParse[i].test(weekdayName)) { - return i; - } else if (strict && format2 === "dd" && this._minWeekdaysParse[i].test(weekdayName)) { - return i; - } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { - return i; + streams.push(str); + str.on("log", (log) => { + log.transport = log.transport || []; + log.transport.push(transport.name); + out.emit("log", log); + }); + str.on("error", (err) => { + err.transport = err.transport || []; + err.transport.push(transport.name); + out.emit("error", err); + }); + }); + return out; + } + /** + * Returns an object corresponding to a specific timing. When done is called + * the timer will finish and log the duration. e.g.: + * @returns {Profile} - TODO: add return description. + * @example + * const timer = winston.startTimer() + * setTimeout(() => { + * timer.done({ + * message: 'Logging message' + * }); + * }, 1000); + */ + startTimer() { + return new Profiler(this); + } + /** + * Tracks the time inbetween subsequent calls to this method with the same + * `id` parameter. The second call to this method will log the difference in + * milliseconds along with the message. + * @param {string} id Unique id of the profiler + * @returns {Logger} - TODO: add return description. + */ + profile(id2, ...args) { + const time = Date.now(); + if (this.profilers[id2]) { + const timeEnd = this.profilers[id2]; + delete this.profilers[id2]; + if (typeof args[args.length - 2] === "function") { + console.warn( + "Callback function no longer supported as of winston@3.0.0" + ); + args.pop(); } + const info = typeof args[args.length - 1] === "object" ? args.pop() : {}; + info.level = info.level || "info"; + info.durationMs = time - timeEnd; + info.message = info.message || id2; + return this.write(info); } + this.profilers[id2] = time; + return this; } - function getSetDayOfWeek(input) { - if (!this.isValid()) { - return input != null ? this : NaN; + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + handleExceptions(...args) { + console.warn( + "Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()" + ); + this.exceptions.handle(...args); + } + /** + * Backwards compatibility to `exceptions.handle` in winston < 3.0.0. + * @returns {undefined} + * @deprecated + */ + unhandleExceptions(...args) { + console.warn( + "Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()" + ); + this.exceptions.unhandle(...args); + } + /** + * Throw a more meaningful deprecation notice + * @throws {Error} - TODO: add throws description. + */ + cli() { + throw new Error( + [ + "Logger.cli() was removed in winston@3.0.0", + "Use a custom winston.formats.cli() instead.", + "See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md" + ].join("\n") + ); + } + /** + * Bubbles the `event` that occured on the specified `transport` up + * from this instance. + * @param {string} event - The event that occured + * @param {Object} transport - Transport on which the event occured + * @private + */ + _onEvent(event, transport) { + function transportEvent(err) { + if (event === "error" && !this.transports.includes(transport)) { + this.add(transport); + } + this.emit(event, err, transport); } - var day = get(this, "Day"); - if (input != null) { - input = parseWeekday(input, this.localeData()); - return this.add(input - day, "d"); - } else { - return day; + if (!transport["__winston" + event]) { + transport["__winston" + event] = transportEvent.bind(this); + transport.on(event, transport["__winston" + event]); + } + } + _addDefaultMeta(msg) { + if (this.defaultMeta) { + Object.assign(msg, this.defaultMeta); } } - function getSetLocaleDayOfWeek(input) { - if (!this.isValid()) { - return input != null ? this : NaN; + }; + function getLevelValue(levels, level) { + const value = levels[level]; + if (!value && value !== 0) { + return null; + } + return value; + } + Object.defineProperty(Logger2.prototype, "transports", { + configurable: false, + enumerable: true, + get() { + const { pipes } = this._readableState; + return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes; + } + }); + module2.exports = Logger2; + } +}); + +// node_modules/winston/lib/winston/create-logger.js +var require_create_logger = __commonJS({ + "node_modules/winston/lib/winston/create-logger.js"(exports2, module2) { + "use strict"; + var { LEVEL } = require_triple_beam(); + var config3 = require_config2(); + var Logger2 = require_logger(); + var debug = require_node2()("winston:create-logger"); + function isLevelEnabledFunctionName(level) { + return "is" + level.charAt(0).toUpperCase() + level.slice(1) + "Enabled"; + } + module2.exports = function(opts = {}) { + opts.levels = opts.levels || config3.npm.levels; + class DerivedLogger extends Logger2 { + /** + * Create a new class derived logger for which the levels can be attached to + * the prototype of. This is a V8 optimization that is well know to increase + * performance of prototype functions. + * @param {!Object} options - Options for the created logger. + */ + constructor(options) { + super(options); } - var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; - return input == null ? weekday : this.add(input - weekday, "d"); } - function getSetISODayOfWeek(input) { - if (!this.isValid()) { - return input != null ? this : NaN; - } - if (input != null) { - var weekday = parseIsoWeekday(input, this.localeData()); - return this.day(this.day() % 7 ? weekday : weekday - 7); - } else { - return this.day() || 7; + const logger = new DerivedLogger(opts); + Object.keys(opts.levels).forEach(function(level) { + debug('Define prototype method for "%s"', level); + if (level === "log") { + console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.'); + return; } - } - function weekdaysRegex(isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, "_weekdaysRegex")) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysStrictRegex; - } else { - return this._weekdaysRegex; + DerivedLogger.prototype[level] = function(...args) { + const self2 = this || logger; + if (args.length === 1) { + const [msg] = args; + const info = msg && msg.message && msg || { message: msg }; + info.level = info[LEVEL] = level; + self2._addDefaultMeta(info); + self2.write(info); + return this || logger; } - } else { - if (!hasOwnProp(this, "_weekdaysRegex")) { - this._weekdaysRegex = defaultWeekdaysRegex; + if (args.length === 0) { + self2.log(level, ""); + return self2; } - return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; - } + return self2.log(level, ...args); + }; + DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function() { + return (this || logger).isLevelEnabled(level); + }; + }); + return logger; + }; + } +}); + +// node_modules/winston/lib/winston/container.js +var require_container = __commonJS({ + "node_modules/winston/lib/winston/container.js"(exports2, module2) { + "use strict"; + var createLogger = require_create_logger(); + module2.exports = class Container { + /** + * Constructor function for the Container object responsible for managing a + * set of `winston.Logger` instances based on string ids. + * @param {!Object} [options={}] - Default pass-thru options for Loggers. + */ + constructor(options = {}) { + this.loggers = /* @__PURE__ */ new Map(); + this.options = options; } - function weekdaysShortRegex(isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, "_weekdaysRegex")) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysShortStrictRegex; + /** + * Retrieves a `winston.Logger` instance for the specified `id`. If an + * instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + add(id2, options) { + if (!this.loggers.has(id2)) { + options = Object.assign({}, options || this.options); + const existing = options.transports || this.options.transports; + if (existing) { + options.transports = Array.isArray(existing) ? existing.slice() : [existing]; } else { - return this._weekdaysShortRegex; - } - } else { - if (!hasOwnProp(this, "_weekdaysShortRegex")) { - this._weekdaysShortRegex = defaultWeekdaysShortRegex; + options.transports = []; } - return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; + const logger = createLogger(options); + logger.on("close", () => this._delete(id2)); + this.loggers.set(id2, logger); } + return this.loggers.get(id2); } - function weekdaysMinRegex(isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, "_weekdaysRegex")) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysMinStrictRegex; - } else { - return this._weekdaysMinRegex; - } - } else { - if (!hasOwnProp(this, "_weekdaysMinRegex")) { - this._weekdaysMinRegex = defaultWeekdaysMinRegex; - } - return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; - } + /** + * Retreives a `winston.Logger` instance for the specified `id`. If + * an instance does not exist, one is created. + * @param {!string} id - The id of the Logger to get. + * @param {?Object} [options] - Options for the Logger instance. + * @returns {Logger} - A configured Logger instance with a specified id. + */ + get(id2, options) { + return this.add(id2, options); } - function computeWeekdaysParse() { - function cmpLenRev(a, b2) { - return b2.length - a.length; + /** + * Check if the container has a logger with the id. + * @param {?string} id - The id of the Logger instance to find. + * @returns {boolean} - Boolean value indicating if this instance has a + * logger with the specified `id`. + */ + has(id2) { + return !!this.loggers.has(id2); + } + /** + * Closes a `Logger` instance with the specified `id` if it exists. + * If no `id` is supplied then all Loggers are closed. + * @param {?string} id - The id of the Logger instance to close. + * @returns {undefined} + */ + close(id2) { + if (id2) { + return this._removeLogger(id2); } - var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; - for (i = 0; i < 7; i++) { - mom = createUTC([2e3, 1]).day(i); - minp = regexEscape(this.weekdaysMin(mom, "")); - shortp = regexEscape(this.weekdaysShort(mom, "")); - longp = regexEscape(this.weekdays(mom, "")); - minPieces.push(minp); - shortPieces.push(shortp); - longPieces.push(longp); - mixedPieces.push(minp); - mixedPieces.push(shortp); - mixedPieces.push(longp); + this.loggers.forEach((val, key) => this._removeLogger(key)); + } + /** + * Remove a logger based on the id. + * @param {!string} id - The id of the logger to remove. + * @returns {undefined} + * @private + */ + _removeLogger(id2) { + if (!this.loggers.has(id2)) { + return; } - minPieces.sort(cmpLenRev); - shortPieces.sort(cmpLenRev); - longPieces.sort(cmpLenRev); - mixedPieces.sort(cmpLenRev); - this._weekdaysRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); - this._weekdaysShortRegex = this._weekdaysRegex; - this._weekdaysMinRegex = this._weekdaysRegex; - this._weekdaysStrictRegex = new RegExp( - "^(" + longPieces.join("|") + ")", - "i" - ); - this._weekdaysShortStrictRegex = new RegExp( - "^(" + shortPieces.join("|") + ")", - "i" - ); - this._weekdaysMinStrictRegex = new RegExp( - "^(" + minPieces.join("|") + ")", - "i" - ); + const logger = this.loggers.get(id2); + logger.close(); + this._delete(id2); } - function hFormat() { - return this.hours() % 12 || 12; + /** + * Deletes a `Logger` instance with the specified `id`. + * @param {!string} id - The id of the Logger instance to delete from + * container. + * @returns {undefined} + * @private + */ + _delete(id2) { + this.loggers.delete(id2); } - function kFormat() { - return this.hours() || 24; + }; + } +}); + +// node_modules/winston/lib/winston.js +var require_winston = __commonJS({ + "node_modules/winston/lib/winston.js"(exports2) { + "use strict"; + var logform = require_logform(); + var { warn } = require_common(); + exports2.version = require_package2().version; + exports2.transports = require_transports(); + exports2.config = require_config2(); + exports2.addColors = logform.levels; + exports2.format = logform.format; + exports2.createLogger = require_create_logger(); + exports2.Logger = require_logger(); + exports2.ExceptionHandler = require_exception_handler(); + exports2.RejectionHandler = require_rejection_handler(); + exports2.Container = require_container(); + exports2.Transport = require_winston_transport(); + exports2.loggers = new exports2.Container(); + var defaultLogger = exports2.createLogger(); + Object.keys(exports2.config.npm.levels).concat([ + "log", + "query", + "stream", + "add", + "remove", + "clear", + "profile", + "startTimer", + "handleExceptions", + "unhandleExceptions", + "handleRejections", + "unhandleRejections", + "configure", + "child" + ]).forEach( + (method) => exports2[method] = (...args) => defaultLogger[method](...args) + ); + Object.defineProperty(exports2, "level", { + get() { + return defaultLogger.level; + }, + set(val) { + defaultLogger.level = val; } - addFormatToken("H", ["HH", 2], 0, "hour"); - addFormatToken("h", ["hh", 2], 0, hFormat); - addFormatToken("k", ["kk", 2], 0, kFormat); - addFormatToken("hmm", 0, 0, function() { - return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2); - }); - addFormatToken("hmmss", 0, 0, function() { - return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); - }); - addFormatToken("Hmm", 0, 0, function() { - return "" + this.hours() + zeroFill(this.minutes(), 2); - }); - addFormatToken("Hmmss", 0, 0, function() { - return "" + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); - }); - function meridiem(token2, lowercase) { - addFormatToken(token2, 0, 0, function() { - return this.localeData().meridiem( - this.hours(), - this.minutes(), - lowercase - ); - }); + }); + Object.defineProperty(exports2, "exceptions", { + get() { + return defaultLogger.exceptions; } - meridiem("a", true); - meridiem("A", false); - function matchMeridiem(isStrict, locale2) { - return locale2._meridiemParse; + }); + Object.defineProperty(exports2, "rejections", { + get() { + return defaultLogger.rejections; } - addRegexToken("a", matchMeridiem); - addRegexToken("A", matchMeridiem); - addRegexToken("H", match1to2, match1to2HasZero); - addRegexToken("h", match1to2, match1to2NoLeadingZero); - addRegexToken("k", match1to2, match1to2NoLeadingZero); - addRegexToken("HH", match1to2, match2); - addRegexToken("hh", match1to2, match2); - addRegexToken("kk", match1to2, match2); - addRegexToken("hmm", match3to4); - addRegexToken("hmmss", match5to6); - addRegexToken("Hmm", match3to4); - addRegexToken("Hmmss", match5to6); - addParseToken(["H", "HH"], HOUR); - addParseToken(["k", "kk"], function(input, array, config3) { - var kInput = toInt(input); - array[HOUR] = kInput === 24 ? 0 : kInput; - }); - addParseToken(["a", "A"], function(input, array, config3) { - config3._isPm = config3._locale.isPM(input); - config3._meridiem = input; - }); - addParseToken(["h", "hh"], function(input, array, config3) { - array[HOUR] = toInt(input); - getParsingFlags(config3).bigHour = true; - }); - addParseToken("hmm", function(input, array, config3) { - var pos = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos)); - array[MINUTE] = toInt(input.substr(pos)); - getParsingFlags(config3).bigHour = true; - }); - addParseToken("hmmss", function(input, array, config3) { - var pos1 = input.length - 4, pos2 = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos1)); - array[MINUTE] = toInt(input.substr(pos1, 2)); - array[SECOND] = toInt(input.substr(pos2)); - getParsingFlags(config3).bigHour = true; - }); - addParseToken("Hmm", function(input, array, config3) { - var pos = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos)); - array[MINUTE] = toInt(input.substr(pos)); - }); - addParseToken("Hmmss", function(input, array, config3) { - var pos1 = input.length - 4, pos2 = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos1)); - array[MINUTE] = toInt(input.substr(pos1, 2)); - array[SECOND] = toInt(input.substr(pos2)); + }); + ["exitOnError"].forEach((prop) => { + Object.defineProperty(exports2, prop, { + get() { + return defaultLogger[prop]; + }, + set(val) { + defaultLogger[prop] = val; + } }); - function localeIsPM(input) { - return (input + "").toLowerCase().charAt(0) === "p"; + }); + Object.defineProperty(exports2, "default", { + get() { + return { + exceptionHandlers: defaultLogger.exceptionHandlers, + rejectionHandlers: defaultLogger.rejectionHandlers, + transports: defaultLogger.transports + }; } - var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, getSetHour = makeGetSet("Hours", true); - function localeMeridiem(hours2, minutes2, isLower) { - if (hours2 > 11) { - return isLower ? "pm" : "PM"; - } else { - return isLower ? "am" : "AM"; - } + }); + warn.deprecated(exports2, "setLevels"); + warn.forFunctions(exports2, "useFormat", ["cli"]); + warn.forProperties(exports2, "useFormat", ["padLevels", "stripColors"]); + warn.forFunctions(exports2, "deprecated", [ + "addRewriter", + "addFilter", + "clone", + "extend" + ]); + warn.forProperties(exports2, "deprecated", ["emitErrs", "levelLength"]); + } +}); + +// node_modules/object-hash/index.js +var require_object_hash = __commonJS({ + "node_modules/object-hash/index.js"(exports2, module2) { + "use strict"; + var crypto4 = __require("crypto"); + exports2 = module2.exports = objectHash; + function objectHash(object, options) { + options = applyDefaults(object, options); + return hash2(object, options); + } + exports2.sha1 = function(object) { + return objectHash(object); + }; + exports2.keys = function(object) { + return objectHash(object, { excludeValues: true, algorithm: "sha1", encoding: "hex" }); + }; + exports2.MD5 = function(object) { + return objectHash(object, { algorithm: "md5", encoding: "hex" }); + }; + exports2.keysMD5 = function(object) { + return objectHash(object, { algorithm: "md5", encoding: "hex", excludeValues: true }); + }; + var hashes = crypto4.getHashes ? crypto4.getHashes().slice() : ["sha1", "md5"]; + hashes.push("passthrough"); + var encodings = ["buffer", "hex", "binary", "base64"]; + function applyDefaults(object, sourceOptions) { + sourceOptions = sourceOptions || {}; + var options = {}; + options.algorithm = sourceOptions.algorithm || "sha1"; + options.encoding = sourceOptions.encoding || "hex"; + options.excludeValues = sourceOptions.excludeValues ? true : false; + options.algorithm = options.algorithm.toLowerCase(); + options.encoding = options.encoding.toLowerCase(); + options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; + options.respectType = sourceOptions.respectType === false ? false : true; + options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; + options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; + options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; + options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; + options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; + options.replacer = sourceOptions.replacer || void 0; + options.excludeKeys = sourceOptions.excludeKeys || void 0; + if (typeof object === "undefined") { + throw new Error("Object argument required."); } - var baseConfig = { - calendar: defaultCalendar, - longDateFormat: defaultLongDateFormat, - invalidDate: defaultInvalidDate, - ordinal: defaultOrdinal, - dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, - relativeTime: defaultRelativeTime, - months: defaultLocaleMonths, - monthsShort: defaultLocaleMonthsShort, - week: defaultLocaleWeek, - weekdays: defaultLocaleWeekdays, - weekdaysMin: defaultLocaleWeekdaysMin, - weekdaysShort: defaultLocaleWeekdaysShort, - meridiemParse: defaultLocaleMeridiemParse - }; - var locales = {}, localeFamilies = {}, globalLocale; - function commonPrefix(arr1, arr2) { - var i, minl = Math.min(arr1.length, arr2.length); - for (i = 0; i < minl; i += 1) { - if (arr1[i] !== arr2[i]) { - return i; - } + for (var i = 0; i < hashes.length; ++i) { + if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { + options.algorithm = hashes[i]; } - return minl; } - function normalizeLocale(key) { - return key ? key.toLowerCase().replace("_", "-") : key; + if (hashes.indexOf(options.algorithm) === -1) { + throw new Error('Algorithm "' + options.algorithm + '" not supported. supported values: ' + hashes.join(", ")); + } + if (encodings.indexOf(options.encoding) === -1 && options.algorithm !== "passthrough") { + throw new Error('Encoding "' + options.encoding + '" not supported. supported values: ' + encodings.join(", ")); + } + return options; + } + function isNativeFunction(f) { + if (typeof f !== "function") { + return false; + } + var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; + return exp.exec(Function.prototype.toString.call(f)) != null; + } + function hash2(object, options) { + var hashingStream; + if (options.algorithm !== "passthrough") { + hashingStream = crypto4.createHash(options.algorithm); + } else { + hashingStream = new PassThrough(); + } + if (typeof hashingStream.write === "undefined") { + hashingStream.write = hashingStream.update; + hashingStream.end = hashingStream.update; + } + var hasher = typeHasher(options, hashingStream); + hasher.dispatch(object); + if (!hashingStream.update) { + hashingStream.end(""); } - function chooseLocale(names) { - var i = 0, j2, next, locale2, split3; - while (i < names.length) { - split3 = normalizeLocale(names[i]).split("-"); - j2 = split3.length; - next = normalizeLocale(names[i + 1]); - next = next ? next.split("-") : null; - while (j2 > 0) { - locale2 = loadLocale(split3.slice(0, j2).join("-")); - if (locale2) { - return locale2; - } - if (next && next.length >= j2 && commonPrefix(split3, next) >= j2 - 1) { - break; - } - j2--; - } - i++; - } - return globalLocale; + if (hashingStream.digest) { + return hashingStream.digest(options.encoding === "buffer" ? void 0 : options.encoding); } - function isLocaleNameSane(name) { - return !!(name && name.match("^[^/\\\\]*$")); + var buf = hashingStream.read(); + if (options.encoding === "buffer") { + return buf; } - function loadLocale(name) { - var oldLocale = null, aliasedRequire; - if (locales[name] === void 0 && typeof module2 !== "undefined" && module2 && module2.exports && isLocaleNameSane(name)) { - try { - oldLocale = globalLocale._abbr; - aliasedRequire = __require; - aliasedRequire("./locale/" + name); - getSetGlobalLocale(oldLocale); - } catch (e) { - locales[name] = null; - } - } - return locales[name]; + return buf.toString(options.encoding); + } + exports2.writeToStream = function(object, options, stream4) { + if (typeof stream4 === "undefined") { + stream4 = options; + options = {}; } - function getSetGlobalLocale(key, values) { - var data; - if (key) { - if (isUndefined2(values)) { - data = getLocale(key); + options = applyDefaults(object, options); + return typeHasher(options, stream4).dispatch(object); + }; + function typeHasher(options, writeTo, context) { + context = context || []; + var write = function(str) { + if (writeTo.update) { + return writeTo.update(str, "utf8"); + } else { + return writeTo.write(str, "utf8"); + } + }; + return { + dispatch: function(value) { + if (options.replacer) { + value = options.replacer(value); + } + var type = typeof value; + if (value === null) { + type = "null"; + } + return this["_" + type](value); + }, + _object: function(object) { + var pattern = /\[object (.*)\]/i; + var objString = Object.prototype.toString.call(object); + var objType = pattern.exec(objString); + if (!objType) { + objType = "unknown:[" + objString + "]"; } else { - data = defineLocale(key, values); + objType = objType[1]; } - if (data) { - globalLocale = data; + objType = objType.toLowerCase(); + var objectNumber = null; + if ((objectNumber = context.indexOf(object)) >= 0) { + return this.dispatch("[CIRCULAR:" + objectNumber + "]"); } else { - if (typeof console !== "undefined" && console.warn) { - console.warn( - "Locale " + key + " not found. Did you forget to load it?" - ); - } + context.push(object); } - } - return globalLocale._abbr; - } - function defineLocale(name, config3) { - if (config3 !== null) { - var locale2, parentConfig = baseConfig; - config3.abbr = name; - if (locales[name] != null) { - deprecateSimple( - "defineLocaleOverride", - "use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info." - ); - parentConfig = locales[name]._config; - } else if (config3.parentLocale != null) { - if (locales[config3.parentLocale] != null) { - parentConfig = locales[config3.parentLocale]._config; + if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) { + write("buffer:"); + return write(object); + } + if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") { + if (this["_" + objType]) { + this["_" + objType](object); + } else if (options.ignoreUnknown) { + return write("[" + objType + "]"); } else { - locale2 = loadLocale(config3.parentLocale); - if (locale2 != null) { - parentConfig = locale2._config; - } else { - if (!localeFamilies[config3.parentLocale]) { - localeFamilies[config3.parentLocale] = []; - } - localeFamilies[config3.parentLocale].push({ - name, - config: config3 - }); - return null; - } + throw new Error('Unknown object type "' + objType + '"'); } - } - locales[name] = new Locale(mergeConfigs(parentConfig, config3)); - if (localeFamilies[name]) { - localeFamilies[name].forEach(function(x2) { - defineLocale(x2.name, x2.config); - }); - } - getSetGlobalLocale(name); - return locales[name]; - } else { - delete locales[name]; - return null; - } - } - function updateLocale(name, config3) { - if (config3 != null) { - var locale2, tmpLocale, parentConfig = baseConfig; - if (locales[name] != null && locales[name].parentLocale != null) { - locales[name].set(mergeConfigs(locales[name]._config, config3)); } else { - tmpLocale = loadLocale(name); - if (tmpLocale != null) { - parentConfig = tmpLocale._config; + var keys = Object.keys(object); + if (options.unorderedObjects) { + keys = keys.sort(); } - config3 = mergeConfigs(parentConfig, config3); - if (tmpLocale == null) { - config3.abbr = name; + if (options.respectType !== false && !isNativeFunction(object)) { + keys.splice(0, 0, "prototype", "__proto__", "constructor"); } - locale2 = new Locale(config3); - locale2.parentLocale = locales[name]; - locales[name] = locale2; - } - getSetGlobalLocale(name); - } else { - if (locales[name] != null) { - if (locales[name].parentLocale != null) { - locales[name] = locales[name].parentLocale; - if (name === getSetGlobalLocale()) { - getSetGlobalLocale(name); - } - } else if (locales[name] != null) { - delete locales[name]; + if (options.excludeKeys) { + keys = keys.filter(function(key) { + return !options.excludeKeys(key); + }); } + write("object:" + keys.length + ":"); + var self2 = this; + return keys.forEach(function(key) { + self2.dispatch(key); + write(":"); + if (!options.excludeValues) { + self2.dispatch(object[key]); + } + write(","); + }); } - } - return locales[name]; - } - function getLocale(key) { - var locale2; - if (key && key._locale && key._locale._abbr) { - key = key._locale._abbr; - } - if (!key) { - return globalLocale; - } - if (!isArray2(key)) { - locale2 = loadLocale(key); - if (locale2) { - return locale2; + }, + _array: function(arr, unordered) { + unordered = typeof unordered !== "undefined" ? unordered : options.unorderedArrays !== false; + var self2 = this; + write("array:" + arr.length + ":"); + if (!unordered || arr.length <= 1) { + return arr.forEach(function(entry) { + return self2.dispatch(entry); + }); } - key = [key]; - } - return chooseLocale(key); - } - function listLocales() { - return keys(locales); - } - function checkOverflow(m2) { - var overflow, a = m2._a; - if (a && getParsingFlags(m2).overflow === -2) { - overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1; - if (getParsingFlags(m2)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { - overflow = DATE; + var contextAdditions = []; + var entries = arr.map(function(entry) { + var strm = new PassThrough(); + var localContext = context.slice(); + var hasher = typeHasher(options, strm, localContext); + hasher.dispatch(entry); + contextAdditions = contextAdditions.concat(localContext.slice(context.length)); + return strm.read().toString(); + }); + context = context.concat(contextAdditions); + entries.sort(); + return this._array(entries, false); + }, + _date: function(date) { + return write("date:" + date.toJSON()); + }, + _symbol: function(sym) { + return write("symbol:" + sym.toString()); + }, + _error: function(err) { + return write("error:" + err.toString()); + }, + _boolean: function(bool) { + return write("bool:" + bool.toString()); + }, + _string: function(string) { + write("string:" + string.length + ":"); + write(string.toString()); + }, + _function: function(fn2) { + write("fn:"); + if (isNativeFunction(fn2)) { + this.dispatch("[native]"); + } else { + this.dispatch(fn2.toString()); } - if (getParsingFlags(m2)._overflowWeeks && overflow === -1) { - overflow = WEEK; + if (options.respectFunctionNames !== false) { + this.dispatch("function-name:" + String(fn2.name)); } - if (getParsingFlags(m2)._overflowWeekday && overflow === -1) { - overflow = WEEKDAY; + if (options.respectFunctionProperties) { + this._object(fn2); } - getParsingFlags(m2).overflow = overflow; + }, + _number: function(number) { + return write("number:" + number.toString()); + }, + _xml: function(xml) { + return write("xml:" + xml.toString()); + }, + _null: function() { + return write("Null"); + }, + _undefined: function() { + return write("Undefined"); + }, + _regexp: function(regex) { + return write("regex:" + regex.toString()); + }, + _uint8array: function(arr) { + write("uint8array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint8clampedarray: function(arr) { + write("uint8clampedarray:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int8array: function(arr) { + write("int8array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint16array: function(arr) { + write("uint16array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int16array: function(arr) { + write("int16array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint32array: function(arr) { + write("uint32array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int32array: function(arr) { + write("int32array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float32array: function(arr) { + write("float32array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float64array: function(arr) { + write("float64array:"); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _arraybuffer: function(arr) { + write("arraybuffer:"); + return this.dispatch(new Uint8Array(arr)); + }, + _url: function(url2) { + return write("url:" + url2.toString(), "utf8"); + }, + _map: function(map) { + write("map:"); + var arr = Array.from(map); + return this._array(arr, options.unorderedSets !== false); + }, + _set: function(set) { + write("set:"); + var arr = Array.from(set); + return this._array(arr, options.unorderedSets !== false); + }, + _file: function(file) { + write("file:"); + return this.dispatch([file.name, file.size, file.type, file.lastModfied]); + }, + _blob: function() { + if (options.ignoreUnknown) { + return write("[blob]"); + } + throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n'); + }, + _domwindow: function() { + return write("domwindow"); + }, + _bigint: function(number) { + return write("bigint:" + number.toString()); + }, + /* Node.js standard native objects */ + _process: function() { + return write("process"); + }, + _timer: function() { + return write("timer"); + }, + _pipe: function() { + return write("pipe"); + }, + _tcp: function() { + return write("tcp"); + }, + _udp: function() { + return write("udp"); + }, + _tty: function() { + return write("tty"); + }, + _statwatcher: function() { + return write("statwatcher"); + }, + _securecontext: function() { + return write("securecontext"); + }, + _connection: function() { + return write("connection"); + }, + _zlib: function() { + return write("zlib"); + }, + _context: function() { + return write("context"); + }, + _nodescript: function() { + return write("nodescript"); + }, + _httpparser: function() { + return write("httpparser"); + }, + _dataview: function() { + return write("dataview"); + }, + _signal: function() { + return write("signal"); + }, + _fsevent: function() { + return write("fsevent"); + }, + _tlswrap: function() { + return write("tlswrap"); } - return m2; - } - var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, isoDates = [ - ["YYYYYY-MM-DD", /[+-]\d{6}-\d\d-\d\d/], - ["YYYY-MM-DD", /\d{4}-\d\d-\d\d/], - ["GGGG-[W]WW-E", /\d{4}-W\d\d-\d/], - ["GGGG-[W]WW", /\d{4}-W\d\d/, false], - ["YYYY-DDD", /\d{4}-\d{3}/], - ["YYYY-MM", /\d{4}-\d\d/, false], - ["YYYYYYMMDD", /[+-]\d{10}/], - ["YYYYMMDD", /\d{8}/], - ["GGGG[W]WWE", /\d{4}W\d{3}/], - ["GGGG[W]WW", /\d{4}W\d{2}/, false], - ["YYYYDDD", /\d{7}/], - ["YYYYMM", /\d{6}/, false], - ["YYYY", /\d{4}/, false] - ], isoTimes = [ - ["HH:mm:ss.SSSS", /\d\d:\d\d:\d\d\.\d+/], - ["HH:mm:ss,SSSS", /\d\d:\d\d:\d\d,\d+/], - ["HH:mm:ss", /\d\d:\d\d:\d\d/], - ["HH:mm", /\d\d:\d\d/], - ["HHmmss.SSSS", /\d\d\d\d\d\d\.\d+/], - ["HHmmss,SSSS", /\d\d\d\d\d\d,\d+/], - ["HHmmss", /\d\d\d\d\d\d/], - ["HHmm", /\d\d\d\d/], - ["HH", /\d\d/] - ], aspNetJsonRegex = /^\/?Date\((-?\d+)/i, rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, obsOffsets = { - UT: 0, - GMT: 0, - EDT: -4 * 60, - EST: -5 * 60, - CDT: -5 * 60, - CST: -6 * 60, - MDT: -6 * 60, - MST: -7 * 60, - PDT: -7 * 60, - PST: -8 * 60 }; - function configFromISO(config3) { - var i, l, string = config3._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat, isoDatesLen = isoDates.length, isoTimesLen = isoTimes.length; - if (match) { - getParsingFlags(config3).iso = true; - for (i = 0, l = isoDatesLen; i < l; i++) { - if (isoDates[i][1].exec(match[1])) { - dateFormat = isoDates[i][0]; - allowTime = isoDates[i][2] !== false; - break; - } - } - if (dateFormat == null) { - config3._isValid = false; - return; - } - if (match[3]) { - for (i = 0, l = isoTimesLen; i < l; i++) { - if (isoTimes[i][1].exec(match[3])) { - timeFormat = (match[2] || " ") + isoTimes[i][0]; - break; - } - } - if (timeFormat == null) { - config3._isValid = false; - return; - } - } - if (!allowTime && timeFormat != null) { - config3._isValid = false; - return; - } - if (match[4]) { - if (tzRegex.exec(match[4])) { - tzFormat = "Z"; - } else { - config3._isValid = false; - return; + } + function PassThrough() { + return { + buf: "", + write: function(b2) { + this.buf += b2; + }, + end: function(b2) { + this.buf += b2; + }, + read: function() { + return this.buf; + } + }; + } + } +}); + +// node_modules/moment/moment.js +var require_moment = __commonJS({ + "node_modules/moment/moment.js"(exports2, module2) { + (function(global2, factory) { + typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global2.moment = factory(); + })(exports2, function() { + "use strict"; + var hookCallback; + function hooks() { + return hookCallback.apply(null, arguments); + } + function setHookCallback(callback) { + hookCallback = callback; + } + function isArray2(input) { + return input instanceof Array || Object.prototype.toString.call(input) === "[object Array]"; + } + function isObject2(input) { + return input != null && Object.prototype.toString.call(input) === "[object Object]"; + } + function hasOwnProp(a, b2) { + return Object.prototype.hasOwnProperty.call(a, b2); + } + function isObjectEmpty(obj) { + if (Object.getOwnPropertyNames) { + return Object.getOwnPropertyNames(obj).length === 0; + } else { + var k2; + for (k2 in obj) { + if (hasOwnProp(obj, k2)) { + return false; } } - config3._f = dateFormat + (timeFormat || "") + (tzFormat || ""); - configFromStringAndFormat(config3); - } else { - config3._isValid = false; + return true; } } - function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { - var result = [ - untruncateYear(yearStr), - defaultLocaleMonthsShort.indexOf(monthStr), - parseInt(dayStr, 10), - parseInt(hourStr, 10), - parseInt(minuteStr, 10) - ]; - if (secondStr) { - result.push(parseInt(secondStr, 10)); - } - return result; + function isUndefined2(input) { + return input === void 0; } - function untruncateYear(yearStr) { - var year = parseInt(yearStr, 10); - if (year <= 49) { - return 2e3 + year; - } else if (year <= 999) { - return 1900 + year; - } - return year; + function isNumber2(input) { + return typeof input === "number" || Object.prototype.toString.call(input) === "[object Number]"; } - function preprocessRFC2822(s) { - return s.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").replace(/^\s\s*/, "").replace(/\s\s*$/, ""); + function isDate2(input) { + return input instanceof Date || Object.prototype.toString.call(input) === "[object Date]"; } - function checkWeekday(weekdayStr, parsedInput, config3) { - if (weekdayStr) { - var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), weekdayActual = new Date( - parsedInput[0], - parsedInput[1], - parsedInput[2] - ).getDay(); - if (weekdayProvided !== weekdayActual) { - getParsingFlags(config3).weekdayMismatch = true; - config3._isValid = false; - return false; + function map(arr, fn2) { + var res = [], i, arrLen = arr.length; + for (i = 0; i < arrLen; ++i) { + res.push(fn2(arr[i], i)); + } + return res; + } + function extend2(a, b2) { + for (var i in b2) { + if (hasOwnProp(b2, i)) { + a[i] = b2[i]; } } - return true; + if (hasOwnProp(b2, "toString")) { + a.toString = b2.toString; + } + if (hasOwnProp(b2, "valueOf")) { + a.valueOf = b2.valueOf; + } + return a; } - function calculateOffset(obsOffset, militaryOffset, numOffset) { - if (obsOffset) { - return obsOffsets[obsOffset]; - } else if (militaryOffset) { - return 0; - } else { - var hm2 = parseInt(numOffset, 10), m2 = hm2 % 100, h = (hm2 - m2) / 100; - return h * 60 + m2; + function createUTC(input, format2, locale2, strict) { + return createLocalOrUTC(input, format2, locale2, strict, true).utc(); + } + function defaultParsingFlags() { + return { + empty: false, + unusedTokens: [], + unusedInput: [], + overflow: -2, + charsLeftOver: 0, + nullInput: false, + invalidEra: null, + invalidMonth: null, + invalidFormat: false, + userInvalidated: false, + iso: false, + parsedDateParts: [], + era: null, + meridiem: null, + rfc2822: false, + weekdayMismatch: false + }; + } + function getParsingFlags(m2) { + if (m2._pf == null) { + m2._pf = defaultParsingFlags(); } + return m2._pf; } - function configFromRFC2822(config3) { - var match = rfc2822.exec(preprocessRFC2822(config3._i)), parsedArray; - if (match) { - parsedArray = extractFromRFC2822Strings( - match[4], - match[3], - match[2], - match[5], - match[6], - match[7] - ); - if (!checkWeekday(match[1], parsedArray, config3)) { - return; + var some; + if (Array.prototype.some) { + some = Array.prototype.some; + } else { + some = function(fun) { + var t = Object(this), len = t.length >>> 0, i; + for (i = 0; i < len; i++) { + if (i in t && fun.call(this, t[i], i, t)) { + return true; + } } - config3._a = parsedArray; - config3._tzm = calculateOffset(match[8], match[9], match[10]); - config3._d = createUTCDate.apply(null, config3._a); - config3._d.setUTCMinutes(config3._d.getUTCMinutes() - config3._tzm); - getParsingFlags(config3).rfc2822 = true; - } else { - config3._isValid = false; - } + return false; + }; } - function configFromString(config3) { - var matched = aspNetJsonRegex.exec(config3._i); - if (matched !== null) { - config3._d = /* @__PURE__ */ new Date(+matched[1]); - return; - } - configFromISO(config3); - if (config3._isValid === false) { - delete config3._isValid; - } else { - return; + function isValid(m2) { + var flags = null, parsedParts = false, isNowValid = m2._d && !isNaN(m2._d.getTime()); + if (isNowValid) { + flags = getParsingFlags(m2); + parsedParts = some.call(flags.parsedDateParts, function(i) { + return i != null; + }); + isNowValid = flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts); + if (m2._strict) { + isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === void 0; + } } - configFromRFC2822(config3); - if (config3._isValid === false) { - delete config3._isValid; + if (Object.isFrozen == null || !Object.isFrozen(m2)) { + m2._isValid = isNowValid; } else { - return; + return isNowValid; } - if (config3._strict) { - config3._isValid = false; + return m2._isValid; + } + function createInvalid(flags) { + var m2 = createUTC(NaN); + if (flags != null) { + extend2(getParsingFlags(m2), flags); } else { - hooks.createFromInputFallback(config3); + getParsingFlags(m2).userInvalidated = true; } + return m2; } - hooks.createFromInputFallback = deprecate( - "value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.", - function(config3) { - config3._d = /* @__PURE__ */ new Date(config3._i + (config3._useUTC ? " UTC" : "")); + var momentProperties = hooks.momentProperties = [], updateInProgress = false; + function copyConfig(to3, from6) { + var i, prop, val, momentPropertiesLen = momentProperties.length; + if (!isUndefined2(from6._isAMomentObject)) { + to3._isAMomentObject = from6._isAMomentObject; } - ); - function defaults2(a, b2, c) { - if (a != null) { - return a; + if (!isUndefined2(from6._i)) { + to3._i = from6._i; } - if (b2 != null) { - return b2; + if (!isUndefined2(from6._f)) { + to3._f = from6._f; } - return c; - } - function currentDateArray(config3) { - var nowValue = new Date(hooks.now()); - if (config3._useUTC) { - return [ - nowValue.getUTCFullYear(), - nowValue.getUTCMonth(), - nowValue.getUTCDate() - ]; + if (!isUndefined2(from6._l)) { + to3._l = from6._l; } - return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; - } - function configFromArray(config3) { - var i, date, input = [], currentDate, expectedWeekday, yearToUse; - if (config3._d) { - return; + if (!isUndefined2(from6._strict)) { + to3._strict = from6._strict; } - currentDate = currentDateArray(config3); - if (config3._w && config3._a[DATE] == null && config3._a[MONTH] == null) { - dayOfYearFromWeekInfo(config3); + if (!isUndefined2(from6._tzm)) { + to3._tzm = from6._tzm; } - if (config3._dayOfYear != null) { - yearToUse = defaults2(config3._a[YEAR], currentDate[YEAR]); - if (config3._dayOfYear > daysInYear(yearToUse) || config3._dayOfYear === 0) { - getParsingFlags(config3)._overflowDayOfYear = true; - } - date = createUTCDate(yearToUse, 0, config3._dayOfYear); - config3._a[MONTH] = date.getUTCMonth(); - config3._a[DATE] = date.getUTCDate(); + if (!isUndefined2(from6._isUTC)) { + to3._isUTC = from6._isUTC; } - for (i = 0; i < 3 && config3._a[i] == null; ++i) { - config3._a[i] = input[i] = currentDate[i]; + if (!isUndefined2(from6._offset)) { + to3._offset = from6._offset; } - for (; i < 7; i++) { - config3._a[i] = input[i] = config3._a[i] == null ? i === 2 ? 1 : 0 : config3._a[i]; + if (!isUndefined2(from6._pf)) { + to3._pf = getParsingFlags(from6); } - if (config3._a[HOUR] === 24 && config3._a[MINUTE] === 0 && config3._a[SECOND] === 0 && config3._a[MILLISECOND] === 0) { - config3._nextDay = true; - config3._a[HOUR] = 0; + if (!isUndefined2(from6._locale)) { + to3._locale = from6._locale; } - config3._d = (config3._useUTC ? createUTCDate : createDate).apply( - null, - input - ); - expectedWeekday = config3._useUTC ? config3._d.getUTCDay() : config3._d.getDay(); - if (config3._tzm != null) { - config3._d.setUTCMinutes(config3._d.getUTCMinutes() - config3._tzm); + if (momentPropertiesLen > 0) { + for (i = 0; i < momentPropertiesLen; i++) { + prop = momentProperties[i]; + val = from6[prop]; + if (!isUndefined2(val)) { + to3[prop] = val; + } + } } - if (config3._nextDay) { - config3._a[HOUR] = 24; + return to3; + } + function Moment(config3) { + copyConfig(this, config3); + this._d = new Date(config3._d != null ? config3._d.getTime() : NaN); + if (!this.isValid()) { + this._d = /* @__PURE__ */ new Date(NaN); } - if (config3._w && typeof config3._w.d !== "undefined" && config3._w.d !== expectedWeekday) { - getParsingFlags(config3).weekdayMismatch = true; + if (updateInProgress === false) { + updateInProgress = true; + hooks.updateOffset(this); + updateInProgress = false; } } - function dayOfYearFromWeekInfo(config3) { - var w2, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; - w2 = config3._w; - if (w2.GG != null || w2.W != null || w2.E != null) { - dow = 1; - doy = 4; - weekYear = defaults2( - w2.GG, - config3._a[YEAR], - weekOfYear(createLocal(), 1, 4).year - ); - week = defaults2(w2.W, 1); - weekday = defaults2(w2.E, 1); - if (weekday < 1 || weekday > 7) { - weekdayOverflow = true; + function isMoment(obj) { + return obj instanceof Moment || obj != null && obj._isAMomentObject != null; + } + function warn(msg) { + if (hooks.suppressDeprecationWarnings === false && typeof console !== "undefined" && console.warn) { + console.warn("Deprecation warning: " + msg); + } + } + function deprecate(msg, fn2) { + var firstTime = true; + return extend2(function() { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(null, msg); } - } else { - dow = config3._locale._week.dow; - doy = config3._locale._week.doy; - curWeek = weekOfYear(createLocal(), dow, doy); - weekYear = defaults2(w2.gg, config3._a[YEAR], curWeek.year); - week = defaults2(w2.w, curWeek.week); - if (w2.d != null) { - weekday = w2.d; - if (weekday < 0 || weekday > 6) { - weekdayOverflow = true; + if (firstTime) { + var args = [], arg, i, key, argLen = arguments.length; + for (i = 0; i < argLen; i++) { + arg = ""; + if (typeof arguments[i] === "object") { + arg += "\n[" + i + "] "; + for (key in arguments[0]) { + if (hasOwnProp(arguments[0], key)) { + arg += key + ": " + arguments[0][key] + ", "; + } + } + arg = arg.slice(0, -2); + } else { + arg = arguments[i]; + } + args.push(arg); } - } else if (w2.e != null) { - weekday = w2.e + dow; - if (w2.e < 0 || w2.e > 6) { - weekdayOverflow = true; + warn( + msg + "\nArguments: " + Array.prototype.slice.call(args).join("") + "\n" + new Error().stack + ); + firstTime = false; + } + return fn2.apply(this, arguments); + }, fn2); + } + var deprecations = {}; + function deprecateSimple(name, msg) { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(name, msg); + } + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } + } + hooks.suppressDeprecationWarnings = false; + hooks.deprecationHandler = null; + function isFunction2(input) { + return typeof Function !== "undefined" && input instanceof Function || Object.prototype.toString.call(input) === "[object Function]"; + } + function set(config3) { + var prop, i; + for (i in config3) { + if (hasOwnProp(config3, i)) { + prop = config3[i]; + if (isFunction2(prop)) { + this[i] = prop; + } else { + this["_" + i] = prop; } - } else { - weekday = dow; } } - if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { - getParsingFlags(config3)._overflowWeeks = true; - } else if (weekdayOverflow != null) { - getParsingFlags(config3)._overflowWeekday = true; - } else { - temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); - config3._a[YEAR] = temp.year; - config3._dayOfYear = temp.dayOfYear; + this._config = config3; + this._dayOfMonthOrdinalParseLenient = new RegExp( + (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + "|" + /\d{1,2}/.source + ); + } + function mergeConfigs(parentConfig, childConfig) { + var res = extend2({}, parentConfig), prop; + for (prop in childConfig) { + if (hasOwnProp(childConfig, prop)) { + if (isObject2(parentConfig[prop]) && isObject2(childConfig[prop])) { + res[prop] = {}; + extend2(res[prop], parentConfig[prop]); + extend2(res[prop], childConfig[prop]); + } else if (childConfig[prop] != null) { + res[prop] = childConfig[prop]; + } else { + delete res[prop]; + } + } + } + for (prop in parentConfig) { + if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject2(parentConfig[prop])) { + res[prop] = extend2({}, res[prop]); + } } + return res; } - hooks.ISO_8601 = function() { - }; - hooks.RFC_2822 = function() { + function Locale(config3) { + if (config3 != null) { + this.set(config3); + } + } + var keys; + if (Object.keys) { + keys = Object.keys; + } else { + keys = function(obj) { + var i, res = []; + for (i in obj) { + if (hasOwnProp(obj, i)) { + res.push(i); + } + } + return res; + }; + } + var defaultCalendar = { + sameDay: "[Today at] LT", + nextDay: "[Tomorrow at] LT", + nextWeek: "dddd [at] LT", + lastDay: "[Yesterday at] LT", + lastWeek: "[Last] dddd [at] LT", + sameElse: "L" }; - function configFromStringAndFormat(config3) { - if (config3._f === hooks.ISO_8601) { - configFromISO(config3); - return; + function calendar(key, mom, now2) { + var output = this._calendar[key] || this._calendar["sameElse"]; + return isFunction2(output) ? output.call(mom, now2) : output; + } + function zeroFill(number, targetLength, forceSign) { + var absNumber = "" + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign3 = number >= 0; + return (sign3 ? forceSign ? "+" : "" : "-") + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; + } + var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, formatFunctions = {}, formatTokenFunctions = {}; + function addFormatToken(token2, padded, ordinal2, callback) { + var func = callback; + if (typeof callback === "string") { + func = function() { + return this[callback](); + }; } - if (config3._f === hooks.RFC_2822) { - configFromRFC2822(config3); - return; + if (token2) { + formatTokenFunctions[token2] = func; } - config3._a = []; - getParsingFlags(config3).empty = true; - var string = "" + config3._i, i, parsedInput, tokens2, token2, skipped, stringLength = string.length, totalParsedInputLength = 0, era, tokenLen; - tokens2 = expandFormat(config3._f, config3._locale).match(formattingTokens) || []; - tokenLen = tokens2.length; - for (i = 0; i < tokenLen; i++) { - token2 = tokens2[i]; - parsedInput = (string.match(getParseRegexForToken(token2, config3)) || [])[0]; - if (parsedInput) { - skipped = string.substr(0, string.indexOf(parsedInput)); - if (skipped.length > 0) { - getParsingFlags(config3).unusedInput.push(skipped); - } - string = string.slice( - string.indexOf(parsedInput) + parsedInput.length + if (padded) { + formatTokenFunctions[padded[0]] = function() { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal2) { + formatTokenFunctions[ordinal2] = function() { + return this.localeData().ordinal( + func.apply(this, arguments), + token2 ); - totalParsedInputLength += parsedInput.length; - } - if (formatTokenFunctions[token2]) { - if (parsedInput) { - getParsingFlags(config3).empty = false; - } else { - getParsingFlags(config3).unusedTokens.push(token2); - } - addTimeToArrayFromToken(token2, parsedInput, config3); - } else if (config3._strict && !parsedInput) { - getParsingFlags(config3).unusedTokens.push(token2); + }; + } + } + function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ""); + } + return input.replace(/\\/g, ""); + } + function makeFormatFunction(format2) { + var array = format2.match(formattingTokens), i, length; + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); } } - getParsingFlags(config3).charsLeftOver = stringLength - totalParsedInputLength; - if (string.length > 0) { - getParsingFlags(config3).unusedInput.push(string); + return function(mom) { + var output = "", i2; + for (i2 = 0; i2 < length; i2++) { + output += isFunction2(array[i2]) ? array[i2].call(mom, format2) : array[i2]; + } + return output; + }; + } + function formatMoment(m2, format2) { + if (!m2.isValid()) { + return m2.localeData().invalidDate(); } - if (config3._a[HOUR] <= 12 && getParsingFlags(config3).bigHour === true && config3._a[HOUR] > 0) { - getParsingFlags(config3).bigHour = void 0; + format2 = expandFormat(format2, m2.localeData()); + formatFunctions[format2] = formatFunctions[format2] || makeFormatFunction(format2); + return formatFunctions[format2](m2); + } + function expandFormat(format2, locale2) { + var i = 5; + function replaceLongDateFormatTokens(input) { + return locale2.longDateFormat(input) || input; } - getParsingFlags(config3).parsedDateParts = config3._a.slice(0); - getParsingFlags(config3).meridiem = config3._meridiem; - config3._a[HOUR] = meridiemFixWrap( - config3._locale, - config3._a[HOUR], - config3._meridiem - ); - era = getParsingFlags(config3).era; - if (era !== null) { - config3._a[YEAR] = config3._locale.erasConvertYear(era, config3._a[YEAR]); + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format2)) { + format2 = format2.replace( + localFormattingTokens, + replaceLongDateFormatTokens + ); + localFormattingTokens.lastIndex = 0; + i -= 1; } - configFromArray(config3); - checkOverflow(config3); + return format2; } - function meridiemFixWrap(locale2, hour, meridiem2) { - var isPm; - if (meridiem2 == null) { - return hour; + var defaultLongDateFormat = { + LTS: "h:mm:ss A", + LT: "h:mm A", + L: "MM/DD/YYYY", + LL: "MMMM D, YYYY", + LLL: "MMMM D, YYYY h:mm A", + LLLL: "dddd, MMMM D, YYYY h:mm A" + }; + function longDateFormat(key) { + var format2 = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()]; + if (format2 || !formatUpper) { + return format2; } - if (locale2.meridiemHour != null) { - return locale2.meridiemHour(hour, meridiem2); - } else if (locale2.isPM != null) { - isPm = locale2.isPM(meridiem2); - if (isPm && hour < 12) { - hour += 12; + this._longDateFormat[key] = formatUpper.match(formattingTokens).map(function(tok) { + if (tok === "MMMM" || tok === "MM" || tok === "DD" || tok === "dddd") { + return tok.slice(1); } - if (!isPm && hour === 12) { - hour = 0; + return tok; + }).join(""); + return this._longDateFormat[key]; + } + var defaultInvalidDate = "Invalid date"; + function invalidDate() { + return this._invalidDate; + } + var defaultOrdinal = "%d", defaultDayOfMonthOrdinalParse = /\d{1,2}/; + function ordinal(number) { + return this._ordinal.replace("%d", number); + } + var defaultRelativeTime = { + future: "in %s", + past: "%s ago", + s: "a few seconds", + ss: "%d seconds", + m: "a minute", + mm: "%d minutes", + h: "an hour", + hh: "%d hours", + d: "a day", + dd: "%d days", + w: "a week", + ww: "%d weeks", + M: "a month", + MM: "%d months", + y: "a year", + yy: "%d years" + }; + function relativeTime(number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return isFunction2(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); + } + function pastFuture(diff2, output) { + var format2 = this._relativeTime[diff2 > 0 ? "future" : "past"]; + return isFunction2(format2) ? format2(output) : format2.replace(/%s/i, output); + } + var aliases = { + D: "date", + dates: "date", + date: "date", + d: "day", + days: "day", + day: "day", + e: "weekday", + weekdays: "weekday", + weekday: "weekday", + E: "isoWeekday", + isoweekdays: "isoWeekday", + isoweekday: "isoWeekday", + DDD: "dayOfYear", + dayofyears: "dayOfYear", + dayofyear: "dayOfYear", + h: "hour", + hours: "hour", + hour: "hour", + ms: "millisecond", + milliseconds: "millisecond", + millisecond: "millisecond", + m: "minute", + minutes: "minute", + minute: "minute", + M: "month", + months: "month", + month: "month", + Q: "quarter", + quarters: "quarter", + quarter: "quarter", + s: "second", + seconds: "second", + second: "second", + gg: "weekYear", + weekyears: "weekYear", + weekyear: "weekYear", + GG: "isoWeekYear", + isoweekyears: "isoWeekYear", + isoweekyear: "isoWeekYear", + w: "week", + weeks: "week", + week: "week", + W: "isoWeek", + isoweeks: "isoWeek", + isoweek: "isoWeek", + y: "year", + years: "year", + year: "year" + }; + function normalizeUnits(units) { + return typeof units === "string" ? aliases[units] || aliases[units.toLowerCase()] : void 0; + } + function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, normalizedProp, prop; + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } } - return hour; - } else { - return hour; } + return normalizedInput; } - function configFromStringAndArray(config3) { - var tempConfig, bestMoment, scoreToBeat, i, currentScore, validFormatFound, bestFormatIsValid = false, configfLen = config3._f.length; - if (configfLen === 0) { - getParsingFlags(config3).invalidFormat = true; - config3._d = /* @__PURE__ */ new Date(NaN); - return; - } - for (i = 0; i < configfLen; i++) { - currentScore = 0; - validFormatFound = false; - tempConfig = copyConfig({}, config3); - if (config3._useUTC != null) { - tempConfig._useUTC = config3._useUTC; - } - tempConfig._f = config3._f[i]; - configFromStringAndFormat(tempConfig); - if (isValid(tempConfig)) { - validFormatFound = true; - } - currentScore += getParsingFlags(tempConfig).charsLeftOver; - currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; - getParsingFlags(tempConfig).score = currentScore; - if (!bestFormatIsValid) { - if (scoreToBeat == null || currentScore < scoreToBeat || validFormatFound) { - scoreToBeat = currentScore; - bestMoment = tempConfig; - if (validFormatFound) { - bestFormatIsValid = true; - } - } - } else { - if (currentScore < scoreToBeat) { - scoreToBeat = currentScore; - bestMoment = tempConfig; - } + var priorities = { + date: 9, + day: 11, + weekday: 11, + isoWeekday: 11, + dayOfYear: 4, + hour: 13, + millisecond: 16, + minute: 14, + month: 8, + quarter: 7, + second: 15, + weekYear: 1, + isoWeekYear: 1, + week: 5, + isoWeek: 5, + year: 1 + }; + function getPrioritizedUnits(unitsObj) { + var units = [], u; + for (u in unitsObj) { + if (hasOwnProp(unitsObj, u)) { + units.push({ unit: u, priority: priorities[u] }); } } - extend2(config3, bestMoment || tempConfig); + units.sort(function(a, b2) { + return a.priority - b2.priority; + }); + return units; } - function configFromObject(config3) { - if (config3._d) { - return; + var match1 = /\d/, match2 = /\d\d/, match3 = /\d{3}/, match4 = /\d{4}/, match6 = /[+-]?\d{6}/, match1to2 = /\d\d?/, match3to4 = /\d\d\d\d?/, match5to6 = /\d\d\d\d\d\d?/, match1to3 = /\d{1,3}/, match1to4 = /\d{1,4}/, match1to6 = /[+-]?\d{1,6}/, matchUnsigned = /\d+/, matchSigned = /[+-]?\d+/, matchOffset = /Z|[+-]\d\d:?\d\d/gi, matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, match1to2NoLeadingZero = /^[1-9]\d?/, match1to2HasZero = /^([1-9]\d|\d)/, regexes; + regexes = {}; + function addRegexToken(token2, regex, strictRegex) { + regexes[token2] = isFunction2(regex) ? regex : function(isStrict, localeData2) { + return isStrict && strictRegex ? strictRegex : regex; + }; + } + function getParseRegexForToken(token2, config3) { + if (!hasOwnProp(regexes, token2)) { + return new RegExp(unescapeFormat(token2)); } - var i = normalizeObjectUnits(config3._i), dayOrDate = i.day === void 0 ? i.date : i.day; - config3._a = map( - [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], - function(obj) { - return obj && parseInt(obj, 10); - } + return regexes[token2](config3._strict, config3._locale); + } + function unescapeFormat(s) { + return regexEscape( + s.replace("\\", "").replace( + /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, + function(matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + } + ) ); - configFromArray(config3); } - function createFromConfig(config3) { - var res = new Moment(checkOverflow(prepareConfig(config3))); - if (res._nextDay) { - res.add(1, "d"); - res._nextDay = void 0; - } - return res; + function regexEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); } - function prepareConfig(config3) { - var input = config3._i, format2 = config3._f; - config3._locale = config3._locale || getLocale(config3._l); - if (input === null || format2 === void 0 && input === "") { - return createInvalid({ nullInput: true }); - } - if (typeof input === "string") { - config3._i = input = config3._locale.preparse(input); - } - if (isMoment(input)) { - return new Moment(checkOverflow(input)); - } else if (isDate2(input)) { - config3._d = input; - } else if (isArray2(format2)) { - configFromStringAndArray(config3); - } else if (format2) { - configFromStringAndFormat(config3); + function absFloor(number) { + if (number < 0) { + return Math.ceil(number) || 0; } else { - configFromInput(config3); - } - if (!isValid(config3)) { - config3._d = null; + return Math.floor(number); } - return config3; } - function configFromInput(config3) { - var input = config3._i; - if (isUndefined2(input)) { - config3._d = new Date(hooks.now()); - } else if (isDate2(input)) { - config3._d = new Date(input.valueOf()); - } else if (typeof input === "string") { - configFromString(config3); - } else if (isArray2(input)) { - config3._a = map(input.slice(0), function(obj) { - return parseInt(obj, 10); - }); - configFromArray(config3); - } else if (isObject2(input)) { - configFromObject(config3); - } else if (isNumber2(input)) { - config3._d = new Date(input); - } else { - hooks.createFromInputFallback(config3); + function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, value = 0; + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + value = absFloor(coercedNumber); } + return value; } - function createLocalOrUTC(input, format2, locale2, strict, isUTC) { - var c = {}; - if (format2 === true || format2 === false) { - strict = format2; - format2 = void 0; + var tokens = {}; + function addParseToken(token2, callback) { + var i, func = callback, tokenLen; + if (typeof token2 === "string") { + token2 = [token2]; } - if (locale2 === true || locale2 === false) { - strict = locale2; - locale2 = void 0; + if (isNumber2(callback)) { + func = function(input, array) { + array[callback] = toInt(input); + }; } - if (isObject2(input) && isObjectEmpty(input) || isArray2(input) && input.length === 0) { - input = void 0; + tokenLen = token2.length; + for (i = 0; i < tokenLen; i++) { + tokens[token2[i]] = func; } - c._isAMomentObject = true; - c._useUTC = c._isUTC = isUTC; - c._l = locale2; - c._i = input; - c._f = format2; - c._strict = strict; - return createFromConfig(c); } - function createLocal(input, format2, locale2, strict) { - return createLocalOrUTC(input, format2, locale2, strict, false); + function addWeekParseToken(token2, callback) { + addParseToken(token2, function(input, array, config3, token3) { + config3._w = config3._w || {}; + callback(input, config3._w, config3, token3); + }); } - var prototypeMin = deprecate( - "moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/", - function() { - var other = createLocal.apply(null, arguments); - if (this.isValid() && other.isValid()) { - return other < this ? this : other; - } else { - return createInvalid(); - } + function addTimeToArrayFromToken(token2, input, config3) { + if (input != null && hasOwnProp(tokens, token2)) { + tokens[token2](input, config3._a, config3, token2); } - ), prototypeMax = deprecate( - "moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/", - function() { - var other = createLocal.apply(null, arguments); - if (this.isValid() && other.isValid()) { - return other > this ? this : other; + } + function isLeapYear(year) { + return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0; + } + var YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, WEEK = 7, WEEKDAY = 8; + addFormatToken("Y", 0, 0, function() { + var y2 = this.year(); + return y2 <= 9999 ? zeroFill(y2, 4) : "+" + y2; + }); + addFormatToken(0, ["YY", 2], 0, function() { + return this.year() % 100; + }); + addFormatToken(0, ["YYYY", 4], 0, "year"); + addFormatToken(0, ["YYYYY", 5], 0, "year"); + addFormatToken(0, ["YYYYYY", 6, true], 0, "year"); + addRegexToken("Y", matchSigned); + addRegexToken("YY", match1to2, match2); + addRegexToken("YYYY", match1to4, match4); + addRegexToken("YYYYY", match1to6, match6); + addRegexToken("YYYYYY", match1to6, match6); + addParseToken(["YYYYY", "YYYYYY"], YEAR); + addParseToken("YYYY", function(input, array) { + array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); + }); + addParseToken("YY", function(input, array) { + array[YEAR] = hooks.parseTwoDigitYear(input); + }); + addParseToken("Y", function(input, array) { + array[YEAR] = parseInt(input, 10); + }); + function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; + } + hooks.parseTwoDigitYear = function(input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2e3); + }; + var getSetYear = makeGetSet("FullYear", true); + function getIsLeapYear() { + return isLeapYear(this.year()); + } + function makeGetSet(unit, keepTime) { + return function(value) { + if (value != null) { + set$1(this, unit, value); + hooks.updateOffset(this, keepTime); + return this; } else { - return createInvalid(); + return get(this, unit); } + }; + } + function get(mom, unit) { + if (!mom.isValid()) { + return NaN; } - ); - function pickBy(fn2, moments) { - var res, i; - if (moments.length === 1 && isArray2(moments[0])) { - moments = moments[0]; + var d = mom._d, isUTC = mom._isUTC; + switch (unit) { + case "Milliseconds": + return isUTC ? d.getUTCMilliseconds() : d.getMilliseconds(); + case "Seconds": + return isUTC ? d.getUTCSeconds() : d.getSeconds(); + case "Minutes": + return isUTC ? d.getUTCMinutes() : d.getMinutes(); + case "Hours": + return isUTC ? d.getUTCHours() : d.getHours(); + case "Date": + return isUTC ? d.getUTCDate() : d.getDate(); + case "Day": + return isUTC ? d.getUTCDay() : d.getDay(); + case "Month": + return isUTC ? d.getUTCMonth() : d.getMonth(); + case "FullYear": + return isUTC ? d.getUTCFullYear() : d.getFullYear(); + default: + return NaN; } - if (!moments.length) { - return createLocal(); + } + function set$1(mom, unit, value) { + var d, isUTC, year, month, date; + if (!mom.isValid() || isNaN(value)) { + return; } - res = moments[0]; - for (i = 1; i < moments.length; ++i) { - if (!moments[i].isValid() || moments[i][fn2](res)) { - res = moments[i]; - } + d = mom._d; + isUTC = mom._isUTC; + switch (unit) { + case "Milliseconds": + return void (isUTC ? d.setUTCMilliseconds(value) : d.setMilliseconds(value)); + case "Seconds": + return void (isUTC ? d.setUTCSeconds(value) : d.setSeconds(value)); + case "Minutes": + return void (isUTC ? d.setUTCMinutes(value) : d.setMinutes(value)); + case "Hours": + return void (isUTC ? d.setUTCHours(value) : d.setHours(value)); + case "Date": + return void (isUTC ? d.setUTCDate(value) : d.setDate(value)); + // case 'Day': // Not real + // return void (isUTC ? d.setUTCDay(value) : d.setDay(value)); + // case 'Month': // Not used because we need to pass two variables + // return void (isUTC ? d.setUTCMonth(value) : d.setMonth(value)); + case "FullYear": + break; + // See below ... + default: + return; } - return res; - } - function min() { - var args = [].slice.call(arguments, 0); - return pickBy("isBefore", args); + year = value; + month = mom.month(); + date = mom.date(); + date = date === 29 && month === 1 && !isLeapYear(year) ? 28 : date; + void (isUTC ? d.setUTCFullYear(year, month, date) : d.setFullYear(year, month, date)); } - function max() { - var args = [].slice.call(arguments, 0); - return pickBy("isAfter", args); + function stringGet(units) { + units = normalizeUnits(units); + if (isFunction2(this[units])) { + return this[units](); + } + return this; } - var now = function() { - return Date.now ? Date.now() : +/* @__PURE__ */ new Date(); - }; - var ordering = [ - "year", - "quarter", - "month", - "week", - "day", - "hour", - "minute", - "second", - "millisecond" - ]; - function isDurationValid(m2) { - var key, unitHasDecimal = false, i, orderLen = ordering.length; - for (key in m2) { - if (hasOwnProp(m2, key) && !(indexOf.call(ordering, key) !== -1 && (m2[key] == null || !isNaN(m2[key])))) { - return false; + function stringSet(units, value) { + if (typeof units === "object") { + units = normalizeObjectUnits(units); + var prioritized = getPrioritizedUnits(units), i, prioritizedLen = prioritized.length; + for (i = 0; i < prioritizedLen; i++) { + this[prioritized[i].unit](units[prioritized[i].unit]); } - } - for (i = 0; i < orderLen; ++i) { - if (m2[ordering[i]]) { - if (unitHasDecimal) { - return false; - } - if (parseFloat(m2[ordering[i]]) !== toInt(m2[ordering[i]])) { - unitHasDecimal = true; - } + } else { + units = normalizeUnits(units); + if (isFunction2(this[units])) { + return this[units](value); } } - return true; - } - function isValid$1() { - return this._isValid; + return this; } - function createInvalid$1() { - return createDuration(NaN); + function mod2(n, x2) { + return (n % x2 + x2) % x2; } - function Duration(duration) { - var normalizedInput = normalizeObjectUnits(duration), years2 = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months2 = normalizedInput.month || 0, weeks2 = normalizedInput.week || normalizedInput.isoWeek || 0, days2 = normalizedInput.day || 0, hours2 = normalizedInput.hour || 0, minutes2 = normalizedInput.minute || 0, seconds2 = normalizedInput.second || 0, milliseconds2 = normalizedInput.millisecond || 0; - this._isValid = isDurationValid(normalizedInput); - this._milliseconds = +milliseconds2 + seconds2 * 1e3 + // 1000 - minutes2 * 6e4 + // 1000 * 60 - hours2 * 1e3 * 60 * 60; - this._days = +days2 + weeks2 * 7; - this._months = +months2 + quarters * 3 + years2 * 12; - this._data = {}; - this._locale = getLocale(); - this._bubble(); + var indexOf; + if (Array.prototype.indexOf) { + indexOf = Array.prototype.indexOf; + } else { + indexOf = function(o) { + var i; + for (i = 0; i < this.length; ++i) { + if (this[i] === o) { + return i; + } + } + return -1; + }; } - function isDuration(obj) { - return obj instanceof Duration; + function daysInMonth(year, month) { + if (isNaN(year) || isNaN(month)) { + return NaN; + } + var modMonth = mod2(month, 12); + year += (month - modMonth) / 12; + return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2; } - function absRound(number) { - if (number < 0) { - return Math.round(-1 * number) * -1; + addFormatToken("M", ["MM", 2], "Mo", function() { + return this.month() + 1; + }); + addFormatToken("MMM", 0, 0, function(format2) { + return this.localeData().monthsShort(this, format2); + }); + addFormatToken("MMMM", 0, 0, function(format2) { + return this.localeData().months(this, format2); + }); + addRegexToken("M", match1to2, match1to2NoLeadingZero); + addRegexToken("MM", match1to2, match2); + addRegexToken("MMM", function(isStrict, locale2) { + return locale2.monthsShortRegex(isStrict); + }); + addRegexToken("MMMM", function(isStrict, locale2) { + return locale2.monthsRegex(isStrict); + }); + addParseToken(["M", "MM"], function(input, array) { + array[MONTH] = toInt(input) - 1; + }); + addParseToken(["MMM", "MMMM"], function(input, array, config3, token2) { + var month = config3._locale.monthsParse(input, token2, config3._strict); + if (month != null) { + array[MONTH] = month; } else { - return Math.round(number); + getParsingFlags(config3).invalidMonth = input; + } + }); + var defaultLocaleMonths = "January_February_March_April_May_June_July_August_September_October_November_December".split( + "_" + ), defaultLocaleMonthsShort = "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, defaultMonthsShortRegex = matchWord, defaultMonthsRegex = matchWord; + function localeMonths(m2, format2) { + if (!m2) { + return isArray2(this._months) ? this._months : this._months["standalone"]; } + return isArray2(this._months) ? this._months[m2.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format2) ? "format" : "standalone"][m2.month()]; } - function compareArrays(array1, array2, dontConvert) { - var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; - for (i = 0; i < len; i++) { - if (dontConvert && array1[i] !== array2[i] || !dontConvert && toInt(array1[i]) !== toInt(array2[i])) { - diffs++; - } + function localeMonthsShort(m2, format2) { + if (!m2) { + return isArray2(this._monthsShort) ? this._monthsShort : this._monthsShort["standalone"]; } - return diffs + lengthDiff; + return isArray2(this._monthsShort) ? this._monthsShort[m2.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format2) ? "format" : "standalone"][m2.month()]; } - function offset(token2, separator) { - addFormatToken(token2, 0, 0, function() { - var offset2 = this.utcOffset(), sign3 = "+"; - if (offset2 < 0) { - offset2 = -offset2; - sign3 = "-"; + function handleStrictParse(monthName, format2, strict) { + var i, ii2, mom, llc = monthName.toLocaleLowerCase(); + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + for (i = 0; i < 12; ++i) { + mom = createUTC([2e3, i]); + this._shortMonthsParse[i] = this.monthsShort( + mom, + "" + ).toLocaleLowerCase(); + this._longMonthsParse[i] = this.months(mom, "").toLocaleLowerCase(); } - return sign3 + zeroFill(~~(offset2 / 60), 2) + separator + zeroFill(~~offset2 % 60, 2); - }); - } - offset("Z", ":"); - offset("ZZ", ""); - addRegexToken("Z", matchShortOffset); - addRegexToken("ZZ", matchShortOffset); - addParseToken(["Z", "ZZ"], function(input, array, config3) { - config3._useUTC = true; - config3._tzm = offsetFromString(matchShortOffset, input); - }); - var chunkOffset = /([\+\-]|\d\d)/gi; - function offsetFromString(matcher, string) { - var matches = (string || "").match(matcher), chunk, parts, minutes2; - if (matches === null) { - return null; } - chunk = matches[matches.length - 1] || []; - parts = (chunk + "").match(chunkOffset) || ["-", 0, 0]; - minutes2 = +(parts[1] * 60) + toInt(parts[2]); - return minutes2 === 0 ? 0 : parts[0] === "+" ? minutes2 : -minutes2; - } - function cloneWithOffset(input, model) { - var res, diff2; - if (model._isUTC) { - res = model.clone(); - diff2 = (isMoment(input) || isDate2(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); - res._d.setTime(res._d.valueOf() + diff2); - hooks.updateOffset(res, false); - return res; + if (strict) { + if (format2 === "MMM") { + ii2 = indexOf.call(this._shortMonthsParse, llc); + return ii2 !== -1 ? ii2 : null; + } else { + ii2 = indexOf.call(this._longMonthsParse, llc); + return ii2 !== -1 ? ii2 : null; + } } else { - return createLocal(input).local(); + if (format2 === "MMM") { + ii2 = indexOf.call(this._shortMonthsParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._longMonthsParse, llc); + return ii2 !== -1 ? ii2 : null; + } else { + ii2 = indexOf.call(this._longMonthsParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._shortMonthsParse, llc); + return ii2 !== -1 ? ii2 : null; + } } } - function getDateOffset(m2) { - return -Math.round(m2._d.getTimezoneOffset()); - } - hooks.updateOffset = function() { - }; - function getSetOffset(input, keepLocalTime, keepMinutes) { - var offset2 = this._offset || 0, localAdjust; - if (!this.isValid()) { - return input != null ? this : NaN; + function localeMonthsParse(monthName, format2, strict) { + var i, mom, regex; + if (this._monthsParseExact) { + return handleStrictParse.call(this, monthName, format2, strict); } - if (input != null) { - if (typeof input === "string") { - input = offsetFromString(matchShortOffset, input); - if (input === null) { - return this; - } - } else if (Math.abs(input) < 16 && !keepMinutes) { - input = input * 60; + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } + for (i = 0; i < 12; i++) { + mom = createUTC([2e3, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp( + "^" + this.months(mom, "").replace(".", "") + "$", + "i" + ); + this._shortMonthsParse[i] = new RegExp( + "^" + this.monthsShort(mom, "").replace(".", "") + "$", + "i" + ); } - if (!this._isUTC && keepLocalTime) { - localAdjust = getDateOffset(this); + if (!strict && !this._monthsParse[i]) { + regex = "^" + this.months(mom, "") + "|^" + this.monthsShort(mom, ""); + this._monthsParse[i] = new RegExp(regex.replace(".", ""), "i"); } - this._offset = input; - this._isUTC = true; - if (localAdjust != null) { - this.add(localAdjust, "m"); + if (strict && format2 === "MMMM" && this._longMonthsParse[i].test(monthName)) { + return i; + } else if (strict && format2 === "MMM" && this._shortMonthsParse[i].test(monthName)) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; } - if (offset2 !== input) { - if (!keepLocalTime || this._changeInProgress) { - addSubtract( - this, - createDuration(input - offset2, "m"), - 1, - false - ); - } else if (!this._changeInProgress) { - this._changeInProgress = true; - hooks.updateOffset(this, true); - this._changeInProgress = null; + } + } + function setMonth(mom, value) { + if (!mom.isValid()) { + return mom; + } + if (typeof value === "string") { + if (/^\d+$/.test(value)) { + value = toInt(value); + } else { + value = mom.localeData().monthsParse(value); + if (!isNumber2(value)) { + return mom; } } - return this; - } else { - return this._isUTC ? offset2 : getDateOffset(this); } + var month = value, date = mom.date(); + date = date < 29 ? date : Math.min(date, daysInMonth(mom.year(), month)); + void (mom._isUTC ? mom._d.setUTCMonth(month, date) : mom._d.setMonth(month, date)); + return mom; } - function getSetZone(input, keepLocalTime) { - if (input != null) { - if (typeof input !== "string") { - input = -input; - } - this.utcOffset(input, keepLocalTime); + function getSetMonth(value) { + if (value != null) { + setMonth(this, value); + hooks.updateOffset(this, true); return this; } else { - return -this.utcOffset(); + return get(this, "Month"); } } - function setOffsetToUTC(keepLocalTime) { - return this.utcOffset(0, keepLocalTime); + function getDaysInMonth() { + return daysInMonth(this.year(), this.month()); } - function setOffsetToLocal(keepLocalTime) { - if (this._isUTC) { - this.utcOffset(0, keepLocalTime); - this._isUTC = false; - if (keepLocalTime) { - this.subtract(getDateOffset(this), "m"); + function monthsShortRegex(isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, "_monthsRegex")) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsShortStrictRegex; + } else { + return this._monthsShortRegex; + } + } else { + if (!hasOwnProp(this, "_monthsShortRegex")) { + this._monthsShortRegex = defaultMonthsShortRegex; } + return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex; } - return this; } - function setOffsetToParsedOffset() { - if (this._tzm != null) { - this.utcOffset(this._tzm, false, true); - } else if (typeof this._i === "string") { - var tZone = offsetFromString(matchOffset, this._i); - if (tZone != null) { - this.utcOffset(tZone); + function monthsRegex(isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, "_monthsRegex")) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsStrictRegex; } else { - this.utcOffset(0, true); + return this._monthsRegex; + } + } else { + if (!hasOwnProp(this, "_monthsRegex")) { + this._monthsRegex = defaultMonthsRegex; } + return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex; } - return this; } - function hasAlignedHourOffset(input) { - if (!this.isValid()) { - return false; + function computeMonthsParse() { + function cmpLenRev(a, b2) { + return b2.length - a.length; } - input = input ? createLocal(input).utcOffset() : 0; - return (this.utcOffset() - input) % 60 === 0; - } - function isDaylightSavingTime() { - return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset(); - } - function isDaylightSavingTimeShifted() { - if (!isUndefined2(this._isDSTShifted)) { - return this._isDSTShifted; + var shortPieces = [], longPieces = [], mixedPieces = [], i, mom, shortP, longP; + for (i = 0; i < 12; i++) { + mom = createUTC([2e3, i]); + shortP = regexEscape(this.monthsShort(mom, "")); + longP = regexEscape(this.months(mom, "")); + shortPieces.push(shortP); + longPieces.push(longP); + mixedPieces.push(longP); + mixedPieces.push(shortP); } - var c = {}, other; - copyConfig(c, this); - c = prepareConfig(c); - if (c._a) { - other = c._isUTC ? createUTC(c._a) : createLocal(c._a); - this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0; + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + this._monthsRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); + this._monthsShortRegex = this._monthsRegex; + this._monthsStrictRegex = new RegExp( + "^(" + longPieces.join("|") + ")", + "i" + ); + this._monthsShortStrictRegex = new RegExp( + "^(" + shortPieces.join("|") + ")", + "i" + ); + } + function createDate(y2, m2, d, h, M2, s, ms) { + var date; + if (y2 < 100 && y2 >= 0) { + date = new Date(y2 + 400, m2, d, h, M2, s, ms); + if (isFinite(date.getFullYear())) { + date.setFullYear(y2); + } } else { - this._isDSTShifted = false; + date = new Date(y2, m2, d, h, M2, s, ms); } - return this._isDSTShifted; - } - function isLocal() { - return this.isValid() ? !this._isUTC : false; - } - function isUtcOffset() { - return this.isValid() ? this._isUTC : false; - } - function isUtc() { - return this.isValid() ? this._isUTC && this._offset === 0 : false; + return date; } - var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; - function createDuration(input, key) { - var duration = input, match = null, sign3, ret, diffRes; - if (isDuration(input)) { - duration = { - ms: input._milliseconds, - d: input._days, - M: input._months - }; - } else if (isNumber2(input) || !isNaN(+input)) { - duration = {}; - if (key) { - duration[key] = +input; - } else { - duration.milliseconds = +input; + function createUTCDate(y2) { + var date, args; + if (y2 < 100 && y2 >= 0) { + args = Array.prototype.slice.call(arguments); + args[0] = y2 + 400; + date = new Date(Date.UTC.apply(null, args)); + if (isFinite(date.getUTCFullYear())) { + date.setUTCFullYear(y2); } - } else if (match = aspNetRegex.exec(input)) { - sign3 = match[1] === "-" ? -1 : 1; - duration = { - y: 0, - d: toInt(match[DATE]) * sign3, - h: toInt(match[HOUR]) * sign3, - m: toInt(match[MINUTE]) * sign3, - s: toInt(match[SECOND]) * sign3, - ms: toInt(absRound(match[MILLISECOND] * 1e3)) * sign3 - // the millisecond decimal point is included in the match - }; - } else if (match = isoRegex.exec(input)) { - sign3 = match[1] === "-" ? -1 : 1; - duration = { - y: parseIso(match[2], sign3), - M: parseIso(match[3], sign3), - w: parseIso(match[4], sign3), - d: parseIso(match[5], sign3), - h: parseIso(match[6], sign3), - m: parseIso(match[7], sign3), - s: parseIso(match[8], sign3) - }; - } else if (duration == null) { - duration = {}; - } else if (typeof duration === "object" && ("from" in duration || "to" in duration)) { - diffRes = momentsDifference( - createLocal(duration.from), - createLocal(duration.to) - ); - duration = {}; - duration.ms = diffRes.milliseconds; - duration.M = diffRes.months; + } else { + date = new Date(Date.UTC.apply(null, arguments)); } - ret = new Duration(duration); - if (isDuration(input) && hasOwnProp(input, "_locale")) { - ret._locale = input._locale; + return date; + } + function firstWeekOffset(year, dow, doy) { + var fwd = 7 + dow - doy, fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; + return -fwdlw + fwd - 1; + } + function dayOfYearFromWeeks(year, week, weekday, dow, doy) { + var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear; + if (dayOfYear <= 0) { + resYear = year - 1; + resDayOfYear = daysInYear(resYear) + dayOfYear; + } else if (dayOfYear > daysInYear(year)) { + resYear = year + 1; + resDayOfYear = dayOfYear - daysInYear(year); + } else { + resYear = year; + resDayOfYear = dayOfYear; } - if (isDuration(input) && hasOwnProp(input, "_isValid")) { - ret._isValid = input._isValid; + return { + year: resYear, + dayOfYear: resDayOfYear + }; + } + function weekOfYear(mom, dow, doy) { + var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear; + if (week < 1) { + resYear = mom.year() - 1; + resWeek = week + weeksInYear(resYear, dow, doy); + } else if (week > weeksInYear(mom.year(), dow, doy)) { + resWeek = week - weeksInYear(mom.year(), dow, doy); + resYear = mom.year() + 1; + } else { + resYear = mom.year(); + resWeek = week; } - return ret; + return { + week: resWeek, + year: resYear + }; } - createDuration.fn = Duration.prototype; - createDuration.invalid = createInvalid$1; - function parseIso(inp, sign3) { - var res = inp && parseFloat(inp.replace(",", ".")); - return (isNaN(res) ? 0 : res) * sign3; + function weeksInYear(year, dow, doy) { + var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy); + return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; } - function positiveMomentsDifference(base, other) { - var res = {}; - res.months = other.month() - base.month() + (other.year() - base.year()) * 12; - if (base.clone().add(res.months, "M").isAfter(other)) { - --res.months; + addFormatToken("w", ["ww", 2], "wo", "week"); + addFormatToken("W", ["WW", 2], "Wo", "isoWeek"); + addRegexToken("w", match1to2, match1to2NoLeadingZero); + addRegexToken("ww", match1to2, match2); + addRegexToken("W", match1to2, match1to2NoLeadingZero); + addRegexToken("WW", match1to2, match2); + addWeekParseToken( + ["w", "ww", "W", "WW"], + function(input, week, config3, token2) { + week[token2.substr(0, 1)] = toInt(input); } - res.milliseconds = +other - +base.clone().add(res.months, "M"); - return res; + ); + function localeWeek(mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; } - function momentsDifference(base, other) { - var res; - if (!(base.isValid() && other.isValid())) { - return { milliseconds: 0, months: 0 }; - } - other = cloneWithOffset(other, base); - if (base.isBefore(other)) { - res = positiveMomentsDifference(base, other); - } else { - res = positiveMomentsDifference(other, base); - res.milliseconds = -res.milliseconds; - res.months = -res.months; - } - return res; + var defaultLocaleWeek = { + dow: 0, + // Sunday is the first day of the week. + doy: 6 + // The week that contains Jan 6th is the first week of the year. + }; + function localeFirstDayOfWeek() { + return this._week.dow; } - function createAdder(direction, name) { - return function(val, period) { - var dur, tmp; - if (period !== null && !isNaN(+period)) { - deprecateSimple( - name, - "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info." - ); - tmp = val; - val = period; - period = tmp; - } - dur = createDuration(val, period); - addSubtract(this, dur, direction); - return this; - }; + function localeFirstDayOfYear() { + return this._week.doy; } - function addSubtract(mom, duration, isAdding, updateOffset) { - var milliseconds2 = duration._milliseconds, days2 = absRound(duration._days), months2 = absRound(duration._months); - if (!mom.isValid()) { - return; + function getSetWeek(input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, "d"); + } + function getSetISOWeek(input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, "d"); + } + addFormatToken("d", 0, "do", "day"); + addFormatToken("dd", 0, 0, function(format2) { + return this.localeData().weekdaysMin(this, format2); + }); + addFormatToken("ddd", 0, 0, function(format2) { + return this.localeData().weekdaysShort(this, format2); + }); + addFormatToken("dddd", 0, 0, function(format2) { + return this.localeData().weekdays(this, format2); + }); + addFormatToken("e", 0, 0, "weekday"); + addFormatToken("E", 0, 0, "isoWeekday"); + addRegexToken("d", match1to2); + addRegexToken("e", match1to2); + addRegexToken("E", match1to2); + addRegexToken("dd", function(isStrict, locale2) { + return locale2.weekdaysMinRegex(isStrict); + }); + addRegexToken("ddd", function(isStrict, locale2) { + return locale2.weekdaysShortRegex(isStrict); + }); + addRegexToken("dddd", function(isStrict, locale2) { + return locale2.weekdaysRegex(isStrict); + }); + addWeekParseToken(["dd", "ddd", "dddd"], function(input, week, config3, token2) { + var weekday = config3._locale.weekdaysParse(input, token2, config3._strict); + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config3).invalidWeekday = input; } - updateOffset = updateOffset == null ? true : updateOffset; - if (months2) { - setMonth(mom, get(mom, "Month") + months2 * isAdding); + }); + addWeekParseToken(["d", "e", "E"], function(input, week, config3, token2) { + week[token2] = toInt(input); + }); + function parseWeekday(input, locale2) { + if (typeof input !== "string") { + return input; } - if (days2) { - set$1(mom, "Date", get(mom, "Date") + days2 * isAdding); + if (!isNaN(input)) { + return parseInt(input, 10); } - if (milliseconds2) { - mom._d.setTime(mom._d.valueOf() + milliseconds2 * isAdding); + input = locale2.weekdaysParse(input); + if (typeof input === "number") { + return input; } - if (updateOffset) { - hooks.updateOffset(mom, days2 || months2); + return null; + } + function parseIsoWeekday(input, locale2) { + if (typeof input === "string") { + return locale2.weekdaysParse(input) % 7 || 7; } + return isNaN(input) ? null : input; } - var add = createAdder(1, "add"), subtract = createAdder(-1, "subtract"); - function isString2(input) { - return typeof input === "string" || input instanceof String; + function shiftWeekdays(ws2, n) { + return ws2.slice(n, 7).concat(ws2.slice(0, n)); } - function isMomentInput(input) { - return isMoment(input) || isDate2(input) || isString2(input) || isNumber2(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === void 0; + var defaultLocaleWeekdays = "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), defaultLocaleWeekdaysShort = "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), defaultLocaleWeekdaysMin = "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), defaultWeekdaysRegex = matchWord, defaultWeekdaysShortRegex = matchWord, defaultWeekdaysMinRegex = matchWord; + function localeWeekdays(m2, format2) { + var weekdays = isArray2(this._weekdays) ? this._weekdays : this._weekdays[m2 && m2 !== true && this._weekdays.isFormat.test(format2) ? "format" : "standalone"]; + return m2 === true ? shiftWeekdays(weekdays, this._week.dow) : m2 ? weekdays[m2.day()] : weekdays; } - function isMomentInputObject(input) { - var objectTest = isObject2(input) && !isObjectEmpty(input), propertyTest = false, properties = [ - "years", - "year", - "y", - "months", - "month", - "M", - "days", - "day", - "d", - "dates", - "date", - "D", - "hours", - "hour", - "h", - "minutes", - "minute", - "m", - "seconds", - "second", - "s", - "milliseconds", - "millisecond", - "ms" - ], i, property, propertyLen = properties.length; - for (i = 0; i < propertyLen; i += 1) { - property = properties[i]; - propertyTest = propertyTest || hasOwnProp(input, property); - } - return objectTest && propertyTest; + function localeWeekdaysShort(m2) { + return m2 === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m2 ? this._weekdaysShort[m2.day()] : this._weekdaysShort; } - function isNumberOrStringArray(input) { - var arrayTest = isArray2(input), dataTypeTest = false; - if (arrayTest) { - dataTypeTest = input.filter(function(item) { - return !isNumber2(item) && isString2(input); - }).length === 0; - } - return arrayTest && dataTypeTest; + function localeWeekdaysMin(m2) { + return m2 === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m2 ? this._weekdaysMin[m2.day()] : this._weekdaysMin; } - function isCalendarSpec(input) { - var objectTest = isObject2(input) && !isObjectEmpty(input), propertyTest = false, properties = [ - "sameDay", - "nextDay", - "lastDay", - "nextWeek", - "lastWeek", - "sameElse" - ], i, property; - for (i = 0; i < properties.length; i += 1) { - property = properties[i]; - propertyTest = propertyTest || hasOwnProp(input, property); + function handleStrictParse$1(weekdayName, format2, strict) { + var i, ii2, mom, llc = weekdayName.toLocaleLowerCase(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._shortWeekdaysParse = []; + this._minWeekdaysParse = []; + for (i = 0; i < 7; ++i) { + mom = createUTC([2e3, 1]).day(i); + this._minWeekdaysParse[i] = this.weekdaysMin( + mom, + "" + ).toLocaleLowerCase(); + this._shortWeekdaysParse[i] = this.weekdaysShort( + mom, + "" + ).toLocaleLowerCase(); + this._weekdaysParse[i] = this.weekdays(mom, "").toLocaleLowerCase(); + } } - return objectTest && propertyTest; - } - function getCalendarFormat(myMoment, now2) { - var diff2 = myMoment.diff(now2, "days", true); - return diff2 < -6 ? "sameElse" : diff2 < -1 ? "lastWeek" : diff2 < 0 ? "lastDay" : diff2 < 1 ? "sameDay" : diff2 < 2 ? "nextDay" : diff2 < 7 ? "nextWeek" : "sameElse"; - } - function calendar$1(time, formats) { - if (arguments.length === 1) { - if (!arguments[0]) { - time = void 0; - formats = void 0; - } else if (isMomentInput(arguments[0])) { - time = arguments[0]; - formats = void 0; - } else if (isCalendarSpec(arguments[0])) { - formats = arguments[0]; - time = void 0; + if (strict) { + if (format2 === "dddd") { + ii2 = indexOf.call(this._weekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } else if (format2 === "ddd") { + ii2 = indexOf.call(this._shortWeekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } else { + ii2 = indexOf.call(this._minWeekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } + } else { + if (format2 === "dddd") { + ii2 = indexOf.call(this._weekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._shortWeekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._minWeekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } else if (format2 === "ddd") { + ii2 = indexOf.call(this._shortWeekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._weekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._minWeekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; + } else { + ii2 = indexOf.call(this._minWeekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._weekdaysParse, llc); + if (ii2 !== -1) { + return ii2; + } + ii2 = indexOf.call(this._shortWeekdaysParse, llc); + return ii2 !== -1 ? ii2 : null; } } - var now2 = time || createLocal(), sod = cloneWithOffset(now2, this).startOf("day"), format2 = hooks.calendarFormat(this, sod) || "sameElse", output = formats && (isFunction2(formats[format2]) ? formats[format2].call(this, now2) : formats[format2]); - return this.format( - output || this.localeData().calendar(format2, this, createLocal(now2)) - ); - } - function clone() { - return new Moment(this); } - function isAfter(input, units) { - var localInput = isMoment(input) ? input : createLocal(input); - if (!(this.isValid() && localInput.isValid())) { - return false; + function localeWeekdaysParse(weekdayName, format2, strict) { + var i, mom, regex; + if (this._weekdaysParseExact) { + return handleStrictParse$1.call(this, weekdayName, format2, strict); } - units = normalizeUnits(units) || "millisecond"; - if (units === "millisecond") { - return this.valueOf() > localInput.valueOf(); - } else { - return localInput.valueOf() < this.clone().startOf(units).valueOf(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._minWeekdaysParse = []; + this._shortWeekdaysParse = []; + this._fullWeekdaysParse = []; + } + for (i = 0; i < 7; i++) { + mom = createUTC([2e3, 1]).day(i); + if (strict && !this._fullWeekdaysParse[i]) { + this._fullWeekdaysParse[i] = new RegExp( + "^" + this.weekdays(mom, "").replace(".", "\\.?") + "$", + "i" + ); + this._shortWeekdaysParse[i] = new RegExp( + "^" + this.weekdaysShort(mom, "").replace(".", "\\.?") + "$", + "i" + ); + this._minWeekdaysParse[i] = new RegExp( + "^" + this.weekdaysMin(mom, "").replace(".", "\\.?") + "$", + "i" + ); + } + if (!this._weekdaysParse[i]) { + regex = "^" + this.weekdays(mom, "") + "|^" + this.weekdaysShort(mom, "") + "|^" + this.weekdaysMin(mom, ""); + this._weekdaysParse[i] = new RegExp(regex.replace(".", ""), "i"); + } + if (strict && format2 === "dddd" && this._fullWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format2 === "ddd" && this._shortWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format2 === "dd" && this._minWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { + return i; + } } } - function isBefore(input, units) { - var localInput = isMoment(input) ? input : createLocal(input); - if (!(this.isValid() && localInput.isValid())) { - return false; + function getSetDayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; } - units = normalizeUnits(units) || "millisecond"; - if (units === "millisecond") { - return this.valueOf() < localInput.valueOf(); + var day = get(this, "Day"); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, "d"); } else { - return this.clone().endOf(units).valueOf() < localInput.valueOf(); + return day; } } - function isBetween(from6, to3, units, inclusivity) { - var localFrom = isMoment(from6) ? from6 : createLocal(from6), localTo = isMoment(to3) ? to3 : createLocal(to3); - if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { - return false; + function getSetLocaleDayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; } - inclusivity = inclusivity || "()"; - return (inclusivity[0] === "(" ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ")" ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)); + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, "d"); } - function isSame(input, units) { - var localInput = isMoment(input) ? input : createLocal(input), inputMs; - if (!(this.isValid() && localInput.isValid())) { - return false; + function getSetISODayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; } - units = normalizeUnits(units) || "millisecond"; - if (units === "millisecond") { - return this.valueOf() === localInput.valueOf(); + if (input != null) { + var weekday = parseIsoWeekday(input, this.localeData()); + return this.day(this.day() % 7 ? weekday : weekday - 7); } else { - inputMs = localInput.valueOf(); - return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); + return this.day() || 7; } } - function isSameOrAfter(input, units) { - return this.isSame(input, units) || this.isAfter(input, units); - } - function isSameOrBefore(input, units) { - return this.isSame(input, units) || this.isBefore(input, units); - } - function diff(input, units, asFloat) { - var that, zoneDelta, output; - if (!this.isValid()) { - return NaN; + function weekdaysRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, "_weekdaysRegex")) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysStrictRegex; + } else { + return this._weekdaysRegex; + } + } else { + if (!hasOwnProp(this, "_weekdaysRegex")) { + this._weekdaysRegex = defaultWeekdaysRegex; + } + return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; } - that = cloneWithOffset(input, this); - if (!that.isValid()) { - return NaN; + } + function weekdaysShortRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, "_weekdaysRegex")) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysShortStrictRegex; + } else { + return this._weekdaysShortRegex; + } + } else { + if (!hasOwnProp(this, "_weekdaysShortRegex")) { + this._weekdaysShortRegex = defaultWeekdaysShortRegex; + } + return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; } - zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; - units = normalizeUnits(units); - switch (units) { - case "year": - output = monthDiff(this, that) / 12; - break; - case "month": - output = monthDiff(this, that); - break; - case "quarter": - output = monthDiff(this, that) / 3; - break; - case "second": - output = (this - that) / 1e3; - break; - // 1000 - case "minute": - output = (this - that) / 6e4; - break; - // 1000 * 60 - case "hour": - output = (this - that) / 36e5; - break; - // 1000 * 60 * 60 - case "day": - output = (this - that - zoneDelta) / 864e5; - break; - // 1000 * 60 * 60 * 24, negate dst - case "week": - output = (this - that - zoneDelta) / 6048e5; - break; - // 1000 * 60 * 60 * 24 * 7, negate dst - default: - output = this - that; + } + function weekdaysMinRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, "_weekdaysRegex")) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysMinStrictRegex; + } else { + return this._weekdaysMinRegex; + } + } else { + if (!hasOwnProp(this, "_weekdaysMinRegex")) { + this._weekdaysMinRegex = defaultWeekdaysMinRegex; + } + return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; } - return asFloat ? output : absFloor(output); } - function monthDiff(a, b2) { - if (a.date() < b2.date()) { - return -monthDiff(b2, a); + function computeWeekdaysParse() { + function cmpLenRev(a, b2) { + return b2.length - a.length; } - var wholeMonthDiff = (b2.year() - a.year()) * 12 + (b2.month() - a.month()), anchor = a.clone().add(wholeMonthDiff, "months"), anchor2, adjust; - if (b2 - anchor < 0) { - anchor2 = a.clone().add(wholeMonthDiff - 1, "months"); - adjust = (b2 - anchor) / (anchor - anchor2); - } else { - anchor2 = a.clone().add(wholeMonthDiff + 1, "months"); - adjust = (b2 - anchor) / (anchor2 - anchor); + var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; + for (i = 0; i < 7; i++) { + mom = createUTC([2e3, 1]).day(i); + minp = regexEscape(this.weekdaysMin(mom, "")); + shortp = regexEscape(this.weekdaysShort(mom, "")); + longp = regexEscape(this.weekdays(mom, "")); + minPieces.push(minp); + shortPieces.push(shortp); + longPieces.push(longp); + mixedPieces.push(minp); + mixedPieces.push(shortp); + mixedPieces.push(longp); } - return -(wholeMonthDiff + adjust) || 0; + minPieces.sort(cmpLenRev); + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + this._weekdaysRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); + this._weekdaysShortRegex = this._weekdaysRegex; + this._weekdaysMinRegex = this._weekdaysRegex; + this._weekdaysStrictRegex = new RegExp( + "^(" + longPieces.join("|") + ")", + "i" + ); + this._weekdaysShortStrictRegex = new RegExp( + "^(" + shortPieces.join("|") + ")", + "i" + ); + this._weekdaysMinStrictRegex = new RegExp( + "^(" + minPieces.join("|") + ")", + "i" + ); } - hooks.defaultFormat = "YYYY-MM-DDTHH:mm:ssZ"; - hooks.defaultFormatUtc = "YYYY-MM-DDTHH:mm:ss[Z]"; - function toString3() { - return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); + function hFormat() { + return this.hours() % 12 || 12; } - function toISOString(keepOffset) { - if (!this.isValid()) { - return null; - } - var utc = keepOffset !== true, m2 = utc ? this.clone().utc() : this; - if (m2.year() < 0 || m2.year() > 9999) { - return formatMoment( - m2, - utc ? "YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYYYY-MM-DD[T]HH:mm:ss.SSSZ" + function kFormat() { + return this.hours() || 24; + } + addFormatToken("H", ["HH", 2], 0, "hour"); + addFormatToken("h", ["hh", 2], 0, hFormat); + addFormatToken("k", ["kk", 2], 0, kFormat); + addFormatToken("hmm", 0, 0, function() { + return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2); + }); + addFormatToken("hmmss", 0, 0, function() { + return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); + }); + addFormatToken("Hmm", 0, 0, function() { + return "" + this.hours() + zeroFill(this.minutes(), 2); + }); + addFormatToken("Hmmss", 0, 0, function() { + return "" + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); + }); + function meridiem(token2, lowercase) { + addFormatToken(token2, 0, 0, function() { + return this.localeData().meridiem( + this.hours(), + this.minutes(), + lowercase ); - } - if (isFunction2(Date.prototype.toISOString)) { - if (utc) { - return this.toDate().toISOString(); - } else { - return new Date(this.valueOf() + this.utcOffset() * 60 * 1e3).toISOString().replace("Z", formatMoment(m2, "Z")); - } - } - return formatMoment( - m2, - utc ? "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYY-MM-DD[T]HH:mm:ss.SSSZ" - ); + }); } - function inspect() { - if (!this.isValid()) { - return "moment.invalid(/* " + this._i + " */)"; - } - var func = "moment", zone = "", prefix, year, datetime, suffix; - if (!this.isLocal()) { - func = this.utcOffset() === 0 ? "moment.utc" : "moment.parseZone"; - zone = "Z"; - } - prefix = "[" + func + '("]'; - year = 0 <= this.year() && this.year() <= 9999 ? "YYYY" : "YYYYYY"; - datetime = "-MM-DD[T]HH:mm:ss.SSS"; - suffix = zone + '[")]'; - return this.format(prefix + year + datetime + suffix); + meridiem("a", true); + meridiem("A", false); + function matchMeridiem(isStrict, locale2) { + return locale2._meridiemParse; } - function format(inputString) { - if (!inputString) { - inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; - } - var output = formatMoment(this, inputString); - return this.localeData().postformat(output); + addRegexToken("a", matchMeridiem); + addRegexToken("A", matchMeridiem); + addRegexToken("H", match1to2, match1to2HasZero); + addRegexToken("h", match1to2, match1to2NoLeadingZero); + addRegexToken("k", match1to2, match1to2NoLeadingZero); + addRegexToken("HH", match1to2, match2); + addRegexToken("hh", match1to2, match2); + addRegexToken("kk", match1to2, match2); + addRegexToken("hmm", match3to4); + addRegexToken("hmmss", match5to6); + addRegexToken("Hmm", match3to4); + addRegexToken("Hmmss", match5to6); + addParseToken(["H", "HH"], HOUR); + addParseToken(["k", "kk"], function(input, array, config3) { + var kInput = toInt(input); + array[HOUR] = kInput === 24 ? 0 : kInput; + }); + addParseToken(["a", "A"], function(input, array, config3) { + config3._isPm = config3._locale.isPM(input); + config3._meridiem = input; + }); + addParseToken(["h", "hh"], function(input, array, config3) { + array[HOUR] = toInt(input); + getParsingFlags(config3).bigHour = true; + }); + addParseToken("hmm", function(input, array, config3) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + getParsingFlags(config3).bigHour = true; + }); + addParseToken("hmmss", function(input, array, config3) { + var pos1 = input.length - 4, pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + getParsingFlags(config3).bigHour = true; + }); + addParseToken("Hmm", function(input, array, config3) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + }); + addParseToken("Hmmss", function(input, array, config3) { + var pos1 = input.length - 4, pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + }); + function localeIsPM(input) { + return (input + "").toLowerCase().charAt(0) === "p"; } - function from5(time, withoutSuffix) { - if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) { - return createDuration({ to: this, from: time }).locale(this.locale()).humanize(!withoutSuffix); + var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, getSetHour = makeGetSet("Hours", true); + function localeMeridiem(hours2, minutes2, isLower) { + if (hours2 > 11) { + return isLower ? "pm" : "PM"; } else { - return this.localeData().invalidDate(); + return isLower ? "am" : "AM"; } } - function fromNow(withoutSuffix) { - return this.from(createLocal(), withoutSuffix); + var baseConfig = { + calendar: defaultCalendar, + longDateFormat: defaultLongDateFormat, + invalidDate: defaultInvalidDate, + ordinal: defaultOrdinal, + dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, + relativeTime: defaultRelativeTime, + months: defaultLocaleMonths, + monthsShort: defaultLocaleMonthsShort, + week: defaultLocaleWeek, + weekdays: defaultLocaleWeekdays, + weekdaysMin: defaultLocaleWeekdaysMin, + weekdaysShort: defaultLocaleWeekdaysShort, + meridiemParse: defaultLocaleMeridiemParse + }; + var locales = {}, localeFamilies = {}, globalLocale; + function commonPrefix(arr1, arr2) { + var i, minl = Math.min(arr1.length, arr2.length); + for (i = 0; i < minl; i += 1) { + if (arr1[i] !== arr2[i]) { + return i; + } + } + return minl; } - function to2(time, withoutSuffix) { - if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) { - return createDuration({ from: this, to: time }).locale(this.locale()).humanize(!withoutSuffix); - } else { - return this.localeData().invalidDate(); + function normalizeLocale(key) { + return key ? key.toLowerCase().replace("_", "-") : key; + } + function chooseLocale(names) { + var i = 0, j2, next, locale2, split3; + while (i < names.length) { + split3 = normalizeLocale(names[i]).split("-"); + j2 = split3.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split("-") : null; + while (j2 > 0) { + locale2 = loadLocale(split3.slice(0, j2).join("-")); + if (locale2) { + return locale2; + } + if (next && next.length >= j2 && commonPrefix(split3, next) >= j2 - 1) { + break; + } + j2--; + } + i++; } + return globalLocale; } - function toNow(withoutSuffix) { - return this.to(createLocal(), withoutSuffix); + function isLocaleNameSane(name) { + return !!(name && name.match("^[^/\\\\]*$")); } - function locale(key) { - var newLocaleData; - if (key === void 0) { - return this._locale._abbr; - } else { - newLocaleData = getLocale(key); - if (newLocaleData != null) { - this._locale = newLocaleData; + function loadLocale(name) { + var oldLocale = null, aliasedRequire; + if (locales[name] === void 0 && typeof module2 !== "undefined" && module2 && module2.exports && isLocaleNameSane(name)) { + try { + oldLocale = globalLocale._abbr; + aliasedRequire = __require; + aliasedRequire("./locale/" + name); + getSetGlobalLocale(oldLocale); + } catch (e) { + locales[name] = null; } - return this; } + return locales[name]; } - var lang = deprecate( - "moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.", - function(key) { - if (key === void 0) { - return this.localeData(); + function getSetGlobalLocale(key, values) { + var data; + if (key) { + if (isUndefined2(values)) { + data = getLocale(key); } else { - return this.locale(key); + data = defineLocale(key, values); + } + if (data) { + globalLocale = data; + } else { + if (typeof console !== "undefined" && console.warn) { + console.warn( + "Locale " + key + " not found. Did you forget to load it?" + ); + } } } - ); - function localeData() { - return this._locale; - } - var MS_PER_SECOND = 1e3, MS_PER_MINUTE = 60 * MS_PER_SECOND, MS_PER_HOUR = 60 * MS_PER_MINUTE, MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; - function mod$1(dividend, divisor) { - return (dividend % divisor + divisor) % divisor; + return globalLocale._abbr; } - function localStartOfDate(y2, m2, d) { - if (y2 < 100 && y2 >= 0) { - return new Date(y2 + 400, m2, d) - MS_PER_400_YEARS; + function defineLocale(name, config3) { + if (config3 !== null) { + var locale2, parentConfig = baseConfig; + config3.abbr = name; + if (locales[name] != null) { + deprecateSimple( + "defineLocaleOverride", + "use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info." + ); + parentConfig = locales[name]._config; + } else if (config3.parentLocale != null) { + if (locales[config3.parentLocale] != null) { + parentConfig = locales[config3.parentLocale]._config; + } else { + locale2 = loadLocale(config3.parentLocale); + if (locale2 != null) { + parentConfig = locale2._config; + } else { + if (!localeFamilies[config3.parentLocale]) { + localeFamilies[config3.parentLocale] = []; + } + localeFamilies[config3.parentLocale].push({ + name, + config: config3 + }); + return null; + } + } + } + locales[name] = new Locale(mergeConfigs(parentConfig, config3)); + if (localeFamilies[name]) { + localeFamilies[name].forEach(function(x2) { + defineLocale(x2.name, x2.config); + }); + } + getSetGlobalLocale(name); + return locales[name]; } else { - return new Date(y2, m2, d).valueOf(); + delete locales[name]; + return null; } } - function utcStartOfDate(y2, m2, d) { - if (y2 < 100 && y2 >= 0) { - return Date.UTC(y2 + 400, m2, d) - MS_PER_400_YEARS; + function updateLocale(name, config3) { + if (config3 != null) { + var locale2, tmpLocale, parentConfig = baseConfig; + if (locales[name] != null && locales[name].parentLocale != null) { + locales[name].set(mergeConfigs(locales[name]._config, config3)); + } else { + tmpLocale = loadLocale(name); + if (tmpLocale != null) { + parentConfig = tmpLocale._config; + } + config3 = mergeConfigs(parentConfig, config3); + if (tmpLocale == null) { + config3.abbr = name; + } + locale2 = new Locale(config3); + locale2.parentLocale = locales[name]; + locales[name] = locale2; + } + getSetGlobalLocale(name); } else { - return Date.UTC(y2, m2, d); + if (locales[name] != null) { + if (locales[name].parentLocale != null) { + locales[name] = locales[name].parentLocale; + if (name === getSetGlobalLocale()) { + getSetGlobalLocale(name); + } + } else if (locales[name] != null) { + delete locales[name]; + } + } } + return locales[name]; } - function startOf(units) { - var time, startOfDate; - units = normalizeUnits(units); - if (units === void 0 || units === "millisecond" || !this.isValid()) { - return this; + function getLocale(key) { + var locale2; + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; } - startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; - switch (units) { - case "year": - time = startOfDate(this.year(), 0, 1); - break; - case "quarter": - time = startOfDate( - this.year(), - this.month() - this.month() % 3, - 1 - ); - break; - case "month": - time = startOfDate(this.year(), this.month(), 1); - break; - case "week": - time = startOfDate( - this.year(), - this.month(), - this.date() - this.weekday() - ); - break; - case "isoWeek": - time = startOfDate( - this.year(), - this.month(), - this.date() - (this.isoWeekday() - 1) - ); - break; - case "day": - case "date": - time = startOfDate(this.year(), this.month(), this.date()); - break; - case "hour": - time = this._d.valueOf(); - time -= mod$1( - time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), - MS_PER_HOUR - ); - break; - case "minute": - time = this._d.valueOf(); - time -= mod$1(time, MS_PER_MINUTE); - break; - case "second": - time = this._d.valueOf(); - time -= mod$1(time, MS_PER_SECOND); - break; + if (!key) { + return globalLocale; } - this._d.setTime(time); - hooks.updateOffset(this, true); - return this; + if (!isArray2(key)) { + locale2 = loadLocale(key); + if (locale2) { + return locale2; + } + key = [key]; + } + return chooseLocale(key); } - function endOf(units) { - var time, startOfDate; - units = normalizeUnits(units); - if (units === void 0 || units === "millisecond" || !this.isValid()) { - return this; + function listLocales() { + return keys(locales); + } + function checkOverflow(m2) { + var overflow, a = m2._a; + if (a && getParsingFlags(m2).overflow === -2) { + overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1; + if (getParsingFlags(m2)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { + overflow = DATE; + } + if (getParsingFlags(m2)._overflowWeeks && overflow === -1) { + overflow = WEEK; + } + if (getParsingFlags(m2)._overflowWeekday && overflow === -1) { + overflow = WEEKDAY; + } + getParsingFlags(m2).overflow = overflow; } - startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; - switch (units) { - case "year": - time = startOfDate(this.year() + 1, 0, 1) - 1; - break; - case "quarter": - time = startOfDate( - this.year(), - this.month() - this.month() % 3 + 3, - 1 - ) - 1; - break; - case "month": - time = startOfDate(this.year(), this.month() + 1, 1) - 1; - break; - case "week": - time = startOfDate( - this.year(), - this.month(), - this.date() - this.weekday() + 7 - ) - 1; - break; - case "isoWeek": - time = startOfDate( - this.year(), - this.month(), - this.date() - (this.isoWeekday() - 1) + 7 - ) - 1; - break; - case "day": - case "date": - time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; - break; - case "hour": - time = this._d.valueOf(); - time += MS_PER_HOUR - mod$1( - time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), - MS_PER_HOUR - ) - 1; - break; - case "minute": - time = this._d.valueOf(); - time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; - break; - case "second": - time = this._d.valueOf(); - time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; - break; + return m2; + } + var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, isoDates = [ + ["YYYYYY-MM-DD", /[+-]\d{6}-\d\d-\d\d/], + ["YYYY-MM-DD", /\d{4}-\d\d-\d\d/], + ["GGGG-[W]WW-E", /\d{4}-W\d\d-\d/], + ["GGGG-[W]WW", /\d{4}-W\d\d/, false], + ["YYYY-DDD", /\d{4}-\d{3}/], + ["YYYY-MM", /\d{4}-\d\d/, false], + ["YYYYYYMMDD", /[+-]\d{10}/], + ["YYYYMMDD", /\d{8}/], + ["GGGG[W]WWE", /\d{4}W\d{3}/], + ["GGGG[W]WW", /\d{4}W\d{2}/, false], + ["YYYYDDD", /\d{7}/], + ["YYYYMM", /\d{6}/, false], + ["YYYY", /\d{4}/, false] + ], isoTimes = [ + ["HH:mm:ss.SSSS", /\d\d:\d\d:\d\d\.\d+/], + ["HH:mm:ss,SSSS", /\d\d:\d\d:\d\d,\d+/], + ["HH:mm:ss", /\d\d:\d\d:\d\d/], + ["HH:mm", /\d\d:\d\d/], + ["HHmmss.SSSS", /\d\d\d\d\d\d\.\d+/], + ["HHmmss,SSSS", /\d\d\d\d\d\d,\d+/], + ["HHmmss", /\d\d\d\d\d\d/], + ["HHmm", /\d\d\d\d/], + ["HH", /\d\d/] + ], aspNetJsonRegex = /^\/?Date\((-?\d+)/i, rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, obsOffsets = { + UT: 0, + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60 + }; + function configFromISO(config3) { + var i, l, string = config3._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat, isoDatesLen = isoDates.length, isoTimesLen = isoTimes.length; + if (match) { + getParsingFlags(config3).iso = true; + for (i = 0, l = isoDatesLen; i < l; i++) { + if (isoDates[i][1].exec(match[1])) { + dateFormat = isoDates[i][0]; + allowTime = isoDates[i][2] !== false; + break; + } + } + if (dateFormat == null) { + config3._isValid = false; + return; + } + if (match[3]) { + for (i = 0, l = isoTimesLen; i < l; i++) { + if (isoTimes[i][1].exec(match[3])) { + timeFormat = (match[2] || " ") + isoTimes[i][0]; + break; + } + } + if (timeFormat == null) { + config3._isValid = false; + return; + } + } + if (!allowTime && timeFormat != null) { + config3._isValid = false; + return; + } + if (match[4]) { + if (tzRegex.exec(match[4])) { + tzFormat = "Z"; + } else { + config3._isValid = false; + return; + } + } + config3._f = dateFormat + (timeFormat || "") + (tzFormat || ""); + configFromStringAndFormat(config3); + } else { + config3._isValid = false; } - this._d.setTime(time); - hooks.updateOffset(this, true); - return this; - } - function valueOf() { - return this._d.valueOf() - (this._offset || 0) * 6e4; - } - function unix() { - return Math.floor(this.valueOf() / 1e3); } - function toDate() { - return new Date(this.valueOf()); - } - function toArray2() { - var m2 = this; - return [ - m2.year(), - m2.month(), - m2.date(), - m2.hour(), - m2.minute(), - m2.second(), - m2.millisecond() + function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { + var result = [ + untruncateYear(yearStr), + defaultLocaleMonthsShort.indexOf(monthStr), + parseInt(dayStr, 10), + parseInt(hourStr, 10), + parseInt(minuteStr, 10) ]; + if (secondStr) { + result.push(parseInt(secondStr, 10)); + } + return result; } - function toObject() { - var m2 = this; - return { - years: m2.year(), - months: m2.month(), - date: m2.date(), - hours: m2.hours(), - minutes: m2.minutes(), - seconds: m2.seconds(), - milliseconds: m2.milliseconds() - }; + function untruncateYear(yearStr) { + var year = parseInt(yearStr, 10); + if (year <= 49) { + return 2e3 + year; + } else if (year <= 999) { + return 1900 + year; + } + return year; } - function toJSON2() { - return this.isValid() ? this.toISOString() : null; + function preprocessRFC2822(s) { + return s.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").replace(/^\s\s*/, "").replace(/\s\s*$/, ""); } - function isValid$2() { - return isValid(this); + function checkWeekday(weekdayStr, parsedInput, config3) { + if (weekdayStr) { + var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), weekdayActual = new Date( + parsedInput[0], + parsedInput[1], + parsedInput[2] + ).getDay(); + if (weekdayProvided !== weekdayActual) { + getParsingFlags(config3).weekdayMismatch = true; + config3._isValid = false; + return false; + } + } + return true; } - function parsingFlags() { - return extend2({}, getParsingFlags(this)); + function calculateOffset(obsOffset, militaryOffset, numOffset) { + if (obsOffset) { + return obsOffsets[obsOffset]; + } else if (militaryOffset) { + return 0; + } else { + var hm2 = parseInt(numOffset, 10), m2 = hm2 % 100, h = (hm2 - m2) / 100; + return h * 60 + m2; + } } - function invalidAt() { - return getParsingFlags(this).overflow; + function configFromRFC2822(config3) { + var match = rfc2822.exec(preprocessRFC2822(config3._i)), parsedArray; + if (match) { + parsedArray = extractFromRFC2822Strings( + match[4], + match[3], + match[2], + match[5], + match[6], + match[7] + ); + if (!checkWeekday(match[1], parsedArray, config3)) { + return; + } + config3._a = parsedArray; + config3._tzm = calculateOffset(match[8], match[9], match[10]); + config3._d = createUTCDate.apply(null, config3._a); + config3._d.setUTCMinutes(config3._d.getUTCMinutes() - config3._tzm); + getParsingFlags(config3).rfc2822 = true; + } else { + config3._isValid = false; + } } - function creationData() { - return { - input: this._i, - format: this._f, - locale: this._locale, - isUTC: this._isUTC, - strict: this._strict - }; + function configFromString(config3) { + var matched = aspNetJsonRegex.exec(config3._i); + if (matched !== null) { + config3._d = /* @__PURE__ */ new Date(+matched[1]); + return; + } + configFromISO(config3); + if (config3._isValid === false) { + delete config3._isValid; + } else { + return; + } + configFromRFC2822(config3); + if (config3._isValid === false) { + delete config3._isValid; + } else { + return; + } + if (config3._strict) { + config3._isValid = false; + } else { + hooks.createFromInputFallback(config3); + } } - addFormatToken("N", 0, 0, "eraAbbr"); - addFormatToken("NN", 0, 0, "eraAbbr"); - addFormatToken("NNN", 0, 0, "eraAbbr"); - addFormatToken("NNNN", 0, 0, "eraName"); - addFormatToken("NNNNN", 0, 0, "eraNarrow"); - addFormatToken("y", ["y", 1], "yo", "eraYear"); - addFormatToken("y", ["yy", 2], 0, "eraYear"); - addFormatToken("y", ["yyy", 3], 0, "eraYear"); - addFormatToken("y", ["yyyy", 4], 0, "eraYear"); - addRegexToken("N", matchEraAbbr); - addRegexToken("NN", matchEraAbbr); - addRegexToken("NNN", matchEraAbbr); - addRegexToken("NNNN", matchEraName); - addRegexToken("NNNNN", matchEraNarrow); - addParseToken( - ["N", "NN", "NNN", "NNNN", "NNNNN"], - function(input, array, config3, token2) { - var era = config3._locale.erasParse(input, token2, config3._strict); - if (era) { - getParsingFlags(config3).era = era; - } else { - getParsingFlags(config3).invalidEra = input; - } + hooks.createFromInputFallback = deprecate( + "value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.", + function(config3) { + config3._d = /* @__PURE__ */ new Date(config3._i + (config3._useUTC ? " UTC" : "")); } ); - addRegexToken("y", matchUnsigned); - addRegexToken("yy", matchUnsigned); - addRegexToken("yyy", matchUnsigned); - addRegexToken("yyyy", matchUnsigned); - addRegexToken("yo", matchEraYearOrdinal); - addParseToken(["y", "yy", "yyy", "yyyy"], YEAR); - addParseToken(["yo"], function(input, array, config3, token2) { - var match; - if (config3._locale._eraYearOrdinalRegex) { - match = input.match(config3._locale._eraYearOrdinalRegex); + function defaults2(a, b2, c) { + if (a != null) { + return a; } - if (config3._locale.eraYearOrdinalParse) { - array[YEAR] = config3._locale.eraYearOrdinalParse(input, match); - } else { - array[YEAR] = parseInt(input, 10); + if (b2 != null) { + return b2; } - }); - function localeEras(m2, format2) { - var i, l, date, eras = this._eras || getLocale("en")._eras; - for (i = 0, l = eras.length; i < l; ++i) { - switch (typeof eras[i].since) { - case "string": - date = hooks(eras[i].since).startOf("day"); - eras[i].since = date.valueOf(); - break; - } - switch (typeof eras[i].until) { - case "undefined": - eras[i].until = Infinity; - break; - case "string": - date = hooks(eras[i].until).startOf("day").valueOf(); - eras[i].until = date.valueOf(); - break; + return c; + } + function currentDateArray(config3) { + var nowValue = new Date(hooks.now()); + if (config3._useUTC) { + return [ + nowValue.getUTCFullYear(), + nowValue.getUTCMonth(), + nowValue.getUTCDate() + ]; + } + return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; + } + function configFromArray(config3) { + var i, date, input = [], currentDate, expectedWeekday, yearToUse; + if (config3._d) { + return; + } + currentDate = currentDateArray(config3); + if (config3._w && config3._a[DATE] == null && config3._a[MONTH] == null) { + dayOfYearFromWeekInfo(config3); + } + if (config3._dayOfYear != null) { + yearToUse = defaults2(config3._a[YEAR], currentDate[YEAR]); + if (config3._dayOfYear > daysInYear(yearToUse) || config3._dayOfYear === 0) { + getParsingFlags(config3)._overflowDayOfYear = true; } + date = createUTCDate(yearToUse, 0, config3._dayOfYear); + config3._a[MONTH] = date.getUTCMonth(); + config3._a[DATE] = date.getUTCDate(); + } + for (i = 0; i < 3 && config3._a[i] == null; ++i) { + config3._a[i] = input[i] = currentDate[i]; + } + for (; i < 7; i++) { + config3._a[i] = input[i] = config3._a[i] == null ? i === 2 ? 1 : 0 : config3._a[i]; + } + if (config3._a[HOUR] === 24 && config3._a[MINUTE] === 0 && config3._a[SECOND] === 0 && config3._a[MILLISECOND] === 0) { + config3._nextDay = true; + config3._a[HOUR] = 0; + } + config3._d = (config3._useUTC ? createUTCDate : createDate).apply( + null, + input + ); + expectedWeekday = config3._useUTC ? config3._d.getUTCDay() : config3._d.getDay(); + if (config3._tzm != null) { + config3._d.setUTCMinutes(config3._d.getUTCMinutes() - config3._tzm); + } + if (config3._nextDay) { + config3._a[HOUR] = 24; + } + if (config3._w && typeof config3._w.d !== "undefined" && config3._w.d !== expectedWeekday) { + getParsingFlags(config3).weekdayMismatch = true; } - return eras; } - function localeErasParse(eraName, format2, strict) { - var i, l, eras = this.eras(), name, abbr, narrow; - eraName = eraName.toUpperCase(); - for (i = 0, l = eras.length; i < l; ++i) { - name = eras[i].name.toUpperCase(); - abbr = eras[i].abbr.toUpperCase(); - narrow = eras[i].narrow.toUpperCase(); - if (strict) { - switch (format2) { - case "N": - case "NN": - case "NNN": - if (abbr === eraName) { - return eras[i]; - } - break; - case "NNNN": - if (name === eraName) { - return eras[i]; - } - break; - case "NNNNN": - if (narrow === eraName) { - return eras[i]; - } - break; + function dayOfYearFromWeekInfo(config3) { + var w2, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; + w2 = config3._w; + if (w2.GG != null || w2.W != null || w2.E != null) { + dow = 1; + doy = 4; + weekYear = defaults2( + w2.GG, + config3._a[YEAR], + weekOfYear(createLocal(), 1, 4).year + ); + week = defaults2(w2.W, 1); + weekday = defaults2(w2.E, 1); + if (weekday < 1 || weekday > 7) { + weekdayOverflow = true; + } + } else { + dow = config3._locale._week.dow; + doy = config3._locale._week.doy; + curWeek = weekOfYear(createLocal(), dow, doy); + weekYear = defaults2(w2.gg, config3._a[YEAR], curWeek.year); + week = defaults2(w2.w, curWeek.week); + if (w2.d != null) { + weekday = w2.d; + if (weekday < 0 || weekday > 6) { + weekdayOverflow = true; } - } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { - return eras[i]; + } else if (w2.e != null) { + weekday = w2.e + dow; + if (w2.e < 0 || w2.e > 6) { + weekdayOverflow = true; + } + } else { + weekday = dow; } } - } - function localeErasConvertYear(era, year) { - var dir = era.since <= era.until ? 1 : -1; - if (year === void 0) { - return hooks(era.since).year(); + if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { + getParsingFlags(config3)._overflowWeeks = true; + } else if (weekdayOverflow != null) { + getParsingFlags(config3)._overflowWeekday = true; } else { - return hooks(era.since).year() + (year - era.offset) * dir; + temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); + config3._a[YEAR] = temp.year; + config3._dayOfYear = temp.dayOfYear; } } - function getEraName() { - var i, l, val, eras = this.localeData().eras(); - for (i = 0, l = eras.length; i < l; ++i) { - val = this.clone().startOf("day").valueOf(); - if (eras[i].since <= val && val <= eras[i].until) { - return eras[i].name; + hooks.ISO_8601 = function() { + }; + hooks.RFC_2822 = function() { + }; + function configFromStringAndFormat(config3) { + if (config3._f === hooks.ISO_8601) { + configFromISO(config3); + return; + } + if (config3._f === hooks.RFC_2822) { + configFromRFC2822(config3); + return; + } + config3._a = []; + getParsingFlags(config3).empty = true; + var string = "" + config3._i, i, parsedInput, tokens2, token2, skipped, stringLength = string.length, totalParsedInputLength = 0, era, tokenLen; + tokens2 = expandFormat(config3._f, config3._locale).match(formattingTokens) || []; + tokenLen = tokens2.length; + for (i = 0; i < tokenLen; i++) { + token2 = tokens2[i]; + parsedInput = (string.match(getParseRegexForToken(token2, config3)) || [])[0]; + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config3).unusedInput.push(skipped); + } + string = string.slice( + string.indexOf(parsedInput) + parsedInput.length + ); + totalParsedInputLength += parsedInput.length; } - if (eras[i].until <= val && val <= eras[i].since) { - return eras[i].name; + if (formatTokenFunctions[token2]) { + if (parsedInput) { + getParsingFlags(config3).empty = false; + } else { + getParsingFlags(config3).unusedTokens.push(token2); + } + addTimeToArrayFromToken(token2, parsedInput, config3); + } else if (config3._strict && !parsedInput) { + getParsingFlags(config3).unusedTokens.push(token2); } } - return ""; + getParsingFlags(config3).charsLeftOver = stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config3).unusedInput.push(string); + } + if (config3._a[HOUR] <= 12 && getParsingFlags(config3).bigHour === true && config3._a[HOUR] > 0) { + getParsingFlags(config3).bigHour = void 0; + } + getParsingFlags(config3).parsedDateParts = config3._a.slice(0); + getParsingFlags(config3).meridiem = config3._meridiem; + config3._a[HOUR] = meridiemFixWrap( + config3._locale, + config3._a[HOUR], + config3._meridiem + ); + era = getParsingFlags(config3).era; + if (era !== null) { + config3._a[YEAR] = config3._locale.erasConvertYear(era, config3._a[YEAR]); + } + configFromArray(config3); + checkOverflow(config3); } - function getEraNarrow() { - var i, l, val, eras = this.localeData().eras(); - for (i = 0, l = eras.length; i < l; ++i) { - val = this.clone().startOf("day").valueOf(); - if (eras[i].since <= val && val <= eras[i].until) { - return eras[i].narrow; + function meridiemFixWrap(locale2, hour, meridiem2) { + var isPm; + if (meridiem2 == null) { + return hour; + } + if (locale2.meridiemHour != null) { + return locale2.meridiemHour(hour, meridiem2); + } else if (locale2.isPM != null) { + isPm = locale2.isPM(meridiem2); + if (isPm && hour < 12) { + hour += 12; } - if (eras[i].until <= val && val <= eras[i].since) { - return eras[i].narrow; + if (!isPm && hour === 12) { + hour = 0; } + return hour; + } else { + return hour; } - return ""; } - function getEraAbbr() { - var i, l, val, eras = this.localeData().eras(); - for (i = 0, l = eras.length; i < l; ++i) { - val = this.clone().startOf("day").valueOf(); - if (eras[i].since <= val && val <= eras[i].until) { - return eras[i].abbr; + function configFromStringAndArray(config3) { + var tempConfig, bestMoment, scoreToBeat, i, currentScore, validFormatFound, bestFormatIsValid = false, configfLen = config3._f.length; + if (configfLen === 0) { + getParsingFlags(config3).invalidFormat = true; + config3._d = /* @__PURE__ */ new Date(NaN); + return; + } + for (i = 0; i < configfLen; i++) { + currentScore = 0; + validFormatFound = false; + tempConfig = copyConfig({}, config3); + if (config3._useUTC != null) { + tempConfig._useUTC = config3._useUTC; } - if (eras[i].until <= val && val <= eras[i].since) { - return eras[i].abbr; + tempConfig._f = config3._f[i]; + configFromStringAndFormat(tempConfig); + if (isValid(tempConfig)) { + validFormatFound = true; } - } - return ""; - } - function getEraYear() { - var i, l, dir, val, eras = this.localeData().eras(); - for (i = 0, l = eras.length; i < l; ++i) { - dir = eras[i].since <= eras[i].until ? 1 : -1; - val = this.clone().startOf("day").valueOf(); - if (eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) { - return (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset; + currentScore += getParsingFlags(tempConfig).charsLeftOver; + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + getParsingFlags(tempConfig).score = currentScore; + if (!bestFormatIsValid) { + if (scoreToBeat == null || currentScore < scoreToBeat || validFormatFound) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + if (validFormatFound) { + bestFormatIsValid = true; + } + } + } else { + if (currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } } } - return this.year(); + extend2(config3, bestMoment || tempConfig); } - function erasNameRegex(isStrict) { - if (!hasOwnProp(this, "_erasNameRegex")) { - computeErasParse.call(this); + function configFromObject(config3) { + if (config3._d) { + return; } - return isStrict ? this._erasNameRegex : this._erasRegex; + var i = normalizeObjectUnits(config3._i), dayOrDate = i.day === void 0 ? i.date : i.day; + config3._a = map( + [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], + function(obj) { + return obj && parseInt(obj, 10); + } + ); + configFromArray(config3); } - function erasAbbrRegex(isStrict) { - if (!hasOwnProp(this, "_erasAbbrRegex")) { - computeErasParse.call(this); + function createFromConfig(config3) { + var res = new Moment(checkOverflow(prepareConfig(config3))); + if (res._nextDay) { + res.add(1, "d"); + res._nextDay = void 0; } - return isStrict ? this._erasAbbrRegex : this._erasRegex; + return res; } - function erasNarrowRegex(isStrict) { - if (!hasOwnProp(this, "_erasNarrowRegex")) { - computeErasParse.call(this); + function prepareConfig(config3) { + var input = config3._i, format2 = config3._f; + config3._locale = config3._locale || getLocale(config3._l); + if (input === null || format2 === void 0 && input === "") { + return createInvalid({ nullInput: true }); } - return isStrict ? this._erasNarrowRegex : this._erasRegex; - } - function matchEraAbbr(isStrict, locale2) { - return locale2.erasAbbrRegex(isStrict); - } - function matchEraName(isStrict, locale2) { - return locale2.erasNameRegex(isStrict); - } - function matchEraNarrow(isStrict, locale2) { - return locale2.erasNarrowRegex(isStrict); - } - function matchEraYearOrdinal(isStrict, locale2) { - return locale2._eraYearOrdinalRegex || matchUnsigned; - } - function computeErasParse() { - var abbrPieces = [], namePieces = [], narrowPieces = [], mixedPieces = [], i, l, erasName, erasAbbr, erasNarrow, eras = this.eras(); - for (i = 0, l = eras.length; i < l; ++i) { - erasName = regexEscape(eras[i].name); - erasAbbr = regexEscape(eras[i].abbr); - erasNarrow = regexEscape(eras[i].narrow); - namePieces.push(erasName); - abbrPieces.push(erasAbbr); - narrowPieces.push(erasNarrow); - mixedPieces.push(erasName); - mixedPieces.push(erasAbbr); - mixedPieces.push(erasNarrow); + if (typeof input === "string") { + config3._i = input = config3._locale.preparse(input); } - this._erasRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); - this._erasNameRegex = new RegExp("^(" + namePieces.join("|") + ")", "i"); - this._erasAbbrRegex = new RegExp("^(" + abbrPieces.join("|") + ")", "i"); - this._erasNarrowRegex = new RegExp( - "^(" + narrowPieces.join("|") + ")", - "i" - ); - } - addFormatToken(0, ["gg", 2], 0, function() { - return this.weekYear() % 100; - }); - addFormatToken(0, ["GG", 2], 0, function() { - return this.isoWeekYear() % 100; - }); - function addWeekYearFormatToken(token2, getter) { - addFormatToken(0, [token2, token2.length], 0, getter); - } - addWeekYearFormatToken("gggg", "weekYear"); - addWeekYearFormatToken("ggggg", "weekYear"); - addWeekYearFormatToken("GGGG", "isoWeekYear"); - addWeekYearFormatToken("GGGGG", "isoWeekYear"); - addRegexToken("G", matchSigned); - addRegexToken("g", matchSigned); - addRegexToken("GG", match1to2, match2); - addRegexToken("gg", match1to2, match2); - addRegexToken("GGGG", match1to4, match4); - addRegexToken("gggg", match1to4, match4); - addRegexToken("GGGGG", match1to6, match6); - addRegexToken("ggggg", match1to6, match6); - addWeekParseToken( - ["gggg", "ggggg", "GGGG", "GGGGG"], - function(input, week, config3, token2) { - week[token2.substr(0, 2)] = toInt(input); + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isDate2(input)) { + config3._d = input; + } else if (isArray2(format2)) { + configFromStringAndArray(config3); + } else if (format2) { + configFromStringAndFormat(config3); + } else { + configFromInput(config3); } - ); - addWeekParseToken(["gg", "GG"], function(input, week, config3, token2) { - week[token2] = hooks.parseTwoDigitYear(input); - }); - function getSetWeekYear(input) { - return getSetWeekYearHelper.call( - this, - input, - this.week(), - this.weekday() + this.localeData()._week.dow, - this.localeData()._week.dow, - this.localeData()._week.doy - ); - } - function getSetISOWeekYear(input) { - return getSetWeekYearHelper.call( - this, - input, - this.isoWeek(), - this.isoWeekday(), - 1, - 4 - ); - } - function getISOWeeksInYear() { - return weeksInYear(this.year(), 1, 4); - } - function getISOWeeksInISOWeekYear() { - return weeksInYear(this.isoWeekYear(), 1, 4); - } - function getWeeksInYear() { - var weekInfo = this.localeData()._week; - return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); - } - function getWeeksInWeekYear() { - var weekInfo = this.localeData()._week; - return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); + if (!isValid(config3)) { + config3._d = null; + } + return config3; } - function getSetWeekYearHelper(input, week, weekday, dow, doy) { - var weeksTarget; - if (input == null) { - return weekOfYear(this, dow, doy).year; + function configFromInput(config3) { + var input = config3._i; + if (isUndefined2(input)) { + config3._d = new Date(hooks.now()); + } else if (isDate2(input)) { + config3._d = new Date(input.valueOf()); + } else if (typeof input === "string") { + configFromString(config3); + } else if (isArray2(input)) { + config3._a = map(input.slice(0), function(obj) { + return parseInt(obj, 10); + }); + configFromArray(config3); + } else if (isObject2(input)) { + configFromObject(config3); + } else if (isNumber2(input)) { + config3._d = new Date(input); } else { - weeksTarget = weeksInYear(input, dow, doy); - if (week > weeksTarget) { - week = weeksTarget; - } - return setWeekAll.call(this, input, week, weekday, dow, doy); + hooks.createFromInputFallback(config3); } } - function setWeekAll(weekYear, week, weekday, dow, doy) { - var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); - this.year(date.getUTCFullYear()); - this.month(date.getUTCMonth()); - this.date(date.getUTCDate()); - return this; - } - addFormatToken("Q", 0, "Qo", "quarter"); - addRegexToken("Q", match1); - addParseToken("Q", function(input, array) { - array[MONTH] = (toInt(input) - 1) * 3; - }); - function getSetQuarter(input) { - return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); - } - addFormatToken("D", ["DD", 2], "Do", "date"); - addRegexToken("D", match1to2, match1to2NoLeadingZero); - addRegexToken("DD", match1to2, match2); - addRegexToken("Do", function(isStrict, locale2) { - return isStrict ? locale2._dayOfMonthOrdinalParse || locale2._ordinalParse : locale2._dayOfMonthOrdinalParseLenient; - }); - addParseToken(["D", "DD"], DATE); - addParseToken("Do", function(input, array) { - array[DATE] = toInt(input.match(match1to2)[0]); - }); - var getSetDayOfMonth = makeGetSet("Date", true); - addFormatToken("DDD", ["DDDD", 3], "DDDo", "dayOfYear"); - addRegexToken("DDD", match1to3); - addRegexToken("DDDD", match3); - addParseToken(["DDD", "DDDD"], function(input, array, config3) { - config3._dayOfYear = toInt(input); - }); - function getSetDayOfYear(input) { - var dayOfYear = Math.round( - (this.clone().startOf("day") - this.clone().startOf("year")) / 864e5 - ) + 1; - return input == null ? dayOfYear : this.add(input - dayOfYear, "d"); - } - addFormatToken("m", ["mm", 2], 0, "minute"); - addRegexToken("m", match1to2, match1to2HasZero); - addRegexToken("mm", match1to2, match2); - addParseToken(["m", "mm"], MINUTE); - var getSetMinute = makeGetSet("Minutes", false); - addFormatToken("s", ["ss", 2], 0, "second"); - addRegexToken("s", match1to2, match1to2HasZero); - addRegexToken("ss", match1to2, match2); - addParseToken(["s", "ss"], SECOND); - var getSetSecond = makeGetSet("Seconds", false); - addFormatToken("S", 0, 0, function() { - return ~~(this.millisecond() / 100); - }); - addFormatToken(0, ["SS", 2], 0, function() { - return ~~(this.millisecond() / 10); - }); - addFormatToken(0, ["SSS", 3], 0, "millisecond"); - addFormatToken(0, ["SSSS", 4], 0, function() { - return this.millisecond() * 10; - }); - addFormatToken(0, ["SSSSS", 5], 0, function() { - return this.millisecond() * 100; - }); - addFormatToken(0, ["SSSSSS", 6], 0, function() { - return this.millisecond() * 1e3; - }); - addFormatToken(0, ["SSSSSSS", 7], 0, function() { - return this.millisecond() * 1e4; - }); - addFormatToken(0, ["SSSSSSSS", 8], 0, function() { - return this.millisecond() * 1e5; - }); - addFormatToken(0, ["SSSSSSSSS", 9], 0, function() { - return this.millisecond() * 1e6; - }); - addRegexToken("S", match1to3, match1); - addRegexToken("SS", match1to3, match2); - addRegexToken("SSS", match1to3, match3); - var token, getSetMillisecond; - for (token = "SSSS"; token.length <= 9; token += "S") { - addRegexToken(token, matchUnsigned); - } - function parseMs(input, array) { - array[MILLISECOND] = toInt(("0." + input) * 1e3); - } - for (token = "S"; token.length <= 9; token += "S") { - addParseToken(token, parseMs); - } - getSetMillisecond = makeGetSet("Milliseconds", false); - addFormatToken("z", 0, 0, "zoneAbbr"); - addFormatToken("zz", 0, 0, "zoneName"); - function getZoneAbbr() { - return this._isUTC ? "UTC" : ""; - } - function getZoneName() { - return this._isUTC ? "Coordinated Universal Time" : ""; + function createLocalOrUTC(input, format2, locale2, strict, isUTC) { + var c = {}; + if (format2 === true || format2 === false) { + strict = format2; + format2 = void 0; + } + if (locale2 === true || locale2 === false) { + strict = locale2; + locale2 = void 0; + } + if (isObject2(input) && isObjectEmpty(input) || isArray2(input) && input.length === 0) { + input = void 0; + } + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale2; + c._i = input; + c._f = format2; + c._strict = strict; + return createFromConfig(c); } - var proto = Moment.prototype; - proto.add = add; - proto.calendar = calendar$1; - proto.clone = clone; - proto.diff = diff; - proto.endOf = endOf; - proto.format = format; - proto.from = from5; - proto.fromNow = fromNow; - proto.to = to2; - proto.toNow = toNow; - proto.get = stringGet; - proto.invalidAt = invalidAt; - proto.isAfter = isAfter; - proto.isBefore = isBefore; - proto.isBetween = isBetween; - proto.isSame = isSame; - proto.isSameOrAfter = isSameOrAfter; - proto.isSameOrBefore = isSameOrBefore; - proto.isValid = isValid$2; - proto.lang = lang; - proto.locale = locale; - proto.localeData = localeData; - proto.max = prototypeMax; - proto.min = prototypeMin; - proto.parsingFlags = parsingFlags; - proto.set = stringSet; - proto.startOf = startOf; - proto.subtract = subtract; - proto.toArray = toArray2; - proto.toObject = toObject; - proto.toDate = toDate; - proto.toISOString = toISOString; - proto.inspect = inspect; - if (typeof Symbol !== "undefined" && Symbol.for != null) { - proto[Symbol.for("nodejs.util.inspect.custom")] = function() { - return "Moment<" + this.format() + ">"; - }; + function createLocal(input, format2, locale2, strict) { + return createLocalOrUTC(input, format2, locale2, strict, false); } - proto.toJSON = toJSON2; - proto.toString = toString3; - proto.unix = unix; - proto.valueOf = valueOf; - proto.creationData = creationData; - proto.eraName = getEraName; - proto.eraNarrow = getEraNarrow; - proto.eraAbbr = getEraAbbr; - proto.eraYear = getEraYear; - proto.year = getSetYear; - proto.isLeapYear = getIsLeapYear; - proto.weekYear = getSetWeekYear; - proto.isoWeekYear = getSetISOWeekYear; - proto.quarter = proto.quarters = getSetQuarter; - proto.month = getSetMonth; - proto.daysInMonth = getDaysInMonth; - proto.week = proto.weeks = getSetWeek; - proto.isoWeek = proto.isoWeeks = getSetISOWeek; - proto.weeksInYear = getWeeksInYear; - proto.weeksInWeekYear = getWeeksInWeekYear; - proto.isoWeeksInYear = getISOWeeksInYear; - proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear; - proto.date = getSetDayOfMonth; - proto.day = proto.days = getSetDayOfWeek; - proto.weekday = getSetLocaleDayOfWeek; - proto.isoWeekday = getSetISODayOfWeek; - proto.dayOfYear = getSetDayOfYear; - proto.hour = proto.hours = getSetHour; - proto.minute = proto.minutes = getSetMinute; - proto.second = proto.seconds = getSetSecond; - proto.millisecond = proto.milliseconds = getSetMillisecond; - proto.utcOffset = getSetOffset; - proto.utc = setOffsetToUTC; - proto.local = setOffsetToLocal; - proto.parseZone = setOffsetToParsedOffset; - proto.hasAlignedHourOffset = hasAlignedHourOffset; - proto.isDST = isDaylightSavingTime; - proto.isLocal = isLocal; - proto.isUtcOffset = isUtcOffset; - proto.isUtc = isUtc; - proto.isUTC = isUtc; - proto.zoneAbbr = getZoneAbbr; - proto.zoneName = getZoneName; - proto.dates = deprecate( - "dates accessor is deprecated. Use date instead.", - getSetDayOfMonth - ); - proto.months = deprecate( - "months accessor is deprecated. Use month instead", - getSetMonth - ); - proto.years = deprecate( - "years accessor is deprecated. Use year instead", - getSetYear - ); - proto.zone = deprecate( - "moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/", - getSetZone - ); - proto.isDSTShifted = deprecate( - "isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information", - isDaylightSavingTimeShifted + var prototypeMin = deprecate( + "moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/", + function() { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other < this ? this : other; + } else { + return createInvalid(); + } + } + ), prototypeMax = deprecate( + "moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/", + function() { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other > this ? this : other; + } else { + return createInvalid(); + } + } ); - function createUnix(input) { - return createLocal(input * 1e3); - } - function createInZone() { - return createLocal.apply(null, arguments).parseZone(); - } - function preParsePostFormat(string) { - return string; - } - var proto$1 = Locale.prototype; - proto$1.calendar = calendar; - proto$1.longDateFormat = longDateFormat; - proto$1.invalidDate = invalidDate; - proto$1.ordinal = ordinal; - proto$1.preparse = preParsePostFormat; - proto$1.postformat = preParsePostFormat; - proto$1.relativeTime = relativeTime; - proto$1.pastFuture = pastFuture; - proto$1.set = set; - proto$1.eras = localeEras; - proto$1.erasParse = localeErasParse; - proto$1.erasConvertYear = localeErasConvertYear; - proto$1.erasAbbrRegex = erasAbbrRegex; - proto$1.erasNameRegex = erasNameRegex; - proto$1.erasNarrowRegex = erasNarrowRegex; - proto$1.months = localeMonths; - proto$1.monthsShort = localeMonthsShort; - proto$1.monthsParse = localeMonthsParse; - proto$1.monthsRegex = monthsRegex; - proto$1.monthsShortRegex = monthsShortRegex; - proto$1.week = localeWeek; - proto$1.firstDayOfYear = localeFirstDayOfYear; - proto$1.firstDayOfWeek = localeFirstDayOfWeek; - proto$1.weekdays = localeWeekdays; - proto$1.weekdaysMin = localeWeekdaysMin; - proto$1.weekdaysShort = localeWeekdaysShort; - proto$1.weekdaysParse = localeWeekdaysParse; - proto$1.weekdaysRegex = weekdaysRegex; - proto$1.weekdaysShortRegex = weekdaysShortRegex; - proto$1.weekdaysMinRegex = weekdaysMinRegex; - proto$1.isPM = localeIsPM; - proto$1.meridiem = localeMeridiem; - function get$1(format2, index2, field, setter) { - var locale2 = getLocale(), utc = createUTC().set(setter, index2); - return locale2[field](utc, format2); - } - function listMonthsImpl(format2, index2, field) { - if (isNumber2(format2)) { - index2 = format2; - format2 = void 0; + function pickBy(fn2, moments) { + var res, i; + if (moments.length === 1 && isArray2(moments[0])) { + moments = moments[0]; } - format2 = format2 || ""; - if (index2 != null) { - return get$1(format2, index2, field, "month"); + if (!moments.length) { + return createLocal(); } - var i, out = []; - for (i = 0; i < 12; i++) { - out[i] = get$1(format2, i, field, "month"); + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (!moments[i].isValid() || moments[i][fn2](res)) { + res = moments[i]; + } } - return out; + return res; } - function listWeekdaysImpl(localeSorted, format2, index2, field) { - if (typeof localeSorted === "boolean") { - if (isNumber2(format2)) { - index2 = format2; - format2 = void 0; - } - format2 = format2 || ""; - } else { - format2 = localeSorted; - index2 = format2; - localeSorted = false; - if (isNumber2(format2)) { - index2 = format2; - format2 = void 0; + function min() { + var args = [].slice.call(arguments, 0); + return pickBy("isBefore", args); + } + function max() { + var args = [].slice.call(arguments, 0); + return pickBy("isAfter", args); + } + var now = function() { + return Date.now ? Date.now() : +/* @__PURE__ */ new Date(); + }; + var ordering = [ + "year", + "quarter", + "month", + "week", + "day", + "hour", + "minute", + "second", + "millisecond" + ]; + function isDurationValid(m2) { + var key, unitHasDecimal = false, i, orderLen = ordering.length; + for (key in m2) { + if (hasOwnProp(m2, key) && !(indexOf.call(ordering, key) !== -1 && (m2[key] == null || !isNaN(m2[key])))) { + return false; } - format2 = format2 || ""; - } - var locale2 = getLocale(), shift = localeSorted ? locale2._week.dow : 0, i, out = []; - if (index2 != null) { - return get$1(format2, (index2 + shift) % 7, field, "day"); } - for (i = 0; i < 7; i++) { - out[i] = get$1(format2, (i + shift) % 7, field, "day"); + for (i = 0; i < orderLen; ++i) { + if (m2[ordering[i]]) { + if (unitHasDecimal) { + return false; + } + if (parseFloat(m2[ordering[i]]) !== toInt(m2[ordering[i]])) { + unitHasDecimal = true; + } + } } - return out; + return true; } - function listMonths(format2, index2) { - return listMonthsImpl(format2, index2, "months"); + function isValid$1() { + return this._isValid; } - function listMonthsShort(format2, index2) { - return listMonthsImpl(format2, index2, "monthsShort"); + function createInvalid$1() { + return createDuration(NaN); } - function listWeekdays(localeSorted, format2, index2) { - return listWeekdaysImpl(localeSorted, format2, index2, "weekdays"); + function Duration(duration) { + var normalizedInput = normalizeObjectUnits(duration), years2 = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months2 = normalizedInput.month || 0, weeks2 = normalizedInput.week || normalizedInput.isoWeek || 0, days2 = normalizedInput.day || 0, hours2 = normalizedInput.hour || 0, minutes2 = normalizedInput.minute || 0, seconds2 = normalizedInput.second || 0, milliseconds2 = normalizedInput.millisecond || 0; + this._isValid = isDurationValid(normalizedInput); + this._milliseconds = +milliseconds2 + seconds2 * 1e3 + // 1000 + minutes2 * 6e4 + // 1000 * 60 + hours2 * 1e3 * 60 * 60; + this._days = +days2 + weeks2 * 7; + this._months = +months2 + quarters * 3 + years2 * 12; + this._data = {}; + this._locale = getLocale(); + this._bubble(); } - function listWeekdaysShort(localeSorted, format2, index2) { - return listWeekdaysImpl(localeSorted, format2, index2, "weekdaysShort"); + function isDuration(obj) { + return obj instanceof Duration; } - function listWeekdaysMin(localeSorted, format2, index2) { - return listWeekdaysImpl(localeSorted, format2, index2, "weekdaysMin"); + function absRound(number) { + if (number < 0) { + return Math.round(-1 * number) * -1; + } else { + return Math.round(number); + } } - getSetGlobalLocale("en", { - eras: [ - { - since: "0001-01-01", - until: Infinity, - offset: 1, - name: "Anno Domini", - narrow: "AD", - abbr: "AD" - }, - { - since: "0000-12-31", - until: -Infinity, - offset: 1, - name: "Before Christ", - narrow: "BC", - abbr: "BC" + function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; + for (i = 0; i < len; i++) { + if (dontConvert && array1[i] !== array2[i] || !dontConvert && toInt(array1[i]) !== toInt(array2[i])) { + diffs++; } - ], - dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, - ordinal: function(number) { - var b2 = number % 10, output = toInt(number % 100 / 10) === 1 ? "th" : b2 === 1 ? "st" : b2 === 2 ? "nd" : b2 === 3 ? "rd" : "th"; - return number + output; } + return diffs + lengthDiff; + } + function offset(token2, separator) { + addFormatToken(token2, 0, 0, function() { + var offset2 = this.utcOffset(), sign3 = "+"; + if (offset2 < 0) { + offset2 = -offset2; + sign3 = "-"; + } + return sign3 + zeroFill(~~(offset2 / 60), 2) + separator + zeroFill(~~offset2 % 60, 2); + }); + } + offset("Z", ":"); + offset("ZZ", ""); + addRegexToken("Z", matchShortOffset); + addRegexToken("ZZ", matchShortOffset); + addParseToken(["Z", "ZZ"], function(input, array, config3) { + config3._useUTC = true; + config3._tzm = offsetFromString(matchShortOffset, input); }); - hooks.lang = deprecate( - "moment.lang is deprecated. Use moment.locale instead.", - getSetGlobalLocale - ); - hooks.langData = deprecate( - "moment.langData is deprecated. Use moment.localeData instead.", - getLocale - ); - var mathAbs = Math.abs; - function abs() { - var data = this._data; - this._milliseconds = mathAbs(this._milliseconds); - this._days = mathAbs(this._days); - this._months = mathAbs(this._months); - data.milliseconds = mathAbs(data.milliseconds); - data.seconds = mathAbs(data.seconds); - data.minutes = mathAbs(data.minutes); - data.hours = mathAbs(data.hours); - data.months = mathAbs(data.months); - data.years = mathAbs(data.years); - return this; + var chunkOffset = /([\+\-]|\d\d)/gi; + function offsetFromString(matcher, string) { + var matches = (string || "").match(matcher), chunk, parts, minutes2; + if (matches === null) { + return null; + } + chunk = matches[matches.length - 1] || []; + parts = (chunk + "").match(chunkOffset) || ["-", 0, 0]; + minutes2 = +(parts[1] * 60) + toInt(parts[2]); + return minutes2 === 0 ? 0 : parts[0] === "+" ? minutes2 : -minutes2; } - function addSubtract$1(duration, input, value, direction) { - var other = createDuration(input, value); - duration._milliseconds += direction * other._milliseconds; - duration._days += direction * other._days; - duration._months += direction * other._months; - return duration._bubble(); + function cloneWithOffset(input, model) { + var res, diff2; + if (model._isUTC) { + res = model.clone(); + diff2 = (isMoment(input) || isDate2(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); + res._d.setTime(res._d.valueOf() + diff2); + hooks.updateOffset(res, false); + return res; + } else { + return createLocal(input).local(); + } } - function add$1(input, value) { - return addSubtract$1(this, input, value, 1); + function getDateOffset(m2) { + return -Math.round(m2._d.getTimezoneOffset()); } - function subtract$1(input, value) { - return addSubtract$1(this, input, value, -1); + hooks.updateOffset = function() { + }; + function getSetOffset(input, keepLocalTime, keepMinutes) { + var offset2 = this._offset || 0, localAdjust; + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + if (typeof input === "string") { + input = offsetFromString(matchShortOffset, input); + if (input === null) { + return this; + } + } else if (Math.abs(input) < 16 && !keepMinutes) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, "m"); + } + if (offset2 !== input) { + if (!keepLocalTime || this._changeInProgress) { + addSubtract( + this, + createDuration(input - offset2, "m"), + 1, + false + ); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset2 : getDateOffset(this); + } } - function absCeil(number) { - if (number < 0) { - return Math.floor(number); + function getSetZone(input, keepLocalTime) { + if (input != null) { + if (typeof input !== "string") { + input = -input; + } + this.utcOffset(input, keepLocalTime); + return this; } else { - return Math.ceil(number); + return -this.utcOffset(); } } - function bubble() { - var milliseconds2 = this._milliseconds, days2 = this._days, months2 = this._months, data = this._data, seconds2, minutes2, hours2, years2, monthsFromDays; - if (!(milliseconds2 >= 0 && days2 >= 0 && months2 >= 0 || milliseconds2 <= 0 && days2 <= 0 && months2 <= 0)) { - milliseconds2 += absCeil(monthsToDays(months2) + days2) * 864e5; - days2 = 0; - months2 = 0; + function setOffsetToUTC(keepLocalTime) { + return this.utcOffset(0, keepLocalTime); + } + function setOffsetToLocal(keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; + if (keepLocalTime) { + this.subtract(getDateOffset(this), "m"); + } } - data.milliseconds = milliseconds2 % 1e3; - seconds2 = absFloor(milliseconds2 / 1e3); - data.seconds = seconds2 % 60; - minutes2 = absFloor(seconds2 / 60); - data.minutes = minutes2 % 60; - hours2 = absFloor(minutes2 / 60); - data.hours = hours2 % 24; - days2 += absFloor(hours2 / 24); - monthsFromDays = absFloor(daysToMonths(days2)); - months2 += monthsFromDays; - days2 -= absCeil(monthsToDays(monthsFromDays)); - years2 = absFloor(months2 / 12); - months2 %= 12; - data.days = days2; - data.months = months2; - data.years = years2; return this; } - function daysToMonths(days2) { - return days2 * 4800 / 146097; - } - function monthsToDays(months2) { - return months2 * 146097 / 4800; + function setOffsetToParsedOffset() { + if (this._tzm != null) { + this.utcOffset(this._tzm, false, true); + } else if (typeof this._i === "string") { + var tZone = offsetFromString(matchOffset, this._i); + if (tZone != null) { + this.utcOffset(tZone); + } else { + this.utcOffset(0, true); + } + } + return this; } - function as2(units) { + function hasAlignedHourOffset(input) { if (!this.isValid()) { - return NaN; + return false; } - var days2, months2, milliseconds2 = this._milliseconds; - units = normalizeUnits(units); - if (units === "month" || units === "quarter" || units === "year") { - days2 = this._days + milliseconds2 / 864e5; - months2 = this._months + daysToMonths(days2); - switch (units) { - case "month": - return months2; - case "quarter": - return months2 / 3; - case "year": - return months2 / 12; - } + input = input ? createLocal(input).utcOffset() : 0; + return (this.utcOffset() - input) % 60 === 0; + } + function isDaylightSavingTime() { + return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset(); + } + function isDaylightSavingTimeShifted() { + if (!isUndefined2(this._isDSTShifted)) { + return this._isDSTShifted; + } + var c = {}, other; + copyConfig(c, this); + c = prepareConfig(c); + if (c._a) { + other = c._isUTC ? createUTC(c._a) : createLocal(c._a); + this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0; } else { - days2 = this._days + Math.round(monthsToDays(this._months)); - switch (units) { - case "week": - return days2 / 7 + milliseconds2 / 6048e5; - case "day": - return days2 + milliseconds2 / 864e5; - case "hour": - return days2 * 24 + milliseconds2 / 36e5; - case "minute": - return days2 * 1440 + milliseconds2 / 6e4; - case "second": - return days2 * 86400 + milliseconds2 / 1e3; - // Math.floor prevents floating point math errors here - case "millisecond": - return Math.floor(days2 * 864e5) + milliseconds2; - default: - throw new Error("Unknown unit " + units); + this._isDSTShifted = false; + } + return this._isDSTShifted; + } + function isLocal() { + return this.isValid() ? !this._isUTC : false; + } + function isUtcOffset() { + return this.isValid() ? this._isUTC : false; + } + function isUtc() { + return this.isValid() ? this._isUTC && this._offset === 0 : false; + } + var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; + function createDuration(input, key) { + var duration = input, match = null, sign3, ret, diffRes; + if (isDuration(input)) { + duration = { + ms: input._milliseconds, + d: input._days, + M: input._months + }; + } else if (isNumber2(input) || !isNaN(+input)) { + duration = {}; + if (key) { + duration[key] = +input; + } else { + duration.milliseconds = +input; } + } else if (match = aspNetRegex.exec(input)) { + sign3 = match[1] === "-" ? -1 : 1; + duration = { + y: 0, + d: toInt(match[DATE]) * sign3, + h: toInt(match[HOUR]) * sign3, + m: toInt(match[MINUTE]) * sign3, + s: toInt(match[SECOND]) * sign3, + ms: toInt(absRound(match[MILLISECOND] * 1e3)) * sign3 + // the millisecond decimal point is included in the match + }; + } else if (match = isoRegex.exec(input)) { + sign3 = match[1] === "-" ? -1 : 1; + duration = { + y: parseIso(match[2], sign3), + M: parseIso(match[3], sign3), + w: parseIso(match[4], sign3), + d: parseIso(match[5], sign3), + h: parseIso(match[6], sign3), + m: parseIso(match[7], sign3), + s: parseIso(match[8], sign3) + }; + } else if (duration == null) { + duration = {}; + } else if (typeof duration === "object" && ("from" in duration || "to" in duration)) { + diffRes = momentsDifference( + createLocal(duration.from), + createLocal(duration.to) + ); + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } + ret = new Duration(duration); + if (isDuration(input) && hasOwnProp(input, "_locale")) { + ret._locale = input._locale; + } + if (isDuration(input) && hasOwnProp(input, "_isValid")) { + ret._isValid = input._isValid; } + return ret; } - function makeAs(alias) { - return function() { - return this.as(alias); - }; + createDuration.fn = Duration.prototype; + createDuration.invalid = createInvalid$1; + function parseIso(inp, sign3) { + var res = inp && parseFloat(inp.replace(",", ".")); + return (isNaN(res) ? 0 : res) * sign3; } - var asMilliseconds = makeAs("ms"), asSeconds = makeAs("s"), asMinutes = makeAs("m"), asHours = makeAs("h"), asDays = makeAs("d"), asWeeks = makeAs("w"), asMonths = makeAs("M"), asQuarters = makeAs("Q"), asYears = makeAs("y"), valueOf$1 = asMilliseconds; - function clone$1() { - return createDuration(this); + function positiveMomentsDifference(base, other) { + var res = {}; + res.months = other.month() - base.month() + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, "M").isAfter(other)) { + --res.months; + } + res.milliseconds = +other - +base.clone().add(res.months, "M"); + return res; } - function get$2(units) { - units = normalizeUnits(units); - return this.isValid() ? this[units + "s"]() : NaN; + function momentsDifference(base, other) { + var res; + if (!(base.isValid() && other.isValid())) { + return { milliseconds: 0, months: 0 }; + } + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } + return res; } - function makeGetter(name) { - return function() { - return this.isValid() ? this._data[name] : NaN; + function createAdder(direction, name) { + return function(val, period) { + var dur, tmp; + if (period !== null && !isNaN(+period)) { + deprecateSimple( + name, + "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info." + ); + tmp = val; + val = period; + period = tmp; + } + dur = createDuration(val, period); + addSubtract(this, dur, direction); + return this; }; } - var milliseconds = makeGetter("milliseconds"), seconds = makeGetter("seconds"), minutes = makeGetter("minutes"), hours = makeGetter("hours"), days = makeGetter("days"), months = makeGetter("months"), years = makeGetter("years"); - function weeks() { - return absFloor(this.days() / 7); + function addSubtract(mom, duration, isAdding, updateOffset) { + var milliseconds2 = duration._milliseconds, days2 = absRound(duration._days), months2 = absRound(duration._months); + if (!mom.isValid()) { + return; + } + updateOffset = updateOffset == null ? true : updateOffset; + if (months2) { + setMonth(mom, get(mom, "Month") + months2 * isAdding); + } + if (days2) { + set$1(mom, "Date", get(mom, "Date") + days2 * isAdding); + } + if (milliseconds2) { + mom._d.setTime(mom._d.valueOf() + milliseconds2 * isAdding); + } + if (updateOffset) { + hooks.updateOffset(mom, days2 || months2); + } } - var round = Math.round, thresholds = { - ss: 44, - // a few seconds to seconds - s: 45, - // seconds to minute - m: 45, - // minutes to hour - h: 22, - // hours to day - d: 26, - // days to month/week - w: null, - // weeks to month - M: 11 - // months to year - }; - function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale2) { - return locale2.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + var add = createAdder(1, "add"), subtract = createAdder(-1, "subtract"); + function isString2(input) { + return typeof input === "string" || input instanceof String; + } + function isMomentInput(input) { + return isMoment(input) || isDate2(input) || isString2(input) || isNumber2(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === void 0; + } + function isMomentInputObject(input) { + var objectTest = isObject2(input) && !isObjectEmpty(input), propertyTest = false, properties = [ + "years", + "year", + "y", + "months", + "month", + "M", + "days", + "day", + "d", + "dates", + "date", + "D", + "hours", + "hour", + "h", + "minutes", + "minute", + "m", + "seconds", + "second", + "s", + "milliseconds", + "millisecond", + "ms" + ], i, property, propertyLen = properties.length; + for (i = 0; i < propertyLen; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } + return objectTest && propertyTest; } - function relativeTime$1(posNegDuration, withoutSuffix, thresholds2, locale2) { - var duration = createDuration(posNegDuration).abs(), seconds2 = round(duration.as("s")), minutes2 = round(duration.as("m")), hours2 = round(duration.as("h")), days2 = round(duration.as("d")), months2 = round(duration.as("M")), weeks2 = round(duration.as("w")), years2 = round(duration.as("y")), a = seconds2 <= thresholds2.ss && ["s", seconds2] || seconds2 < thresholds2.s && ["ss", seconds2] || minutes2 <= 1 && ["m"] || minutes2 < thresholds2.m && ["mm", minutes2] || hours2 <= 1 && ["h"] || hours2 < thresholds2.h && ["hh", hours2] || days2 <= 1 && ["d"] || days2 < thresholds2.d && ["dd", days2]; - if (thresholds2.w != null) { - a = a || weeks2 <= 1 && ["w"] || weeks2 < thresholds2.w && ["ww", weeks2]; + function isNumberOrStringArray(input) { + var arrayTest = isArray2(input), dataTypeTest = false; + if (arrayTest) { + dataTypeTest = input.filter(function(item) { + return !isNumber2(item) && isString2(input); + }).length === 0; } - a = a || months2 <= 1 && ["M"] || months2 < thresholds2.M && ["MM", months2] || years2 <= 1 && ["y"] || ["yy", years2]; - a[2] = withoutSuffix; - a[3] = +posNegDuration > 0; - a[4] = locale2; - return substituteTimeAgo.apply(null, a); + return arrayTest && dataTypeTest; } - function getSetRelativeTimeRounding(roundingFunction) { - if (roundingFunction === void 0) { - return round; + function isCalendarSpec(input) { + var objectTest = isObject2(input) && !isObjectEmpty(input), propertyTest = false, properties = [ + "sameDay", + "nextDay", + "lastDay", + "nextWeek", + "lastWeek", + "sameElse" + ], i, property; + for (i = 0; i < properties.length; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); } - if (typeof roundingFunction === "function") { - round = roundingFunction; - return true; + return objectTest && propertyTest; + } + function getCalendarFormat(myMoment, now2) { + var diff2 = myMoment.diff(now2, "days", true); + return diff2 < -6 ? "sameElse" : diff2 < -1 ? "lastWeek" : diff2 < 0 ? "lastDay" : diff2 < 1 ? "sameDay" : diff2 < 2 ? "nextDay" : diff2 < 7 ? "nextWeek" : "sameElse"; + } + function calendar$1(time, formats) { + if (arguments.length === 1) { + if (!arguments[0]) { + time = void 0; + formats = void 0; + } else if (isMomentInput(arguments[0])) { + time = arguments[0]; + formats = void 0; + } else if (isCalendarSpec(arguments[0])) { + formats = arguments[0]; + time = void 0; + } } - return false; + var now2 = time || createLocal(), sod = cloneWithOffset(now2, this).startOf("day"), format2 = hooks.calendarFormat(this, sod) || "sameElse", output = formats && (isFunction2(formats[format2]) ? formats[format2].call(this, now2) : formats[format2]); + return this.format( + output || this.localeData().calendar(format2, this, createLocal(now2)) + ); } - function getSetRelativeTimeThreshold(threshold, limit) { - if (thresholds[threshold] === void 0) { + function clone() { + return new Moment(this); + } + function isAfter(input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { return false; } - if (limit === void 0) { - return thresholds[threshold]; - } - thresholds[threshold] = limit; - if (threshold === "s") { - thresholds.ss = limit - 1; + units = normalizeUnits(units) || "millisecond"; + if (units === "millisecond") { + return this.valueOf() > localInput.valueOf(); + } else { + return localInput.valueOf() < this.clone().startOf(units).valueOf(); } - return true; } - function humanize(argWithSuffix, argThresholds) { - if (!this.isValid()) { - return this.localeData().invalidDate(); + function isBefore(input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; } - var withSuffix = false, th = thresholds, locale2, output; - if (typeof argWithSuffix === "object") { - argThresholds = argWithSuffix; - argWithSuffix = false; + units = normalizeUnits(units) || "millisecond"; + if (units === "millisecond") { + return this.valueOf() < localInput.valueOf(); + } else { + return this.clone().endOf(units).valueOf() < localInput.valueOf(); } - if (typeof argWithSuffix === "boolean") { - withSuffix = argWithSuffix; + } + function isBetween(from6, to3, units, inclusivity) { + var localFrom = isMoment(from6) ? from6 : createLocal(from6), localTo = isMoment(to3) ? to3 : createLocal(to3); + if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { + return false; } - if (typeof argThresholds === "object") { - th = Object.assign({}, thresholds, argThresholds); - if (argThresholds.s != null && argThresholds.ss == null) { - th.ss = argThresholds.s - 1; - } + inclusivity = inclusivity || "()"; + return (inclusivity[0] === "(" ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ")" ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)); + } + function isSame(input, units) { + var localInput = isMoment(input) ? input : createLocal(input), inputMs; + if (!(this.isValid() && localInput.isValid())) { + return false; } - locale2 = this.localeData(); - output = relativeTime$1(this, !withSuffix, th, locale2); - if (withSuffix) { - output = locale2.pastFuture(+this, output); + units = normalizeUnits(units) || "millisecond"; + if (units === "millisecond") { + return this.valueOf() === localInput.valueOf(); + } else { + inputMs = localInput.valueOf(); + return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); } - return locale2.postformat(output); } - var abs$1 = Math.abs; - function sign2(x2) { - return (x2 > 0) - (x2 < 0) || +x2; + function isSameOrAfter(input, units) { + return this.isSame(input, units) || this.isAfter(input, units); } - function toISOString$1() { + function isSameOrBefore(input, units) { + return this.isSame(input, units) || this.isBefore(input, units); + } + function diff(input, units, asFloat) { + var that, zoneDelta, output; if (!this.isValid()) { - return this.localeData().invalidDate(); + return NaN; } - var seconds2 = abs$1(this._milliseconds) / 1e3, days2 = abs$1(this._days), months2 = abs$1(this._months), minutes2, hours2, years2, s, total = this.asSeconds(), totalSign, ymSign, daysSign, hmsSign; - if (!total) { - return "P0D"; + that = cloneWithOffset(input, this); + if (!that.isValid()) { + return NaN; } - minutes2 = absFloor(seconds2 / 60); - hours2 = absFloor(minutes2 / 60); - seconds2 %= 60; - minutes2 %= 60; - years2 = absFloor(months2 / 12); - months2 %= 12; - s = seconds2 ? seconds2.toFixed(3).replace(/\.?0+$/, "") : ""; - totalSign = total < 0 ? "-" : ""; - ymSign = sign2(this._months) !== sign2(total) ? "-" : ""; - daysSign = sign2(this._days) !== sign2(total) ? "-" : ""; - hmsSign = sign2(this._milliseconds) !== sign2(total) ? "-" : ""; - return totalSign + "P" + (years2 ? ymSign + years2 + "Y" : "") + (months2 ? ymSign + months2 + "M" : "") + (days2 ? daysSign + days2 + "D" : "") + (hours2 || minutes2 || seconds2 ? "T" : "") + (hours2 ? hmsSign + hours2 + "H" : "") + (minutes2 ? hmsSign + minutes2 + "M" : "") + (seconds2 ? hmsSign + s + "S" : ""); - } - var proto$2 = Duration.prototype; - proto$2.isValid = isValid$1; - proto$2.abs = abs; - proto$2.add = add$1; - proto$2.subtract = subtract$1; - proto$2.as = as2; - proto$2.asMilliseconds = asMilliseconds; - proto$2.asSeconds = asSeconds; - proto$2.asMinutes = asMinutes; - proto$2.asHours = asHours; - proto$2.asDays = asDays; - proto$2.asWeeks = asWeeks; - proto$2.asMonths = asMonths; - proto$2.asQuarters = asQuarters; - proto$2.asYears = asYears; - proto$2.valueOf = valueOf$1; - proto$2._bubble = bubble; - proto$2.clone = clone$1; - proto$2.get = get$2; - proto$2.milliseconds = milliseconds; - proto$2.seconds = seconds; - proto$2.minutes = minutes; - proto$2.hours = hours; - proto$2.days = days; - proto$2.weeks = weeks; - proto$2.months = months; - proto$2.years = years; - proto$2.humanize = humanize; - proto$2.toISOString = toISOString$1; - proto$2.toString = toISOString$1; - proto$2.toJSON = toISOString$1; - proto$2.locale = locale; - proto$2.localeData = localeData; - proto$2.toIsoString = deprecate( - "toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)", - toISOString$1 - ); - proto$2.lang = lang; - addFormatToken("X", 0, 0, "unix"); - addFormatToken("x", 0, 0, "valueOf"); - addRegexToken("x", matchSigned); - addRegexToken("X", matchTimestamp); - addParseToken("X", function(input, array, config3) { - config3._d = new Date(parseFloat(input) * 1e3); - }); - addParseToken("x", function(input, array, config3) { - config3._d = new Date(toInt(input)); - }); - hooks.version = "2.30.1"; - setHookCallback(createLocal); - hooks.fn = proto; - hooks.min = min; - hooks.max = max; - hooks.now = now; - hooks.utc = createUTC; - hooks.unix = createUnix; - hooks.months = listMonths; - hooks.isDate = isDate2; - hooks.locale = getSetGlobalLocale; - hooks.invalid = createInvalid; - hooks.duration = createDuration; - hooks.isMoment = isMoment; - hooks.weekdays = listWeekdays; - hooks.parseZone = createInZone; - hooks.localeData = getLocale; - hooks.isDuration = isDuration; - hooks.monthsShort = listMonthsShort; - hooks.weekdaysMin = listWeekdaysMin; - hooks.defineLocale = defineLocale; - hooks.updateLocale = updateLocale; - hooks.locales = listLocales; - hooks.weekdaysShort = listWeekdaysShort; - hooks.normalizeUnits = normalizeUnits; - hooks.relativeTimeRounding = getSetRelativeTimeRounding; - hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; - hooks.calendarFormat = getCalendarFormat; - hooks.prototype = proto; - hooks.HTML5_FMT = { - DATETIME_LOCAL: "YYYY-MM-DDTHH:mm", - // - DATETIME_LOCAL_SECONDS: "YYYY-MM-DDTHH:mm:ss", - // - DATETIME_LOCAL_MS: "YYYY-MM-DDTHH:mm:ss.SSS", - // - DATE: "YYYY-MM-DD", - // - TIME: "HH:mm", - // - TIME_SECONDS: "HH:mm:ss", - // - TIME_MS: "HH:mm:ss.SSS", - // - WEEK: "GGGG-[W]WW", - // - MONTH: "YYYY-MM" - // - }; - return hooks; - }); - } -}); - -// node_modules/file-stream-rotator/FileStreamRotator.js -var require_FileStreamRotator = __commonJS({ - "node_modules/file-stream-rotator/FileStreamRotator.js"(exports2, module2) { - "use strict"; - var fs2 = __require("fs"); - var path = __require("path"); - var moment = require_moment(); - var crypto4 = __require("crypto"); - var EventEmitter3 = __require("events"); - var FileStreamRotator = {}; - module2.exports = FileStreamRotator; - var staticFrequency = ["daily", "test", "m", "h", "custom"]; - var DATE_FORMAT = "YYYYMMDDHHmm"; - var _checkNumAndType = function(type, num2) { - if (typeof num2 == "number") { - switch (type) { - case "m": - if (num2 < 0 || num2 > 60) { - return false; - } + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + units = normalizeUnits(units); + switch (units) { + case "year": + output = monthDiff(this, that) / 12; break; - case "h": - if (num2 < 0 || num2 > 24) { - return false; - } + case "month": + output = monthDiff(this, that); break; - } - return { type, digit: num2 }; - } - }; - var _checkDailyAndTest = function(freqType) { - switch (freqType) { - case "custom": - case "daily": - return { type: freqType, digit: void 0 }; - break; - case "test": - return { type: freqType, digit: 0 }; - } - return false; - }; - FileStreamRotator.getFrequency = function(frequency) { - var _f = frequency.toLowerCase().match(/^(\d+)([mh])$/); - if (_f) { - return _checkNumAndType(_f[2], parseInt(_f[1])); - } - var dailyOrTest = _checkDailyAndTest(frequency); - if (dailyOrTest) { - return dailyOrTest; - } - return false; - }; - FileStreamRotator.parseFileSize = function(size5) { - if (size5 && typeof size5 == "string") { - var _s2 = size5.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/); - if (_s2) { - switch (_s2[2]) { - case "k": - return _s2[1] * 1024; - case "m": - return _s2[1] * 1024 * 1024; - case "g": - return _s2[1] * 1024 * 1024 * 1024; - } - } - } - return null; - }; - FileStreamRotator.getDate = function(format, date_format, utc) { - date_format = date_format || DATE_FORMAT; - let currentMoment = utc ? moment.utc() : moment().local(); - if (format && staticFrequency.indexOf(format.type) !== -1) { - switch (format.type) { - case "m": - var minute = Math.floor(currentMoment.minutes() / format.digit) * format.digit; - return currentMoment.minutes(minute).format(date_format); + case "quarter": + output = monthDiff(this, that) / 3; break; - case "h": - var hour = Math.floor(currentMoment.hour() / format.digit) * format.digit; - return currentMoment.hour(hour).format(date_format); + case "second": + output = (this - that) / 1e3; break; - case "daily": - case "custom": - case "test": - return currentMoment.format(date_format); + // 1000 + case "minute": + output = (this - that) / 6e4; + break; + // 1000 * 60 + case "hour": + output = (this - that) / 36e5; + break; + // 1000 * 60 * 60 + case "day": + output = (this - that - zoneDelta) / 864e5; + break; + // 1000 * 60 * 60 * 24, negate dst + case "week": + output = (this - that - zoneDelta) / 6048e5; + break; + // 1000 * 60 * 60 * 24 * 7, negate dst + default: + output = this - that; } + return asFloat ? output : absFloor(output); } - return currentMoment.format(date_format); - }; - FileStreamRotator.setAuditLog = function(max_logs, audit_file, log_file) { - var _rtn = null; - if (max_logs) { - var use_days = max_logs.toString().substr(-1); - var _num = max_logs.toString().match(/^(\d+)/); - if (Number(_num[1]) > 0) { - var baseLog = path.dirname(log_file.replace(/%DATE%.+/, "_filename")); - try { - if (audit_file) { - var full_path = path.resolve(audit_file); - _rtn = JSON.parse(fs2.readFileSync(full_path, { encoding: "utf-8" })); - } else { - var full_path = path.resolve(baseLog + "/.audit.json"); - _rtn = JSON.parse(fs2.readFileSync(full_path, { encoding: "utf-8" })); - } - } catch (e) { - if (e.code !== "ENOENT") { - return null; - } - _rtn = { - keep: { - days: false, - amount: Number(_num[1]) - }, - auditLog: audit_file || baseLog + "/.audit.json", - files: [] - }; - } - _rtn.keep = { - days: use_days === "d", - amount: Number(_num[1]) - }; + function monthDiff(a, b2) { + if (a.date() < b2.date()) { + return -monthDiff(b2, a); } - } - return _rtn; - }; - FileStreamRotator.writeAuditLog = function(audit, verbose) { - try { - mkDirForFile(audit.auditLog); - fs2.writeFileSync(audit.auditLog, JSON.stringify(audit, null, 4)); - } catch (e) { - if (verbose) { - console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] Failed to store log audit at:", audit.auditLog, "Error:", e); + var wholeMonthDiff = (b2.year() - a.year()) * 12 + (b2.month() - a.month()), anchor = a.clone().add(wholeMonthDiff, "months"), anchor2, adjust; + if (b2 - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, "months"); + adjust = (b2 - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, "months"); + adjust = (b2 - anchor) / (anchor2 - anchor); } + return -(wholeMonthDiff + adjust) || 0; } - }; - function removeFile(file, verbose) { - if (file.hash === crypto4.createHash(file.hashType).update(file.name + "LOG_FILE" + file.date).digest("hex")) { - try { - if (fs2.existsSync(file.name)) { - fs2.unlinkSync(file.name); - } - } catch (e) { - if (verbose) { - console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] Could not remove old log file: ", file.name); + hooks.defaultFormat = "YYYY-MM-DDTHH:mm:ssZ"; + hooks.defaultFormatUtc = "YYYY-MM-DDTHH:mm:ss[Z]"; + function toString3() { + return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); + } + function toISOString(keepOffset) { + if (!this.isValid()) { + return null; + } + var utc = keepOffset !== true, m2 = utc ? this.clone().utc() : this; + if (m2.year() < 0 || m2.year() > 9999) { + return formatMoment( + m2, + utc ? "YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYYYY-MM-DD[T]HH:mm:ss.SSSZ" + ); + } + if (isFunction2(Date.prototype.toISOString)) { + if (utc) { + return this.toDate().toISOString(); + } else { + return new Date(this.valueOf() + this.utcOffset() * 60 * 1e3).toISOString().replace("Z", formatMoment(m2, "Z")); } } + return formatMoment( + m2, + utc ? "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYY-MM-DD[T]HH:mm:ss.SSSZ" + ); } - } - function createCurrentSymLink(logfile, name, verbose) { - let symLinkName = name || "current.log"; - let logPath = path.dirname(logfile); - let logfileName = path.basename(logfile); - let current = logPath + "/" + symLinkName; - try { - let stats = fs2.lstatSync(current); - if (stats.isSymbolicLink()) { - fs2.unlinkSync(current); - fs2.symlinkSync(logfileName, current); + function inspect() { + if (!this.isValid()) { + return "moment.invalid(/* " + this._i + " */)"; } - } catch (err) { - if (err && err.code == "ENOENT") { - try { - fs2.symlinkSync(logfileName, current); - } catch (e) { - if (verbose) { - console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] Could not create symlink file: ", current, " -> ", logfileName); - } - } + var func = "moment", zone = "", prefix, year, datetime, suffix; + if (!this.isLocal()) { + func = this.utcOffset() === 0 ? "moment.utc" : "moment.parseZone"; + zone = "Z"; } + prefix = "[" + func + '("]'; + year = 0 <= this.year() && this.year() <= 9999 ? "YYYY" : "YYYYYY"; + datetime = "-MM-DD[T]HH:mm:ss.SSS"; + suffix = zone + '[")]'; + return this.format(prefix + year + datetime + suffix); } - } - function createLogWatcher(logfile, verbose, cb) { - if (!logfile) return null; - try { - let stats = fs2.lstatSync(logfile); - return fs2.watch(logfile, function(event, filename) { - if (event == "rename") { - try { - let stats2 = fs2.lstatSync(logfile); - } catch (err) { - cb(err, logfile); - } - } - }); - } catch (err) { - if (verbose) { - console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Could not add watcher for " + logfile); + function format(inputString) { + if (!inputString) { + inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; } + var output = formatMoment(this, inputString); + return this.localeData().postformat(output); } - } - FileStreamRotator.addLogToAudit = function(logfile, audit, stream4, verbose) { - if (audit && audit.files) { - var index2 = audit.files.findIndex(function(file) { - return file.name === logfile; - }); - if (index2 !== -1) { - return audit; - } - var time = Date.now(); - audit.files.push({ - date: time, - name: logfile, - hash: crypto4.createHash(audit.hashType).update(logfile + "LOG_FILE" + time).digest("hex") - }); - if (audit.keep.days) { - var oldestDate = moment().subtract(audit.keep.amount, "days").valueOf(); - var recentFiles = audit.files.filter(function(file) { - if (file.date > oldestDate) { - return true; - } - file.hashType = audit.hashType; - removeFile(file, verbose); - stream4.emit("logRemoved", file); - return false; - }); - audit.files = recentFiles; + function from5(time, withoutSuffix) { + if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) { + return createDuration({ to: this, from: time }).locale(this.locale()).humanize(!withoutSuffix); } else { - var filesToKeep = audit.files.splice(-audit.keep.amount); - if (audit.files.length > 0) { - audit.files.filter(function(file) { - file.hashType = audit.hashType; - removeFile(file, verbose); - stream4.emit("logRemoved", file); - return false; - }); - } - audit.files = filesToKeep; + return this.localeData().invalidDate(); } - FileStreamRotator.writeAuditLog(audit, verbose); - } - return audit; - }; - FileStreamRotator.getStream = function(options) { - var frequencyMetaData = null; - var curDate = null; - var self2 = this; - if (!options.filename) { - console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] No filename supplied. Defaulting to STDOUT"); - return process.stdout; } - if (options.frequency) { - frequencyMetaData = self2.getFrequency(options.frequency); + function fromNow(withoutSuffix) { + return this.from(createLocal(), withoutSuffix); } - let auditLog = self2.setAuditLog(options.max_logs, options.audit_file, options.filename); - if (auditLog != null) { - auditLog.hashType = options.audit_hash_type !== void 0 ? options.audit_hash_type : "md5"; + function to2(time, withoutSuffix) { + if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) { + return createDuration({ from: this, to: time }).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } } - self2.verbose = options.verbose !== void 0 ? options.verbose : true; - var fileSize = null; - var fileCount = 0; - var curSize = 0; - if (options.size) { - fileSize = FileStreamRotator.parseFileSize(options.size); + function toNow(withoutSuffix) { + return this.to(createLocal(), withoutSuffix); } - var dateFormat = options.date_format || DATE_FORMAT; - if (frequencyMetaData && frequencyMetaData.type == "daily") { - if (!options.date_format) { - dateFormat = "YYYY-MM-DD"; + function locale(key) { + var newLocaleData; + if (key === void 0) { + return this._locale._abbr; + } else { + newLocaleData = getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; } - if (moment().format(dateFormat) != moment().endOf("day").format(dateFormat) || moment().format(dateFormat) == moment().add(1, "day").format(dateFormat)) { - if (self2.verbose) { - console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Changing type to custom as date format changes more often than once a day or not every day"); + } + var lang = deprecate( + "moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.", + function(key) { + if (key === void 0) { + return this.localeData(); + } else { + return this.locale(key); } - frequencyMetaData.type = "custom"; } + ); + function localeData() { + return this._locale; } - if (frequencyMetaData) { - curDate = options.frequency ? self2.getDate(frequencyMetaData, dateFormat, options.utc) : ""; + var MS_PER_SECOND = 1e3, MS_PER_MINUTE = 60 * MS_PER_SECOND, MS_PER_HOUR = 60 * MS_PER_MINUTE, MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; + function mod$1(dividend, divisor) { + return (dividend % divisor + divisor) % divisor; } - options.create_symlink = options.create_symlink || false; - options.extension = options.extension || ""; - var filename = options.filename; - var oldFile = null; - var logfile = filename + (curDate ? "." + curDate : ""); - if (filename.match(/%DATE%/)) { - logfile = filename.replace(/%DATE%/g, curDate ? curDate : self2.getDate(null, dateFormat, options.utc)); + function localStartOfDate(y2, m2, d) { + if (y2 < 100 && y2 >= 0) { + return new Date(y2 + 400, m2, d) - MS_PER_400_YEARS; + } else { + return new Date(y2, m2, d).valueOf(); + } } - if (fileSize) { - var lastLogFile = null; - var t_log = logfile; - var f = null; - if (auditLog && auditLog.files && auditLog.files instanceof Array && auditLog.files.length > 0) { - var lastEntry = auditLog.files[auditLog.files.length - 1].name; - if (lastEntry.match(t_log)) { - var lastCount = lastEntry.match(t_log + "\\.(\\d+)"); - if (lastCount) { - t_log = lastEntry; - fileCount = lastCount[1]; - } - } + function utcStartOfDate(y2, m2, d) { + if (y2 < 100 && y2 >= 0) { + return Date.UTC(y2 + 400, m2, d) - MS_PER_400_YEARS; + } else { + return Date.UTC(y2, m2, d); } - if (fileCount == 0 && t_log == logfile) { - t_log += options.extension; + } + function startOf(units) { + var time, startOfDate; + units = normalizeUnits(units); + if (units === void 0 || units === "millisecond" || !this.isValid()) { + return this; } - while (f = fs2.existsSync(t_log)) { - lastLogFile = t_log; - fileCount++; - t_log = logfile + "." + fileCount + options.extension; + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + switch (units) { + case "year": + time = startOfDate(this.year(), 0, 1); + break; + case "quarter": + time = startOfDate( + this.year(), + this.month() - this.month() % 3, + 1 + ); + break; + case "month": + time = startOfDate(this.year(), this.month(), 1); + break; + case "week": + time = startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + ); + break; + case "isoWeek": + time = startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + ); + break; + case "day": + case "date": + time = startOfDate(this.year(), this.month(), this.date()); + break; + case "hour": + time = this._d.valueOf(); + time -= mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR + ); + break; + case "minute": + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_MINUTE); + break; + case "second": + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_SECOND); + break; } - if (lastLogFile) { - var lastLogFileStats = fs2.statSync(lastLogFile); - if (lastLogFileStats.size < fileSize) { - t_log = lastLogFile; - fileCount--; - curSize = lastLogFileStats.size; - } + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + function endOf(units) { + var time, startOfDate; + units = normalizeUnits(units); + if (units === void 0 || units === "millisecond" || !this.isValid()) { + return this; } - logfile = t_log; - } else { - logfile += options.extension; + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + switch (units) { + case "year": + time = startOfDate(this.year() + 1, 0, 1) - 1; + break; + case "quarter": + time = startOfDate( + this.year(), + this.month() - this.month() % 3 + 3, + 1 + ) - 1; + break; + case "month": + time = startOfDate(this.year(), this.month() + 1, 1) - 1; + break; + case "week": + time = startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + 7 + ) - 1; + break; + case "isoWeek": + time = startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + 7 + ) - 1; + break; + case "day": + case "date": + time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; + break; + case "hour": + time = this._d.valueOf(); + time += MS_PER_HOUR - mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR + ) - 1; + break; + case "minute": + time = this._d.valueOf(); + time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; + break; + case "second": + time = this._d.valueOf(); + time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; + break; + } + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; } - if (self2.verbose) { - console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Logging to: ", logfile); + function valueOf() { + return this._d.valueOf() - (this._offset || 0) * 6e4; } - mkDirForFile(logfile); - var file_options = options.file_options || { flags: "a" }; - var rotateStream = fs2.createWriteStream(logfile, file_options); - if (curDate && frequencyMetaData && staticFrequency.indexOf(frequencyMetaData.type) > -1 || fileSize > 0) { - if (self2.verbose) { - console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Rotating file: ", frequencyMetaData ? frequencyMetaData.type : "", fileSize ? "size: " + fileSize : ""); - } - var stream4 = new EventEmitter3(); - stream4.auditLog = auditLog; - stream4.end = function() { - rotateStream.end.apply(rotateStream, arguments); + function unix() { + return Math.floor(this.valueOf() / 1e3); + } + function toDate() { + return new Date(this.valueOf()); + } + function toArray2() { + var m2 = this; + return [ + m2.year(), + m2.month(), + m2.date(), + m2.hour(), + m2.minute(), + m2.second(), + m2.millisecond() + ]; + } + function toObject() { + var m2 = this; + return { + years: m2.year(), + months: m2.month(), + date: m2.date(), + hours: m2.hours(), + minutes: m2.minutes(), + seconds: m2.seconds(), + milliseconds: m2.milliseconds() }; - BubbleEvents(rotateStream, stream4); - stream4.on("close", function() { - if (logWatcher) { - logWatcher.close(); - } - }); - stream4.on("new", function(newLog) { - stream4.auditLog = self2.addLogToAudit(newLog, stream4.auditLog, stream4, self2.verbose); - if (options.create_symlink) { - createCurrentSymLink(newLog, options.symlink_name, self2.verbose); - } - if (options.watch_log) { - stream4.emit("addWatcher", newLog); - } - }); - var logWatcher; - stream4.on("addWatcher", function(newLog) { - if (logWatcher) { - logWatcher.close(); - } - if (!options.watch_log) { - return; - } - logWatcher = createLogWatcher(newLog, self2.verbose, function(err, newLog2) { - stream4.emit("createLog", newLog2); - }); - }); - stream4.on("createLog", function(file) { - try { - let stats = fs2.lstatSync(file); - } catch (err) { - if (rotateStream && rotateStream.end == "function") { - rotateStream.end(); - } - rotateStream = fs2.createWriteStream(file, file_options); - stream4.emit("new", file); - BubbleEvents(rotateStream, stream4); - } - }); - stream4.write = function(str, encoding) { - var newDate = frequencyMetaData ? this.getDate(frequencyMetaData, dateFormat, options.utc) : curDate; - if (newDate != curDate || fileSize && curSize > fileSize) { - var newLogfile = filename + (curDate && frequencyMetaData ? "." + newDate : ""); - if (filename.match(/%DATE%/) && curDate) { - newLogfile = filename.replace(/%DATE%/g, newDate); - } - if (fileSize && curSize > fileSize) { - fileCount++; - newLogfile += "." + fileCount + options.extension; - } else { - fileCount = 0; - newLogfile += options.extension; - } - curSize = 0; - if (self2.verbose) { - console.log(/* @__PURE__ */ new Date(), __require("util").format("[FileStreamRotator] Changing logs from %s to %s", logfile, newLogfile)); - } - curDate = newDate; - oldFile = logfile; - logfile = newLogfile; - if (options.end_stream === true) { - rotateStream.end(); - } else { - rotateStream.destroy(); - } - mkDirForFile(logfile); - rotateStream = fs2.createWriteStream(newLogfile, file_options); - stream4.emit("new", newLogfile); - stream4.emit("rotate", oldFile, newLogfile); - BubbleEvents(rotateStream, stream4); - } - rotateStream.write(str, encoding); - curSize += Buffer.byteLength(str, encoding); - }.bind(this); - process.nextTick(function() { - stream4.emit("new", logfile); - }); - stream4.emit("new", logfile); - return stream4; - } else { - if (self2.verbose) { - console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] File won't be rotated: ", options.frequency, options.size); - } - process.nextTick(function() { - rotateStream.emit("new", logfile); - }); - return rotateStream; } - }; - var mkDirForFile = function(pathWithFile) { - var _path = path.dirname(pathWithFile); - _path.split(path.sep).reduce( - function(fullPath, folder) { - fullPath += folder + path.sep; - if (!fs2.existsSync(fullPath)) { - try { - fs2.mkdirSync(fullPath); - } catch (e) { - if (e.code !== "EEXIST") { - throw e; - } - } - } - return fullPath; - }, - "" - ); - }; - var BubbleEvents = function BubbleEvents2(emitter, proxy) { - emitter.on("close", function() { - proxy.emit("close"); - }); - emitter.on("finish", function() { - proxy.emit("finish"); - }); - emitter.on("error", function(err) { - proxy.emit("error", err); - }); - emitter.on("open", function(fd2) { - proxy.emit("open", fd2); - }); - }; - } -}); - -// node_modules/winston-daily-rotate-file/daily-rotate-file.js -var require_daily_rotate_file = __commonJS({ - "node_modules/winston-daily-rotate-file/daily-rotate-file.js"(exports2, module2) { - var fs2 = __require("fs"); - var os2 = __require("os"); - var path = __require("path"); - var util3 = __require("util"); - var zlib2 = __require("zlib"); - var hash2 = require_object_hash(); - var MESSAGE = require_triple_beam().MESSAGE; - var PassThrough = __require("stream").PassThrough; - var Transport2 = require_winston_transport(); - var loggerDefaults = { - json: false, - colorize: false, - eol: os2.EOL, - logstash: null, - prettyPrint: false, - label: null, - stringify: false, - depth: null, - showLevel: true, - timestamp: () => { - return (/* @__PURE__ */ new Date()).toISOString(); + function toJSON2() { + return this.isValid() ? this.toISOString() : null; } - }; - var DailyRotateFile2 = function(options) { - options = options || {}; - Transport2.call(this, options); - function throwIf(target) { - Array.prototype.slice.call(arguments, 1).forEach((name) => { - if (options[name]) { - throw new Error("Cannot set " + name + " and " + target + " together"); + function isValid$2() { + return isValid(this); + } + function parsingFlags() { + return extend2({}, getParsingFlags(this)); + } + function invalidAt() { + return getParsingFlags(this).overflow; + } + function creationData() { + return { + input: this._i, + format: this._f, + locale: this._locale, + isUTC: this._isUTC, + strict: this._strict + }; + } + addFormatToken("N", 0, 0, "eraAbbr"); + addFormatToken("NN", 0, 0, "eraAbbr"); + addFormatToken("NNN", 0, 0, "eraAbbr"); + addFormatToken("NNNN", 0, 0, "eraName"); + addFormatToken("NNNNN", 0, 0, "eraNarrow"); + addFormatToken("y", ["y", 1], "yo", "eraYear"); + addFormatToken("y", ["yy", 2], 0, "eraYear"); + addFormatToken("y", ["yyy", 3], 0, "eraYear"); + addFormatToken("y", ["yyyy", 4], 0, "eraYear"); + addRegexToken("N", matchEraAbbr); + addRegexToken("NN", matchEraAbbr); + addRegexToken("NNN", matchEraAbbr); + addRegexToken("NNNN", matchEraName); + addRegexToken("NNNNN", matchEraNarrow); + addParseToken( + ["N", "NN", "NNN", "NNNN", "NNNNN"], + function(input, array, config3, token2) { + var era = config3._locale.erasParse(input, token2, config3._strict); + if (era) { + getParsingFlags(config3).era = era; + } else { + getParsingFlags(config3).invalidEra = input; } - }); + } + ); + addRegexToken("y", matchUnsigned); + addRegexToken("yy", matchUnsigned); + addRegexToken("yyy", matchUnsigned); + addRegexToken("yyyy", matchUnsigned); + addRegexToken("yo", matchEraYearOrdinal); + addParseToken(["y", "yy", "yyy", "yyyy"], YEAR); + addParseToken(["yo"], function(input, array, config3, token2) { + var match; + if (config3._locale._eraYearOrdinalRegex) { + match = input.match(config3._locale._eraYearOrdinalRegex); + } + if (config3._locale.eraYearOrdinalParse) { + array[YEAR] = config3._locale.eraYearOrdinalParse(input, match); + } else { + array[YEAR] = parseInt(input, 10); + } + }); + function localeEras(m2, format2) { + var i, l, date, eras = this._eras || getLocale("en")._eras; + for (i = 0, l = eras.length; i < l; ++i) { + switch (typeof eras[i].since) { + case "string": + date = hooks(eras[i].since).startOf("day"); + eras[i].since = date.valueOf(); + break; + } + switch (typeof eras[i].until) { + case "undefined": + eras[i].until = Infinity; + break; + case "string": + date = hooks(eras[i].until).startOf("day").valueOf(); + eras[i].until = date.valueOf(); + break; + } + } + return eras; } - function getMaxSize(size5) { - if (size5 && typeof size5 === "string") { - if (size5.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/)) { - return size5; + function localeErasParse(eraName, format2, strict) { + var i, l, eras = this.eras(), name, abbr, narrow; + eraName = eraName.toUpperCase(); + for (i = 0, l = eras.length; i < l; ++i) { + name = eras[i].name.toUpperCase(); + abbr = eras[i].abbr.toUpperCase(); + narrow = eras[i].narrow.toUpperCase(); + if (strict) { + switch (format2) { + case "N": + case "NN": + case "NNN": + if (abbr === eraName) { + return eras[i]; + } + break; + case "NNNN": + if (name === eraName) { + return eras[i]; + } + break; + case "NNNNN": + if (narrow === eraName) { + return eras[i]; + } + break; + } + } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { + return eras[i]; } - } else if (size5 && Number.isInteger(size5)) { - const sizeK = Math.round(size5 / 1024); - return sizeK === 0 ? "1k" : sizeK + "k"; } - return null; } - function isValidFileName(filename) { - return !/["<>|:*?\\/\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test( - filename - ); + function localeErasConvertYear(era, year) { + var dir = era.since <= era.until ? 1 : -1; + if (year === void 0) { + return hooks(era.since).year(); + } else { + return hooks(era.since).year() + (year - era.offset) * dir; + } } - function isValidDirName(dirname2) { - return !/["<>|\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test( - dirname2 - ); + function getEraName() { + var i, l, val, eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + val = this.clone().startOf("day").valueOf(); + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].name; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].name; + } + } + return ""; } - this.options = Object.assign({}, loggerDefaults, options); - if (options.stream) { - throwIf("stream", "filename", "maxsize"); - this.logStream = new PassThrough(); - this.logStream.pipe(options.stream); - } else { - this.filename = options.filename ? path.basename(options.filename) : "winston.log"; - this.dirname = options.dirname || path.dirname(options.filename); - if (!isValidFileName(this.filename) || !isValidDirName(this.dirname)) { - throw new Error("Your path or filename contain an invalid character."); + function getEraNarrow() { + var i, l, val, eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + val = this.clone().startOf("day").valueOf(); + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].narrow; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].narrow; + } } - this.logStream = require_FileStreamRotator().getStream({ - filename: path.join(this.dirname, this.filename), - frequency: options.frequency ? options.frequency : "custom", - date_format: options.datePattern ? options.datePattern : "YYYY-MM-DD", - verbose: false, - size: getMaxSize(options.maxSize), - max_logs: options.maxFiles, - end_stream: true, - audit_file: options.auditFile ? options.auditFile : path.join(this.dirname, "." + hash2(options) + "-audit.json"), - file_options: options.options ? options.options : { flags: "a" }, - utc: options.utc ? options.utc : false, - extension: options.extension ? options.extension : "", - create_symlink: options.createSymlink ? options.createSymlink : false, - symlink_name: options.symlinkName ? options.symlinkName : "current.log", - watch_log: options.watchLog ? options.watchLog : false, - audit_hash_type: options.auditHashType ? options.auditHashType : "sha256" - }); - this.logStream.on("new", (newFile) => { - this.emit("new", newFile); - }); - this.logStream.on("rotate", (oldFile, newFile) => { - this.emit("rotate", oldFile, newFile); - }); - this.logStream.on("logRemoved", (params) => { - if (options.zippedArchive) { - const gzName = params.name + ".gz"; - try { - fs2.unlinkSync(gzName); - } catch (err) { - if (err.code !== "ENOENT") { - err.message = `Error occurred while removing ${gzName}: ${err.message}`; - this.emit("error", err); - return; - } - } - this.emit("logRemoved", gzName); - return; + return ""; + } + function getEraAbbr() { + var i, l, val, eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + val = this.clone().startOf("day").valueOf(); + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].abbr; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].abbr; } - this.emit("logRemoved", params.name); - }); - if (options.zippedArchive) { - this.logStream.on("rotate", (oldFile) => { - try { - if (!fs2.existsSync(oldFile)) { - return; - } - } catch (err) { - err.message = `Error occurred while checking existence of ${oldFile}: ${err.message}`; - this.emit("error", err); - return; - } - try { - if (fs2.existsSync(`${oldFile}.gz`)) { - return; - } - } catch (err) { - err.message = `Error occurred while checking existence of ${oldFile}.gz: ${err.message}`; - this.emit("error", err); - return; - } - const gzip = zlib2.createGzip(); - const inp = fs2.createReadStream(oldFile); - inp.on("error", (err) => { - err.message = `Error occurred while reading ${oldFile}: ${err.message}`; - this.emit("error", err); - }); - const out = fs2.createWriteStream(oldFile + ".gz"); - out.on("error", (err) => { - err.message = `Error occurred while writing ${oldFile}.gz: ${err.message}`; - this.emit("error", err); - }); - inp.pipe(gzip).pipe(out).on("finish", () => { - try { - fs2.unlinkSync(oldFile); - } catch (err) { - if (err.code !== "ENOENT") { - err.message = `Error occurred while removing ${oldFile}: ${err.message}`; - this.emit("error", err); - return; - } - } - this.emit("archive", oldFile + ".gz"); - }); - }); } - if (options.watchLog) { - this.logStream.on("addWatcher", (newFile) => { - this.emit("addWatcher", newFile); - }); + return ""; + } + function getEraYear() { + var i, l, dir, val, eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + dir = eras[i].since <= eras[i].until ? 1 : -1; + val = this.clone().startOf("day").valueOf(); + if (eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) { + return (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset; + } } + return this.year(); } - }; - module2.exports = DailyRotateFile2; - util3.inherits(DailyRotateFile2, Transport2); - DailyRotateFile2.prototype.name = "dailyRotateFile"; - var noop2 = function() { - }; - DailyRotateFile2.prototype.log = function(info, callback) { - callback = callback || noop2; - this.logStream.write(info[MESSAGE] + this.options.eol); - this.emit("logged", info); - callback(null, true); - }; - DailyRotateFile2.prototype.close = function() { - if (this.logStream) { - this.logStream.end(() => { - this.emit("finish"); - }); + function erasNameRegex(isStrict) { + if (!hasOwnProp(this, "_erasNameRegex")) { + computeErasParse.call(this); + } + return isStrict ? this._erasNameRegex : this._erasRegex; } - }; - DailyRotateFile2.prototype.query = function(options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; + function erasAbbrRegex(isStrict) { + if (!hasOwnProp(this, "_erasAbbrRegex")) { + computeErasParse.call(this); + } + return isStrict ? this._erasAbbrRegex : this._erasRegex; } - if (!this.options.json) { - throw new Error( - "query() may not be used without the json option being set to true" - ); + function erasNarrowRegex(isStrict) { + if (!hasOwnProp(this, "_erasNarrowRegex")) { + computeErasParse.call(this); + } + return isStrict ? this._erasNarrowRegex : this._erasRegex; } - if (!this.filename) { - throw new Error("query() may not be used when initializing with a stream"); + function matchEraAbbr(isStrict, locale2) { + return locale2.erasAbbrRegex(isStrict); } - let results = []; - options = options || {}; - options.rows = options.rows || options.limit || 10; - options.start = options.start || 0; - options.until = options.until || /* @__PURE__ */ new Date(); - if (typeof options.until !== "object") { - options.until = new Date(options.until); + function matchEraName(isStrict, locale2) { + return locale2.erasNameRegex(isStrict); } - options.from = options.from || options.until - 24 * 60 * 60 * 1e3; - if (typeof options.from !== "object") { - options.from = new Date(options.from); + function matchEraNarrow(isStrict, locale2) { + return locale2.erasNarrowRegex(isStrict); } - options.order = options.order || "desc"; - const logFiles = (() => { - const fileRegex = new RegExp(this.filename.replace("%DATE%", ".*"), "i"); - return fs2.readdirSync(this.dirname).filter((file) => path.basename(file).match(fileRegex)); - })(); - if (logFiles.length === 0 && callback) { - callback(null, results); + function matchEraYearOrdinal(isStrict, locale2) { + return locale2._eraYearOrdinalRegex || matchUnsigned; } - const processLogFile = (file) => { - if (!file) { - return; - } - const logFile = path.join(this.dirname, file); - let buff = ""; - let stream4; - if (file.endsWith(".gz")) { - stream4 = new PassThrough(); - const inp = fs2.createReadStream(logFile); - inp.on("error", (err) => { - err.message = `Error occurred while reading ${logFile}: ${err.message}`; - stream4.emit("error", err); - }); - inp.pipe(zlib2.createGunzip()).pipe(stream4); - } else { - stream4 = fs2.createReadStream(logFile, { - encoding: "utf8" - }); + function computeErasParse() { + var abbrPieces = [], namePieces = [], narrowPieces = [], mixedPieces = [], i, l, erasName, erasAbbr, erasNarrow, eras = this.eras(); + for (i = 0, l = eras.length; i < l; ++i) { + erasName = regexEscape(eras[i].name); + erasAbbr = regexEscape(eras[i].abbr); + erasNarrow = regexEscape(eras[i].narrow); + namePieces.push(erasName); + abbrPieces.push(erasAbbr); + narrowPieces.push(erasNarrow); + mixedPieces.push(erasName); + mixedPieces.push(erasAbbr); + mixedPieces.push(erasNarrow); } - stream4.on("error", (err) => { - if (stream4.readable) { - stream4.destroy(); - } - if (!callback) { - return; - } - return err.code === "ENOENT" ? callback(null, results) : callback(err); - }); - stream4.on("data", (data) => { - data = (buff + data).split(/\n+/); - const l = data.length - 1; - for (let i = 0; i < l; i++) { - add(data[i]); - } - buff = data[l]; - }); - stream4.on("end", () => { - if (buff) { - add(buff, true); - } - if (logFiles.length) { - processLogFile(logFiles.shift()); - } else if (callback) { - results.sort((a, b2) => { - const d1 = new Date(a.timestamp).getTime(); - const d2 = new Date(b2.timestamp).getTime(); - return d1 > d2 ? 1 : d1 < d2 ? -1 : 0; - }); - if (options.order === "desc") { - results = results.reverse(); - } - const start = options.start || 0; - const limit = options.limit || results.length; - results = results.slice(start, start + limit); - if (options.fields) { - results = results.map((log) => { - const obj = {}; - options.fields.forEach((key) => { - obj[key] = log[key]; - }); - return obj; - }); - } - callback(null, results); - } - }); - function add(buff2, attempt) { - try { - const log = JSON.parse(buff2); - if (!log || typeof log !== "object") { - return; - } - const time = new Date(log.timestamp); - if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) { - return; - } - results.push(log); - } catch (e) { - if (!attempt) { - stream4.emit("error", e); - } - } + this._erasRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); + this._erasNameRegex = new RegExp("^(" + namePieces.join("|") + ")", "i"); + this._erasAbbrRegex = new RegExp("^(" + abbrPieces.join("|") + ")", "i"); + this._erasNarrowRegex = new RegExp( + "^(" + narrowPieces.join("|") + ")", + "i" + ); + } + addFormatToken(0, ["gg", 2], 0, function() { + return this.weekYear() % 100; + }); + addFormatToken(0, ["GG", 2], 0, function() { + return this.isoWeekYear() % 100; + }); + function addWeekYearFormatToken(token2, getter) { + addFormatToken(0, [token2, token2.length], 0, getter); + } + addWeekYearFormatToken("gggg", "weekYear"); + addWeekYearFormatToken("ggggg", "weekYear"); + addWeekYearFormatToken("GGGG", "isoWeekYear"); + addWeekYearFormatToken("GGGGG", "isoWeekYear"); + addRegexToken("G", matchSigned); + addRegexToken("g", matchSigned); + addRegexToken("GG", match1to2, match2); + addRegexToken("gg", match1to2, match2); + addRegexToken("GGGG", match1to4, match4); + addRegexToken("gggg", match1to4, match4); + addRegexToken("GGGGG", match1to6, match6); + addRegexToken("ggggg", match1to6, match6); + addWeekParseToken( + ["gggg", "ggggg", "GGGG", "GGGGG"], + function(input, week, config3, token2) { + week[token2.substr(0, 2)] = toInt(input); } - }; - processLogFile(logFiles.shift()); - }; - } -}); - -// node_modules/winston-daily-rotate-file/index.js -var require_winston_daily_rotate_file = __commonJS({ - "node_modules/winston-daily-rotate-file/index.js"(exports2, module2) { - var winston2 = require_winston(); - var DailyRotateFile2 = require_daily_rotate_file(); - winston2.transports.DailyRotateFile = DailyRotateFile2; - module2.exports = DailyRotateFile2; - } -}); - -// node_modules/abitype/dist/esm/version.js -var version; -var init_version = __esm({ - "node_modules/abitype/dist/esm/version.js"() { - version = "1.0.8"; - } -}); - -// node_modules/abitype/dist/esm/errors.js -var BaseError; -var init_errors = __esm({ - "node_modules/abitype/dist/esm/errors.js"() { - init_version(); - BaseError = class _BaseError extends Error { - constructor(shortMessage, args = {}) { - const details = args.cause instanceof _BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details; - const docsPath6 = args.cause instanceof _BaseError ? args.cause.docsPath || args.docsPath : args.docsPath; - const message = [ - shortMessage || "An error occurred.", - "", - ...args.metaMessages ? [...args.metaMessages, ""] : [], - ...docsPath6 ? [`Docs: https://abitype.dev${docsPath6}`] : [], - ...details ? [`Details: ${details}`] : [], - `Version: abitype@${version}` - ].join("\n"); - super(message); - Object.defineProperty(this, "details", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "docsPath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "metaMessages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "shortMessage", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiTypeError" - }); - if (args.cause) - this.cause = args.cause; - this.details = details; - this.docsPath = docsPath6; - this.metaMessages = args.metaMessages; - this.shortMessage = shortMessage; + ); + addWeekParseToken(["gg", "GG"], function(input, week, config3, token2) { + week[token2] = hooks.parseTwoDigitYear(input); + }); + function getSetWeekYear(input) { + return getSetWeekYearHelper.call( + this, + input, + this.week(), + this.weekday() + this.localeData()._week.dow, + this.localeData()._week.dow, + this.localeData()._week.doy + ); } - }; - } -}); - -// node_modules/abitype/dist/esm/regex.js -function execTyped(regex, string) { - const match = regex.exec(string); - return match?.groups; -} -var bytesRegex, integerRegex, isTupleRegex; -var init_regex = __esm({ - "node_modules/abitype/dist/esm/regex.js"() { - bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; - integerRegex = /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; - isTupleRegex = /^\(.+?\).*?$/; - } -}); - -// node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js -function formatAbiParameter(abiParameter) { - let type = abiParameter.type; - if (tupleRegex.test(abiParameter.type) && "components" in abiParameter) { - type = "("; - const length = abiParameter.components.length; - for (let i = 0; i < length; i++) { - const component = abiParameter.components[i]; - type += formatAbiParameter(component); - if (i < length - 1) - type += ", "; - } - const result = execTyped(tupleRegex, abiParameter.type); - type += `)${result?.array ?? ""}`; - return formatAbiParameter({ - ...abiParameter, - type - }); - } - if ("indexed" in abiParameter && abiParameter.indexed) - type = `${type} indexed`; - if (abiParameter.name) - return `${type} ${abiParameter.name}`; - return type; -} -var tupleRegex; -var init_formatAbiParameter = __esm({ - "node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js"() { - init_regex(); - tupleRegex = /^tuple(?(\[(\d*)\])*)$/; - } -}); - -// node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js -function formatAbiParameters(abiParameters) { - let params = ""; - const length = abiParameters.length; - for (let i = 0; i < length; i++) { - const abiParameter = abiParameters[i]; - params += formatAbiParameter(abiParameter); - if (i !== length - 1) - params += ", "; - } - return params; -} -var init_formatAbiParameters = __esm({ - "node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js"() { - init_formatAbiParameter(); - } -}); - -// node_modules/abitype/dist/esm/human-readable/formatAbiItem.js -function formatAbiItem(abiItem) { - if (abiItem.type === "function") - return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== "nonpayable" ? ` ${abiItem.stateMutability}` : ""}${abiItem.outputs?.length ? ` returns (${formatAbiParameters(abiItem.outputs)})` : ""}`; - if (abiItem.type === "event") - return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; - if (abiItem.type === "error") - return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; - if (abiItem.type === "constructor") - return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === "payable" ? " payable" : ""}`; - if (abiItem.type === "fallback") - return `fallback() external${abiItem.stateMutability === "payable" ? " payable" : ""}`; - return "receive() external payable"; -} -var init_formatAbiItem = __esm({ - "node_modules/abitype/dist/esm/human-readable/formatAbiItem.js"() { - init_formatAbiParameters(); - } -}); - -// node_modules/abitype/dist/esm/human-readable/runtime/signatures.js -function isErrorSignature(signature) { - return errorSignatureRegex.test(signature); -} -function execErrorSignature(signature) { - return execTyped(errorSignatureRegex, signature); -} -function isEventSignature(signature) { - return eventSignatureRegex.test(signature); -} -function execEventSignature(signature) { - return execTyped(eventSignatureRegex, signature); -} -function isFunctionSignature(signature) { - return functionSignatureRegex.test(signature); -} -function execFunctionSignature(signature) { - return execTyped(functionSignatureRegex, signature); -} -function isStructSignature(signature) { - return structSignatureRegex.test(signature); -} -function execStructSignature(signature) { - return execTyped(structSignatureRegex, signature); -} -function isConstructorSignature(signature) { - return constructorSignatureRegex.test(signature); -} -function execConstructorSignature(signature) { - return execTyped(constructorSignatureRegex, signature); -} -function isFallbackSignature(signature) { - return fallbackSignatureRegex.test(signature); -} -function execFallbackSignature(signature) { - return execTyped(fallbackSignatureRegex, signature); -} -function isReceiveSignature(signature) { - return receiveSignatureRegex.test(signature); -} -var errorSignatureRegex, eventSignatureRegex, functionSignatureRegex, structSignatureRegex, constructorSignatureRegex, fallbackSignatureRegex, receiveSignatureRegex, modifiers, eventModifiers, functionModifiers; -var init_signatures = __esm({ - "node_modules/abitype/dist/esm/human-readable/runtime/signatures.js"() { - init_regex(); - errorSignatureRegex = /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; - eventSignatureRegex = /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; - functionSignatureRegex = /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/; - structSignatureRegex = /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/; - constructorSignatureRegex = /^constructor\((?.*?)\)(?:\s(?payable{1}))?$/; - fallbackSignatureRegex = /^fallback\(\) external(?:\s(?payable{1}))?$/; - receiveSignatureRegex = /^receive\(\) external payable$/; - modifiers = /* @__PURE__ */ new Set([ - "memory", - "indexed", - "storage", - "calldata" - ]); - eventModifiers = /* @__PURE__ */ new Set(["indexed"]); - functionModifiers = /* @__PURE__ */ new Set([ - "calldata", - "memory", - "storage" - ]); - } -}); - -// node_modules/abitype/dist/esm/human-readable/errors/abiItem.js -var InvalidAbiItemError, UnknownTypeError, UnknownSolidityTypeError; -var init_abiItem = __esm({ - "node_modules/abitype/dist/esm/human-readable/errors/abiItem.js"() { - init_errors(); - InvalidAbiItemError = class extends BaseError { - constructor({ signature }) { - super("Failed to parse ABI item.", { - details: `parseAbiItem(${JSON.stringify(signature, null, 2)})`, - docsPath: "/api/human#parseabiitem-1" - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidAbiItemError" - }); + function getSetISOWeekYear(input) { + return getSetWeekYearHelper.call( + this, + input, + this.isoWeek(), + this.isoWeekday(), + 1, + 4 + ); } - }; - UnknownTypeError = class extends BaseError { - constructor({ type }) { - super("Unknown type.", { - metaMessages: [ - `Type "${type}" is not a valid ABI type. Perhaps you forgot to include a struct signature?` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "UnknownTypeError" - }); + function getISOWeeksInYear() { + return weeksInYear(this.year(), 1, 4); } - }; - UnknownSolidityTypeError = class extends BaseError { - constructor({ type }) { - super("Unknown type.", { - metaMessages: [`Type "${type}" is not a valid ABI type.`] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "UnknownSolidityTypeError" - }); + function getISOWeeksInISOWeekYear() { + return weeksInYear(this.isoWeekYear(), 1, 4); } - }; - } -}); - -// node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js -var InvalidAbiParametersError, InvalidParameterError, SolidityProtectedKeywordError, InvalidModifierError, InvalidFunctionModifierError, InvalidAbiTypeParameterError; -var init_abiParameter = __esm({ - "node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js"() { - init_errors(); - InvalidAbiParametersError = class extends BaseError { - constructor({ params }) { - super("Failed to parse ABI parameters.", { - details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`, - docsPath: "/api/human#parseabiparameters-1" - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidAbiParametersError" - }); + function getWeeksInYear() { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } - }; - InvalidParameterError = class extends BaseError { - constructor({ param }) { - super("Invalid ABI parameter.", { - details: param - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidParameterError" - }); + function getWeeksInWeekYear() { + var weekInfo = this.localeData()._week; + return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); } - }; - SolidityProtectedKeywordError = class extends BaseError { - constructor({ param, name }) { - super("Invalid ABI parameter.", { - details: param, - metaMessages: [ - `"${name}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "SolidityProtectedKeywordError" - }); + function getSetWeekYearHelper(input, week, weekday, dow, doy) { + var weeksTarget; + if (input == null) { + return weekOfYear(this, dow, doy).year; + } else { + weeksTarget = weeksInYear(input, dow, doy); + if (week > weeksTarget) { + week = weeksTarget; + } + return setWeekAll.call(this, input, week, weekday, dow, doy); + } } - }; - InvalidModifierError = class extends BaseError { - constructor({ param, type, modifier }) { - super("Invalid ABI parameter.", { - details: param, - metaMessages: [ - `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidModifierError" - }); + function setWeekAll(weekYear, week, weekday, dow, doy) { + var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); + this.year(date.getUTCFullYear()); + this.month(date.getUTCMonth()); + this.date(date.getUTCDate()); + return this; } - }; - InvalidFunctionModifierError = class extends BaseError { - constructor({ param, type, modifier }) { - super("Invalid ABI parameter.", { - details: param, - metaMessages: [ - `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.`, - `Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidFunctionModifierError" - }); + addFormatToken("Q", 0, "Qo", "quarter"); + addRegexToken("Q", match1); + addParseToken("Q", function(input, array) { + array[MONTH] = (toInt(input) - 1) * 3; + }); + function getSetQuarter(input) { + return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); + } + addFormatToken("D", ["DD", 2], "Do", "date"); + addRegexToken("D", match1to2, match1to2NoLeadingZero); + addRegexToken("DD", match1to2, match2); + addRegexToken("Do", function(isStrict, locale2) { + return isStrict ? locale2._dayOfMonthOrdinalParse || locale2._ordinalParse : locale2._dayOfMonthOrdinalParseLenient; + }); + addParseToken(["D", "DD"], DATE); + addParseToken("Do", function(input, array) { + array[DATE] = toInt(input.match(match1to2)[0]); + }); + var getSetDayOfMonth = makeGetSet("Date", true); + addFormatToken("DDD", ["DDDD", 3], "DDDo", "dayOfYear"); + addRegexToken("DDD", match1to3); + addRegexToken("DDDD", match3); + addParseToken(["DDD", "DDDD"], function(input, array, config3) { + config3._dayOfYear = toInt(input); + }); + function getSetDayOfYear(input) { + var dayOfYear = Math.round( + (this.clone().startOf("day") - this.clone().startOf("year")) / 864e5 + ) + 1; + return input == null ? dayOfYear : this.add(input - dayOfYear, "d"); + } + addFormatToken("m", ["mm", 2], 0, "minute"); + addRegexToken("m", match1to2, match1to2HasZero); + addRegexToken("mm", match1to2, match2); + addParseToken(["m", "mm"], MINUTE); + var getSetMinute = makeGetSet("Minutes", false); + addFormatToken("s", ["ss", 2], 0, "second"); + addRegexToken("s", match1to2, match1to2HasZero); + addRegexToken("ss", match1to2, match2); + addParseToken(["s", "ss"], SECOND); + var getSetSecond = makeGetSet("Seconds", false); + addFormatToken("S", 0, 0, function() { + return ~~(this.millisecond() / 100); + }); + addFormatToken(0, ["SS", 2], 0, function() { + return ~~(this.millisecond() / 10); + }); + addFormatToken(0, ["SSS", 3], 0, "millisecond"); + addFormatToken(0, ["SSSS", 4], 0, function() { + return this.millisecond() * 10; + }); + addFormatToken(0, ["SSSSS", 5], 0, function() { + return this.millisecond() * 100; + }); + addFormatToken(0, ["SSSSSS", 6], 0, function() { + return this.millisecond() * 1e3; + }); + addFormatToken(0, ["SSSSSSS", 7], 0, function() { + return this.millisecond() * 1e4; + }); + addFormatToken(0, ["SSSSSSSS", 8], 0, function() { + return this.millisecond() * 1e5; + }); + addFormatToken(0, ["SSSSSSSSS", 9], 0, function() { + return this.millisecond() * 1e6; + }); + addRegexToken("S", match1to3, match1); + addRegexToken("SS", match1to3, match2); + addRegexToken("SSS", match1to3, match3); + var token, getSetMillisecond; + for (token = "SSSS"; token.length <= 9; token += "S") { + addRegexToken(token, matchUnsigned); + } + function parseMs(input, array) { + array[MILLISECOND] = toInt(("0." + input) * 1e3); + } + for (token = "S"; token.length <= 9; token += "S") { + addParseToken(token, parseMs); + } + getSetMillisecond = makeGetSet("Milliseconds", false); + addFormatToken("z", 0, 0, "zoneAbbr"); + addFormatToken("zz", 0, 0, "zoneName"); + function getZoneAbbr() { + return this._isUTC ? "UTC" : ""; + } + function getZoneName() { + return this._isUTC ? "Coordinated Universal Time" : ""; + } + var proto = Moment.prototype; + proto.add = add; + proto.calendar = calendar$1; + proto.clone = clone; + proto.diff = diff; + proto.endOf = endOf; + proto.format = format; + proto.from = from5; + proto.fromNow = fromNow; + proto.to = to2; + proto.toNow = toNow; + proto.get = stringGet; + proto.invalidAt = invalidAt; + proto.isAfter = isAfter; + proto.isBefore = isBefore; + proto.isBetween = isBetween; + proto.isSame = isSame; + proto.isSameOrAfter = isSameOrAfter; + proto.isSameOrBefore = isSameOrBefore; + proto.isValid = isValid$2; + proto.lang = lang; + proto.locale = locale; + proto.localeData = localeData; + proto.max = prototypeMax; + proto.min = prototypeMin; + proto.parsingFlags = parsingFlags; + proto.set = stringSet; + proto.startOf = startOf; + proto.subtract = subtract; + proto.toArray = toArray2; + proto.toObject = toObject; + proto.toDate = toDate; + proto.toISOString = toISOString; + proto.inspect = inspect; + if (typeof Symbol !== "undefined" && Symbol.for != null) { + proto[Symbol.for("nodejs.util.inspect.custom")] = function() { + return "Moment<" + this.format() + ">"; + }; + } + proto.toJSON = toJSON2; + proto.toString = toString3; + proto.unix = unix; + proto.valueOf = valueOf; + proto.creationData = creationData; + proto.eraName = getEraName; + proto.eraNarrow = getEraNarrow; + proto.eraAbbr = getEraAbbr; + proto.eraYear = getEraYear; + proto.year = getSetYear; + proto.isLeapYear = getIsLeapYear; + proto.weekYear = getSetWeekYear; + proto.isoWeekYear = getSetISOWeekYear; + proto.quarter = proto.quarters = getSetQuarter; + proto.month = getSetMonth; + proto.daysInMonth = getDaysInMonth; + proto.week = proto.weeks = getSetWeek; + proto.isoWeek = proto.isoWeeks = getSetISOWeek; + proto.weeksInYear = getWeeksInYear; + proto.weeksInWeekYear = getWeeksInWeekYear; + proto.isoWeeksInYear = getISOWeeksInYear; + proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear; + proto.date = getSetDayOfMonth; + proto.day = proto.days = getSetDayOfWeek; + proto.weekday = getSetLocaleDayOfWeek; + proto.isoWeekday = getSetISODayOfWeek; + proto.dayOfYear = getSetDayOfYear; + proto.hour = proto.hours = getSetHour; + proto.minute = proto.minutes = getSetMinute; + proto.second = proto.seconds = getSetSecond; + proto.millisecond = proto.milliseconds = getSetMillisecond; + proto.utcOffset = getSetOffset; + proto.utc = setOffsetToUTC; + proto.local = setOffsetToLocal; + proto.parseZone = setOffsetToParsedOffset; + proto.hasAlignedHourOffset = hasAlignedHourOffset; + proto.isDST = isDaylightSavingTime; + proto.isLocal = isLocal; + proto.isUtcOffset = isUtcOffset; + proto.isUtc = isUtc; + proto.isUTC = isUtc; + proto.zoneAbbr = getZoneAbbr; + proto.zoneName = getZoneName; + proto.dates = deprecate( + "dates accessor is deprecated. Use date instead.", + getSetDayOfMonth + ); + proto.months = deprecate( + "months accessor is deprecated. Use month instead", + getSetMonth + ); + proto.years = deprecate( + "years accessor is deprecated. Use year instead", + getSetYear + ); + proto.zone = deprecate( + "moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/", + getSetZone + ); + proto.isDSTShifted = deprecate( + "isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information", + isDaylightSavingTimeShifted + ); + function createUnix(input) { + return createLocal(input * 1e3); } - }; - InvalidAbiTypeParameterError = class extends BaseError { - constructor({ abiParameter }) { - super("Invalid ABI parameter.", { - details: JSON.stringify(abiParameter, null, 2), - metaMessages: ["ABI parameter type is invalid."] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidAbiTypeParameterError" - }); + function createInZone() { + return createLocal.apply(null, arguments).parseZone(); } - }; - } -}); - -// node_modules/abitype/dist/esm/human-readable/errors/signature.js -var InvalidSignatureError, UnknownSignatureError, InvalidStructSignatureError; -var init_signature = __esm({ - "node_modules/abitype/dist/esm/human-readable/errors/signature.js"() { - init_errors(); - InvalidSignatureError = class extends BaseError { - constructor({ signature, type }) { - super(`Invalid ${type} signature.`, { - details: signature - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidSignatureError" - }); + function preParsePostFormat(string) { + return string; } - }; - UnknownSignatureError = class extends BaseError { - constructor({ signature }) { - super("Unknown signature.", { - details: signature - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "UnknownSignatureError" - }); + var proto$1 = Locale.prototype; + proto$1.calendar = calendar; + proto$1.longDateFormat = longDateFormat; + proto$1.invalidDate = invalidDate; + proto$1.ordinal = ordinal; + proto$1.preparse = preParsePostFormat; + proto$1.postformat = preParsePostFormat; + proto$1.relativeTime = relativeTime; + proto$1.pastFuture = pastFuture; + proto$1.set = set; + proto$1.eras = localeEras; + proto$1.erasParse = localeErasParse; + proto$1.erasConvertYear = localeErasConvertYear; + proto$1.erasAbbrRegex = erasAbbrRegex; + proto$1.erasNameRegex = erasNameRegex; + proto$1.erasNarrowRegex = erasNarrowRegex; + proto$1.months = localeMonths; + proto$1.monthsShort = localeMonthsShort; + proto$1.monthsParse = localeMonthsParse; + proto$1.monthsRegex = monthsRegex; + proto$1.monthsShortRegex = monthsShortRegex; + proto$1.week = localeWeek; + proto$1.firstDayOfYear = localeFirstDayOfYear; + proto$1.firstDayOfWeek = localeFirstDayOfWeek; + proto$1.weekdays = localeWeekdays; + proto$1.weekdaysMin = localeWeekdaysMin; + proto$1.weekdaysShort = localeWeekdaysShort; + proto$1.weekdaysParse = localeWeekdaysParse; + proto$1.weekdaysRegex = weekdaysRegex; + proto$1.weekdaysShortRegex = weekdaysShortRegex; + proto$1.weekdaysMinRegex = weekdaysMinRegex; + proto$1.isPM = localeIsPM; + proto$1.meridiem = localeMeridiem; + function get$1(format2, index2, field, setter) { + var locale2 = getLocale(), utc = createUTC().set(setter, index2); + return locale2[field](utc, format2); } - }; - InvalidStructSignatureError = class extends BaseError { - constructor({ signature }) { - super("Invalid struct signature.", { - details: signature, - metaMessages: ["No properties exist."] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidStructSignatureError" - }); + function listMonthsImpl(format2, index2, field) { + if (isNumber2(format2)) { + index2 = format2; + format2 = void 0; + } + format2 = format2 || ""; + if (index2 != null) { + return get$1(format2, index2, field, "month"); + } + var i, out = []; + for (i = 0; i < 12; i++) { + out[i] = get$1(format2, i, field, "month"); + } + return out; } - }; - } -}); - -// node_modules/abitype/dist/esm/human-readable/errors/struct.js -var CircularReferenceError; -var init_struct = __esm({ - "node_modules/abitype/dist/esm/human-readable/errors/struct.js"() { - init_errors(); - CircularReferenceError = class extends BaseError { - constructor({ type }) { - super("Circular reference detected.", { - metaMessages: [`Struct "${type}" is a circular reference.`] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "CircularReferenceError" - }); + function listWeekdaysImpl(localeSorted, format2, index2, field) { + if (typeof localeSorted === "boolean") { + if (isNumber2(format2)) { + index2 = format2; + format2 = void 0; + } + format2 = format2 || ""; + } else { + format2 = localeSorted; + index2 = format2; + localeSorted = false; + if (isNumber2(format2)) { + index2 = format2; + format2 = void 0; + } + format2 = format2 || ""; + } + var locale2 = getLocale(), shift = localeSorted ? locale2._week.dow : 0, i, out = []; + if (index2 != null) { + return get$1(format2, (index2 + shift) % 7, field, "day"); + } + for (i = 0; i < 7; i++) { + out[i] = get$1(format2, (i + shift) % 7, field, "day"); + } + return out; } - }; - } -}); - -// node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js -var InvalidParenthesisError; -var init_splitParameters = __esm({ - "node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js"() { - init_errors(); - InvalidParenthesisError = class extends BaseError { - constructor({ current, depth }) { - super("Unbalanced parentheses.", { - metaMessages: [ - `"${current.trim()}" has too many ${depth > 0 ? "opening" : "closing"} parentheses.` - ], - details: `Depth "${depth}"` - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "InvalidParenthesisError" - }); + function listMonths(format2, index2) { + return listMonthsImpl(format2, index2, "months"); } - }; - } -}); - -// node_modules/abitype/dist/esm/human-readable/runtime/cache.js -function getParameterCacheKey(param, type, structs) { - let structKey = ""; - if (structs) - for (const struct of Object.entries(structs)) { - if (!struct) - continue; - let propertyKey = ""; - for (const property of struct[1]) { - propertyKey += `[${property.type}${property.name ? `:${property.name}` : ""}]`; + function listMonthsShort(format2, index2) { + return listMonthsImpl(format2, index2, "monthsShort"); } - structKey += `(${struct[0]}{${propertyKey}})`; - } - if (type) - return `${type}:${param}${structKey}`; - return param; -} -var parameterCache; -var init_cache = __esm({ - "node_modules/abitype/dist/esm/human-readable/runtime/cache.js"() { - parameterCache = /* @__PURE__ */ new Map([ - // Unnamed - ["address", { type: "address" }], - ["bool", { type: "bool" }], - ["bytes", { type: "bytes" }], - ["bytes32", { type: "bytes32" }], - ["int", { type: "int256" }], - ["int256", { type: "int256" }], - ["string", { type: "string" }], - ["uint", { type: "uint256" }], - ["uint8", { type: "uint8" }], - ["uint16", { type: "uint16" }], - ["uint24", { type: "uint24" }], - ["uint32", { type: "uint32" }], - ["uint64", { type: "uint64" }], - ["uint96", { type: "uint96" }], - ["uint112", { type: "uint112" }], - ["uint160", { type: "uint160" }], - ["uint192", { type: "uint192" }], - ["uint256", { type: "uint256" }], - // Named - ["address owner", { type: "address", name: "owner" }], - ["address to", { type: "address", name: "to" }], - ["bool approved", { type: "bool", name: "approved" }], - ["bytes _data", { type: "bytes", name: "_data" }], - ["bytes data", { type: "bytes", name: "data" }], - ["bytes signature", { type: "bytes", name: "signature" }], - ["bytes32 hash", { type: "bytes32", name: "hash" }], - ["bytes32 r", { type: "bytes32", name: "r" }], - ["bytes32 root", { type: "bytes32", name: "root" }], - ["bytes32 s", { type: "bytes32", name: "s" }], - ["string name", { type: "string", name: "name" }], - ["string symbol", { type: "string", name: "symbol" }], - ["string tokenURI", { type: "string", name: "tokenURI" }], - ["uint tokenId", { type: "uint256", name: "tokenId" }], - ["uint8 v", { type: "uint8", name: "v" }], - ["uint256 balance", { type: "uint256", name: "balance" }], - ["uint256 tokenId", { type: "uint256", name: "tokenId" }], - ["uint256 value", { type: "uint256", name: "value" }], - // Indexed - [ - "event:address indexed from", - { type: "address", name: "from", indexed: true } - ], - ["event:address indexed to", { type: "address", name: "to", indexed: true }], - [ - "event:uint indexed tokenId", - { type: "uint256", name: "tokenId", indexed: true } - ], - [ - "event:uint256 indexed tokenId", - { type: "uint256", name: "tokenId", indexed: true } - ] - ]); - } -}); - -// node_modules/abitype/dist/esm/human-readable/runtime/utils.js -function parseSignature(signature, structs = {}) { - if (isFunctionSignature(signature)) - return parseFunctionSignature(signature, structs); - if (isEventSignature(signature)) - return parseEventSignature(signature, structs); - if (isErrorSignature(signature)) - return parseErrorSignature(signature, structs); - if (isConstructorSignature(signature)) - return parseConstructorSignature(signature, structs); - if (isFallbackSignature(signature)) - return parseFallbackSignature(signature); - if (isReceiveSignature(signature)) - return { - type: "receive", - stateMutability: "payable" - }; - throw new UnknownSignatureError({ signature }); -} -function parseFunctionSignature(signature, structs = {}) { - const match = execFunctionSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "function" }); - const inputParams = splitParameters(match.parameters); - const inputs = []; - const inputLength = inputParams.length; - for (let i = 0; i < inputLength; i++) { - inputs.push(parseAbiParameter(inputParams[i], { - modifiers: functionModifiers, - structs, - type: "function" - })); - } - const outputs = []; - if (match.returns) { - const outputParams = splitParameters(match.returns); - const outputLength = outputParams.length; - for (let i = 0; i < outputLength; i++) { - outputs.push(parseAbiParameter(outputParams[i], { - modifiers: functionModifiers, - structs, - type: "function" - })); - } - } - return { - name: match.name, - type: "function", - stateMutability: match.stateMutability ?? "nonpayable", - inputs, - outputs - }; -} -function parseEventSignature(signature, structs = {}) { - const match = execEventSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "event" }); - const params = splitParameters(match.parameters); - const abiParameters = []; - const length = params.length; - for (let i = 0; i < length; i++) - abiParameters.push(parseAbiParameter(params[i], { - modifiers: eventModifiers, - structs, - type: "event" - })); - return { name: match.name, type: "event", inputs: abiParameters }; -} -function parseErrorSignature(signature, structs = {}) { - const match = execErrorSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "error" }); - const params = splitParameters(match.parameters); - const abiParameters = []; - const length = params.length; - for (let i = 0; i < length; i++) - abiParameters.push(parseAbiParameter(params[i], { structs, type: "error" })); - return { name: match.name, type: "error", inputs: abiParameters }; -} -function parseConstructorSignature(signature, structs = {}) { - const match = execConstructorSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "constructor" }); - const params = splitParameters(match.parameters); - const abiParameters = []; - const length = params.length; - for (let i = 0; i < length; i++) - abiParameters.push(parseAbiParameter(params[i], { structs, type: "constructor" })); - return { - type: "constructor", - stateMutability: match.stateMutability ?? "nonpayable", - inputs: abiParameters - }; -} -function parseFallbackSignature(signature) { - const match = execFallbackSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "fallback" }); - return { - type: "fallback", - stateMutability: match.stateMutability ?? "nonpayable" - }; -} -function parseAbiParameter(param, options) { - const parameterCacheKey = getParameterCacheKey(param, options?.type, options?.structs); - if (parameterCache.has(parameterCacheKey)) - return parameterCache.get(parameterCacheKey); - const isTuple = isTupleRegex.test(param); - const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param); - if (!match) - throw new InvalidParameterError({ param }); - if (match.name && isSolidityKeyword(match.name)) - throw new SolidityProtectedKeywordError({ param, name: match.name }); - const name = match.name ? { name: match.name } : {}; - const indexed = match.modifier === "indexed" ? { indexed: true } : {}; - const structs = options?.structs ?? {}; - let type; - let components = {}; - if (isTuple) { - type = "tuple"; - const params = splitParameters(match.type); - const components_ = []; - const length = params.length; - for (let i = 0; i < length; i++) { - components_.push(parseAbiParameter(params[i], { structs })); - } - components = { components: components_ }; - } else if (match.type in structs) { - type = "tuple"; - components = { components: structs[match.type] }; - } else if (dynamicIntegerRegex.test(match.type)) { - type = `${match.type}256`; - } else { - type = match.type; - if (!(options?.type === "struct") && !isSolidityType(type)) - throw new UnknownSolidityTypeError({ type }); - } - if (match.modifier) { - if (!options?.modifiers?.has?.(match.modifier)) - throw new InvalidModifierError({ - param, - type: options?.type, - modifier: match.modifier - }); - if (functionModifiers.has(match.modifier) && !isValidDataLocation(type, !!match.array)) - throw new InvalidFunctionModifierError({ - param, - type: options?.type, - modifier: match.modifier - }); - } - const abiParameter = { - type: `${type}${match.array ?? ""}`, - ...name, - ...indexed, - ...components - }; - parameterCache.set(parameterCacheKey, abiParameter); - return abiParameter; -} -function splitParameters(params, result = [], current = "", depth = 0) { - const length = params.trim().length; - for (let i = 0; i < length; i++) { - const char = params[i]; - const tail = params.slice(i + 1); - switch (char) { - case ",": - return depth === 0 ? splitParameters(tail, [...result, current.trim()]) : splitParameters(tail, result, `${current}${char}`, depth); - case "(": - return splitParameters(tail, result, `${current}${char}`, depth + 1); - case ")": - return splitParameters(tail, result, `${current}${char}`, depth - 1); - default: - return splitParameters(tail, result, `${current}${char}`, depth); - } - } - if (current === "") - return result; - if (depth !== 0) - throw new InvalidParenthesisError({ current, depth }); - result.push(current.trim()); - return result; -} -function isSolidityType(type) { - return type === "address" || type === "bool" || type === "function" || type === "string" || bytesRegex.test(type) || integerRegex.test(type); -} -function isSolidityKeyword(name) { - return name === "address" || name === "bool" || name === "function" || name === "string" || name === "tuple" || bytesRegex.test(name) || integerRegex.test(name) || protectedKeywordsRegex.test(name); -} -function isValidDataLocation(type, isArray2) { - return isArray2 || type === "bytes" || type === "string" || type === "tuple"; -} -var abiParameterWithoutTupleRegex, abiParameterWithTupleRegex, dynamicIntegerRegex, protectedKeywordsRegex; -var init_utils = __esm({ - "node_modules/abitype/dist/esm/human-readable/runtime/utils.js"() { - init_regex(); - init_abiItem(); - init_abiParameter(); - init_signature(); - init_splitParameters(); - init_cache(); - init_signatures(); - abiParameterWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; - abiParameterWithTupleRegex = /^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; - dynamicIntegerRegex = /^u?int$/; - protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/; - } -}); - -// node_modules/abitype/dist/esm/human-readable/runtime/structs.js -function parseStructs(signatures) { - const shallowStructs = {}; - const signaturesLength = signatures.length; - for (let i = 0; i < signaturesLength; i++) { - const signature = signatures[i]; - if (!isStructSignature(signature)) - continue; - const match = execStructSignature(signature); - if (!match) - throw new InvalidSignatureError({ signature, type: "struct" }); - const properties = match.properties.split(";"); - const components = []; - const propertiesLength = properties.length; - for (let k2 = 0; k2 < propertiesLength; k2++) { - const property = properties[k2]; - const trimmed = property.trim(); - if (!trimmed) - continue; - const abiParameter = parseAbiParameter(trimmed, { - type: "struct" + function listWeekdays(localeSorted, format2, index2) { + return listWeekdaysImpl(localeSorted, format2, index2, "weekdays"); + } + function listWeekdaysShort(localeSorted, format2, index2) { + return listWeekdaysImpl(localeSorted, format2, index2, "weekdaysShort"); + } + function listWeekdaysMin(localeSorted, format2, index2) { + return listWeekdaysImpl(localeSorted, format2, index2, "weekdaysMin"); + } + getSetGlobalLocale("en", { + eras: [ + { + since: "0001-01-01", + until: Infinity, + offset: 1, + name: "Anno Domini", + narrow: "AD", + abbr: "AD" + }, + { + since: "0000-12-31", + until: -Infinity, + offset: 1, + name: "Before Christ", + narrow: "BC", + abbr: "BC" + } + ], + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal: function(number) { + var b2 = number % 10, output = toInt(number % 100 / 10) === 1 ? "th" : b2 === 1 ? "st" : b2 === 2 ? "nd" : b2 === 3 ? "rd" : "th"; + return number + output; + } }); - components.push(abiParameter); - } - if (!components.length) - throw new InvalidStructSignatureError({ signature }); - shallowStructs[match.name] = components; - } - const resolvedStructs = {}; - const entries = Object.entries(shallowStructs); - const entriesLength = entries.length; - for (let i = 0; i < entriesLength; i++) { - const [name, parameters] = entries[i]; - resolvedStructs[name] = resolveStructs(parameters, shallowStructs); - } - return resolvedStructs; -} -function resolveStructs(abiParameters, structs, ancestors = /* @__PURE__ */ new Set()) { - const components = []; - const length = abiParameters.length; - for (let i = 0; i < length; i++) { - const abiParameter = abiParameters[i]; - const isTuple = isTupleRegex.test(abiParameter.type); - if (isTuple) - components.push(abiParameter); - else { - const match = execTyped(typeWithoutTupleRegex, abiParameter.type); - if (!match?.type) - throw new InvalidAbiTypeParameterError({ abiParameter }); - const { array, type } = match; - if (type in structs) { - if (ancestors.has(type)) - throw new CircularReferenceError({ type }); - components.push({ - ...abiParameter, - type: `tuple${array ?? ""}`, - components: resolveStructs(structs[type] ?? [], structs, /* @__PURE__ */ new Set([...ancestors, type])) - }); - } else { - if (isSolidityType(type)) - components.push(abiParameter); - else - throw new UnknownTypeError({ type }); + hooks.lang = deprecate( + "moment.lang is deprecated. Use moment.locale instead.", + getSetGlobalLocale + ); + hooks.langData = deprecate( + "moment.langData is deprecated. Use moment.localeData instead.", + getLocale + ); + var mathAbs = Math.abs; + function abs() { + var data = this._data; + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); + return this; } - } - } - return components; -} -var typeWithoutTupleRegex; -var init_structs = __esm({ - "node_modules/abitype/dist/esm/human-readable/runtime/structs.js"() { - init_regex(); - init_abiItem(); - init_abiParameter(); - init_signature(); - init_struct(); - init_signatures(); - init_utils(); - typeWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/; - } -}); - -// node_modules/abitype/dist/esm/human-readable/parseAbi.js -function parseAbi(signatures) { - const structs = parseStructs(signatures); - const abi4 = []; - const length = signatures.length; - for (let i = 0; i < length; i++) { - const signature = signatures[i]; - if (isStructSignature(signature)) - continue; - abi4.push(parseSignature(signature, structs)); - } - return abi4; -} -var init_parseAbi = __esm({ - "node_modules/abitype/dist/esm/human-readable/parseAbi.js"() { - init_signatures(); - init_structs(); - init_utils(); - } -}); - -// node_modules/abitype/dist/esm/human-readable/parseAbiItem.js -function parseAbiItem(signature) { - let abiItem; - if (typeof signature === "string") - abiItem = parseSignature(signature); - else { - const structs = parseStructs(signature); - const length = signature.length; - for (let i = 0; i < length; i++) { - const signature_ = signature[i]; - if (isStructSignature(signature_)) - continue; - abiItem = parseSignature(signature_, structs); - break; - } - } - if (!abiItem) - throw new InvalidAbiItemError({ signature }); - return abiItem; -} -var init_parseAbiItem = __esm({ - "node_modules/abitype/dist/esm/human-readable/parseAbiItem.js"() { - init_abiItem(); - init_signatures(); - init_structs(); - init_utils(); - } -}); - -// node_modules/abitype/dist/esm/human-readable/parseAbiParameters.js -function parseAbiParameters(params) { - const abiParameters = []; - if (typeof params === "string") { - const parameters = splitParameters(params); - const length = parameters.length; - for (let i = 0; i < length; i++) { - abiParameters.push(parseAbiParameter(parameters[i], { modifiers })); - } - } else { - const structs = parseStructs(params); - const length = params.length; - for (let i = 0; i < length; i++) { - const signature = params[i]; - if (isStructSignature(signature)) - continue; - const parameters = splitParameters(signature); - const length2 = parameters.length; - for (let k2 = 0; k2 < length2; k2++) { - abiParameters.push(parseAbiParameter(parameters[k2], { modifiers, structs })); + function addSubtract$1(duration, input, value, direction) { + var other = createDuration(input, value); + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; + return duration._bubble(); } - } - } - if (abiParameters.length === 0) - throw new InvalidAbiParametersError({ params }); - return abiParameters; -} -var init_parseAbiParameters = __esm({ - "node_modules/abitype/dist/esm/human-readable/parseAbiParameters.js"() { - init_abiParameter(); - init_signatures(); - init_structs(); - init_utils(); - init_utils(); - } -}); - -// node_modules/abitype/dist/esm/exports/index.js -var init_exports = __esm({ - "node_modules/abitype/dist/esm/exports/index.js"() { - init_formatAbiItem(); - init_parseAbi(); - init_parseAbiItem(); - init_parseAbiParameters(); - } -}); - -// node_modules/viem/_esm/utils/abi/formatAbiItem.js -function formatAbiItem2(abiItem, { includeName = false } = {}) { - if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error") - throw new InvalidDefinitionTypeError(abiItem.type); - return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`; -} -function formatAbiParams(params, { includeName = false } = {}) { - if (!params) - return ""; - return params.map((param) => formatAbiParam(param, { includeName })).join(includeName ? ", " : ","); -} -function formatAbiParam(param, { includeName }) { - if (param.type.startsWith("tuple")) { - return `(${formatAbiParams(param.components, { includeName })})${param.type.slice("tuple".length)}`; - } - return param.type + (includeName && param.name ? ` ${param.name}` : ""); -} -var init_formatAbiItem2 = __esm({ - "node_modules/viem/_esm/utils/abi/formatAbiItem.js"() { - init_abi(); - } -}); - -// node_modules/viem/_esm/utils/data/isHex.js -function isHex(value, { strict = true } = {}) { - if (!value) - return false; - if (typeof value !== "string") - return false; - return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x"); -} -var init_isHex = __esm({ - "node_modules/viem/_esm/utils/data/isHex.js"() { - } -}); - -// node_modules/viem/_esm/utils/data/size.js -function size(value) { - if (isHex(value, { strict: false })) - return Math.ceil((value.length - 2) / 2); - return value.length; -} -var init_size = __esm({ - "node_modules/viem/_esm/utils/data/size.js"() { - init_isHex(); - } -}); - -// node_modules/viem/_esm/errors/version.js -var version2; -var init_version2 = __esm({ - "node_modules/viem/_esm/errors/version.js"() { - version2 = "2.24.1"; - } -}); - -// node_modules/viem/_esm/errors/base.js -function walk(err, fn2) { - if (fn2?.(err)) - return err; - if (err && typeof err === "object" && "cause" in err && err.cause !== void 0) - return walk(err.cause, fn2); - return fn2 ? null : err; -} -var errorConfig, BaseError2; -var init_base = __esm({ - "node_modules/viem/_esm/errors/base.js"() { - init_version2(); - errorConfig = { - getDocsUrl: ({ docsBaseUrl, docsPath: docsPath6 = "", docsSlug }) => docsPath6 ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath6}${docsSlug ? `#${docsSlug}` : ""}` : void 0, - version: `viem@${version2}` - }; - BaseError2 = class _BaseError extends Error { - constructor(shortMessage, args = {}) { - const details = (() => { - if (args.cause instanceof _BaseError) - return args.cause.details; - if (args.cause?.message) - return args.cause.message; - return args.details; - })(); - const docsPath6 = (() => { - if (args.cause instanceof _BaseError) - return args.cause.docsPath || args.docsPath; - return args.docsPath; - })(); - const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath: docsPath6 }); - const message = [ - shortMessage || "An error occurred.", - "", - ...args.metaMessages ? [...args.metaMessages, ""] : [], - ...docsUrl ? [`Docs: ${docsUrl}`] : [], - ...details ? [`Details: ${details}`] : [], - ...errorConfig.version ? [`Version: ${errorConfig.version}`] : [] - ].join("\n"); - super(message, args.cause ? { cause: args.cause } : void 0); - Object.defineProperty(this, "details", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "docsPath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "metaMessages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "shortMessage", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "version", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "BaseError" - }); - this.details = details; - this.docsPath = docsPath6; - this.metaMessages = args.metaMessages; - this.name = args.name ?? this.name; - this.shortMessage = shortMessage; - this.version = version2; + function add$1(input, value) { + return addSubtract$1(this, input, value, 1); } - walk(fn2) { - return walk(this, fn2); + function subtract$1(input, value) { + return addSubtract$1(this, input, value, -1); } - }; - } -}); - -// node_modules/viem/_esm/errors/abi.js -var AbiConstructorNotFoundError, AbiConstructorParamsNotFoundError, AbiDecodingDataSizeTooSmallError, AbiDecodingZeroDataError, AbiEncodingArrayLengthMismatchError, AbiEncodingBytesSizeMismatchError, AbiEncodingLengthMismatchError, AbiErrorSignatureNotFoundError, AbiEventSignatureEmptyTopicsError, AbiEventSignatureNotFoundError, AbiEventNotFoundError, AbiFunctionNotFoundError, AbiFunctionOutputsNotFoundError, AbiItemAmbiguityError, BytesSizeMismatchError, DecodeLogDataMismatch, DecodeLogTopicsMismatch, InvalidAbiEncodingTypeError, InvalidAbiDecodingTypeError, InvalidArrayError, InvalidDefinitionTypeError; -var init_abi = __esm({ - "node_modules/viem/_esm/errors/abi.js"() { - init_formatAbiItem2(); - init_size(); - init_base(); - AbiConstructorNotFoundError = class extends BaseError2 { - constructor({ docsPath: docsPath6 }) { - super([ - "A constructor was not found on the ABI.", - "Make sure you are using the correct ABI and that the constructor exists on it." - ].join("\n"), { - docsPath: docsPath6, - name: "AbiConstructorNotFoundError" - }); + function absCeil(number) { + if (number < 0) { + return Math.floor(number); + } else { + return Math.ceil(number); + } } - }; - AbiConstructorParamsNotFoundError = class extends BaseError2 { - constructor({ docsPath: docsPath6 }) { - super([ - "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.", - "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists." - ].join("\n"), { - docsPath: docsPath6, - name: "AbiConstructorParamsNotFoundError" - }); + function bubble() { + var milliseconds2 = this._milliseconds, days2 = this._days, months2 = this._months, data = this._data, seconds2, minutes2, hours2, years2, monthsFromDays; + if (!(milliseconds2 >= 0 && days2 >= 0 && months2 >= 0 || milliseconds2 <= 0 && days2 <= 0 && months2 <= 0)) { + milliseconds2 += absCeil(monthsToDays(months2) + days2) * 864e5; + days2 = 0; + months2 = 0; + } + data.milliseconds = milliseconds2 % 1e3; + seconds2 = absFloor(milliseconds2 / 1e3); + data.seconds = seconds2 % 60; + minutes2 = absFloor(seconds2 / 60); + data.minutes = minutes2 % 60; + hours2 = absFloor(minutes2 / 60); + data.hours = hours2 % 24; + days2 += absFloor(hours2 / 24); + monthsFromDays = absFloor(daysToMonths(days2)); + months2 += monthsFromDays; + days2 -= absCeil(monthsToDays(monthsFromDays)); + years2 = absFloor(months2 / 12); + months2 %= 12; + data.days = days2; + data.months = months2; + data.years = years2; + return this; } - }; - AbiDecodingDataSizeTooSmallError = class extends BaseError2 { - constructor({ data, params, size: size5 }) { - super([`Data size of ${size5} bytes is too small for given parameters.`].join("\n"), { - metaMessages: [ - `Params: (${formatAbiParams(params, { includeName: true })})`, - `Data: ${data} (${size5} bytes)` - ], - name: "AbiDecodingDataSizeTooSmallError" - }); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "params", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "size", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.data = data; - this.params = params; - this.size = size5; + function daysToMonths(days2) { + return days2 * 4800 / 146097; + } + function monthsToDays(months2) { + return months2 * 146097 / 4800; + } + function as2(units) { + if (!this.isValid()) { + return NaN; + } + var days2, months2, milliseconds2 = this._milliseconds; + units = normalizeUnits(units); + if (units === "month" || units === "quarter" || units === "year") { + days2 = this._days + milliseconds2 / 864e5; + months2 = this._months + daysToMonths(days2); + switch (units) { + case "month": + return months2; + case "quarter": + return months2 / 3; + case "year": + return months2 / 12; + } + } else { + days2 = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case "week": + return days2 / 7 + milliseconds2 / 6048e5; + case "day": + return days2 + milliseconds2 / 864e5; + case "hour": + return days2 * 24 + milliseconds2 / 36e5; + case "minute": + return days2 * 1440 + milliseconds2 / 6e4; + case "second": + return days2 * 86400 + milliseconds2 / 1e3; + // Math.floor prevents floating point math errors here + case "millisecond": + return Math.floor(days2 * 864e5) + milliseconds2; + default: + throw new Error("Unknown unit " + units); + } + } + } + function makeAs(alias) { + return function() { + return this.as(alias); + }; + } + var asMilliseconds = makeAs("ms"), asSeconds = makeAs("s"), asMinutes = makeAs("m"), asHours = makeAs("h"), asDays = makeAs("d"), asWeeks = makeAs("w"), asMonths = makeAs("M"), asQuarters = makeAs("Q"), asYears = makeAs("y"), valueOf$1 = asMilliseconds; + function clone$1() { + return createDuration(this); + } + function get$2(units) { + units = normalizeUnits(units); + return this.isValid() ? this[units + "s"]() : NaN; + } + function makeGetter(name) { + return function() { + return this.isValid() ? this._data[name] : NaN; + }; + } + var milliseconds = makeGetter("milliseconds"), seconds = makeGetter("seconds"), minutes = makeGetter("minutes"), hours = makeGetter("hours"), days = makeGetter("days"), months = makeGetter("months"), years = makeGetter("years"); + function weeks() { + return absFloor(this.days() / 7); + } + var round = Math.round, thresholds = { + ss: 44, + // a few seconds to seconds + s: 45, + // seconds to minute + m: 45, + // minutes to hour + h: 22, + // hours to day + d: 26, + // days to month/week + w: null, + // weeks to month + M: 11 + // months to year + }; + function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale2) { + return locale2.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } - }; - AbiDecodingZeroDataError = class extends BaseError2 { - constructor() { - super('Cannot decode zero data ("0x") with ABI parameters.', { - name: "AbiDecodingZeroDataError" - }); + function relativeTime$1(posNegDuration, withoutSuffix, thresholds2, locale2) { + var duration = createDuration(posNegDuration).abs(), seconds2 = round(duration.as("s")), minutes2 = round(duration.as("m")), hours2 = round(duration.as("h")), days2 = round(duration.as("d")), months2 = round(duration.as("M")), weeks2 = round(duration.as("w")), years2 = round(duration.as("y")), a = seconds2 <= thresholds2.ss && ["s", seconds2] || seconds2 < thresholds2.s && ["ss", seconds2] || minutes2 <= 1 && ["m"] || minutes2 < thresholds2.m && ["mm", minutes2] || hours2 <= 1 && ["h"] || hours2 < thresholds2.h && ["hh", hours2] || days2 <= 1 && ["d"] || days2 < thresholds2.d && ["dd", days2]; + if (thresholds2.w != null) { + a = a || weeks2 <= 1 && ["w"] || weeks2 < thresholds2.w && ["ww", weeks2]; + } + a = a || months2 <= 1 && ["M"] || months2 < thresholds2.M && ["MM", months2] || years2 <= 1 && ["y"] || ["yy", years2]; + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale2; + return substituteTimeAgo.apply(null, a); } - }; - AbiEncodingArrayLengthMismatchError = class extends BaseError2 { - constructor({ expectedLength, givenLength, type }) { - super([ - `ABI encoding array length mismatch for type ${type}.`, - `Expected length: ${expectedLength}`, - `Given length: ${givenLength}` - ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" }); + function getSetRelativeTimeRounding(roundingFunction) { + if (roundingFunction === void 0) { + return round; + } + if (typeof roundingFunction === "function") { + round = roundingFunction; + return true; + } + return false; } - }; - AbiEncodingBytesSizeMismatchError = class extends BaseError2 { - constructor({ expectedSize, value }) { - super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); + function getSetRelativeTimeThreshold(threshold, limit) { + if (thresholds[threshold] === void 0) { + return false; + } + if (limit === void 0) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + if (threshold === "s") { + thresholds.ss = limit - 1; + } + return true; } - }; - AbiEncodingLengthMismatchError = class extends BaseError2 { - constructor({ expectedLength, givenLength }) { - super([ - "ABI encoding params/values length mismatch.", - `Expected length (params): ${expectedLength}`, - `Given length (values): ${givenLength}` - ].join("\n"), { name: "AbiEncodingLengthMismatchError" }); + function humanize(argWithSuffix, argThresholds) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + var withSuffix = false, th = thresholds, locale2, output; + if (typeof argWithSuffix === "object") { + argThresholds = argWithSuffix; + argWithSuffix = false; + } + if (typeof argWithSuffix === "boolean") { + withSuffix = argWithSuffix; + } + if (typeof argThresholds === "object") { + th = Object.assign({}, thresholds, argThresholds); + if (argThresholds.s != null && argThresholds.ss == null) { + th.ss = argThresholds.s - 1; + } + } + locale2 = this.localeData(); + output = relativeTime$1(this, !withSuffix, th, locale2); + if (withSuffix) { + output = locale2.pastFuture(+this, output); + } + return locale2.postformat(output); } - }; - AbiErrorSignatureNotFoundError = class extends BaseError2 { - constructor(signature, { docsPath: docsPath6 }) { - super([ - `Encoded error signature "${signature}" not found on ABI.`, - "Make sure you are using the correct ABI and that the error exists on it.", - `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.` - ].join("\n"), { - docsPath: docsPath6, - name: "AbiErrorSignatureNotFoundError" - }); - Object.defineProperty(this, "signature", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.signature = signature; + var abs$1 = Math.abs; + function sign2(x2) { + return (x2 > 0) - (x2 < 0) || +x2; } - }; - AbiEventSignatureEmptyTopicsError = class extends BaseError2 { - constructor({ docsPath: docsPath6 }) { - super("Cannot extract event signature from empty topics.", { - docsPath: docsPath6, - name: "AbiEventSignatureEmptyTopicsError" - }); + function toISOString$1() { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + var seconds2 = abs$1(this._milliseconds) / 1e3, days2 = abs$1(this._days), months2 = abs$1(this._months), minutes2, hours2, years2, s, total = this.asSeconds(), totalSign, ymSign, daysSign, hmsSign; + if (!total) { + return "P0D"; + } + minutes2 = absFloor(seconds2 / 60); + hours2 = absFloor(minutes2 / 60); + seconds2 %= 60; + minutes2 %= 60; + years2 = absFloor(months2 / 12); + months2 %= 12; + s = seconds2 ? seconds2.toFixed(3).replace(/\.?0+$/, "") : ""; + totalSign = total < 0 ? "-" : ""; + ymSign = sign2(this._months) !== sign2(total) ? "-" : ""; + daysSign = sign2(this._days) !== sign2(total) ? "-" : ""; + hmsSign = sign2(this._milliseconds) !== sign2(total) ? "-" : ""; + return totalSign + "P" + (years2 ? ymSign + years2 + "Y" : "") + (months2 ? ymSign + months2 + "M" : "") + (days2 ? daysSign + days2 + "D" : "") + (hours2 || minutes2 || seconds2 ? "T" : "") + (hours2 ? hmsSign + hours2 + "H" : "") + (minutes2 ? hmsSign + minutes2 + "M" : "") + (seconds2 ? hmsSign + s + "S" : ""); } - }; - AbiEventSignatureNotFoundError = class extends BaseError2 { - constructor(signature, { docsPath: docsPath6 }) { - super([ - `Encoded event signature "${signature}" not found on ABI.`, - "Make sure you are using the correct ABI and that the event exists on it.", - `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.` - ].join("\n"), { - docsPath: docsPath6, - name: "AbiEventSignatureNotFoundError" - }); + var proto$2 = Duration.prototype; + proto$2.isValid = isValid$1; + proto$2.abs = abs; + proto$2.add = add$1; + proto$2.subtract = subtract$1; + proto$2.as = as2; + proto$2.asMilliseconds = asMilliseconds; + proto$2.asSeconds = asSeconds; + proto$2.asMinutes = asMinutes; + proto$2.asHours = asHours; + proto$2.asDays = asDays; + proto$2.asWeeks = asWeeks; + proto$2.asMonths = asMonths; + proto$2.asQuarters = asQuarters; + proto$2.asYears = asYears; + proto$2.valueOf = valueOf$1; + proto$2._bubble = bubble; + proto$2.clone = clone$1; + proto$2.get = get$2; + proto$2.milliseconds = milliseconds; + proto$2.seconds = seconds; + proto$2.minutes = minutes; + proto$2.hours = hours; + proto$2.days = days; + proto$2.weeks = weeks; + proto$2.months = months; + proto$2.years = years; + proto$2.humanize = humanize; + proto$2.toISOString = toISOString$1; + proto$2.toString = toISOString$1; + proto$2.toJSON = toISOString$1; + proto$2.locale = locale; + proto$2.localeData = localeData; + proto$2.toIsoString = deprecate( + "toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)", + toISOString$1 + ); + proto$2.lang = lang; + addFormatToken("X", 0, 0, "unix"); + addFormatToken("x", 0, 0, "valueOf"); + addRegexToken("x", matchSigned); + addRegexToken("X", matchTimestamp); + addParseToken("X", function(input, array, config3) { + config3._d = new Date(parseFloat(input) * 1e3); + }); + addParseToken("x", function(input, array, config3) { + config3._d = new Date(toInt(input)); + }); + hooks.version = "2.30.1"; + setHookCallback(createLocal); + hooks.fn = proto; + hooks.min = min; + hooks.max = max; + hooks.now = now; + hooks.utc = createUTC; + hooks.unix = createUnix; + hooks.months = listMonths; + hooks.isDate = isDate2; + hooks.locale = getSetGlobalLocale; + hooks.invalid = createInvalid; + hooks.duration = createDuration; + hooks.isMoment = isMoment; + hooks.weekdays = listWeekdays; + hooks.parseZone = createInZone; + hooks.localeData = getLocale; + hooks.isDuration = isDuration; + hooks.monthsShort = listMonthsShort; + hooks.weekdaysMin = listWeekdaysMin; + hooks.defineLocale = defineLocale; + hooks.updateLocale = updateLocale; + hooks.locales = listLocales; + hooks.weekdaysShort = listWeekdaysShort; + hooks.normalizeUnits = normalizeUnits; + hooks.relativeTimeRounding = getSetRelativeTimeRounding; + hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; + hooks.calendarFormat = getCalendarFormat; + hooks.prototype = proto; + hooks.HTML5_FMT = { + DATETIME_LOCAL: "YYYY-MM-DDTHH:mm", + // + DATETIME_LOCAL_SECONDS: "YYYY-MM-DDTHH:mm:ss", + // + DATETIME_LOCAL_MS: "YYYY-MM-DDTHH:mm:ss.SSS", + // + DATE: "YYYY-MM-DD", + // + TIME: "HH:mm", + // + TIME_SECONDS: "HH:mm:ss", + // + TIME_MS: "HH:mm:ss.SSS", + // + WEEK: "GGGG-[W]WW", + // + MONTH: "YYYY-MM" + // + }; + return hooks; + }); + } +}); + +// node_modules/file-stream-rotator/FileStreamRotator.js +var require_FileStreamRotator = __commonJS({ + "node_modules/file-stream-rotator/FileStreamRotator.js"(exports2, module2) { + "use strict"; + var fs2 = __require("fs"); + var path = __require("path"); + var moment = require_moment(); + var crypto4 = __require("crypto"); + var EventEmitter3 = __require("events"); + var FileStreamRotator = {}; + module2.exports = FileStreamRotator; + var staticFrequency = ["daily", "test", "m", "h", "custom"]; + var DATE_FORMAT = "YYYYMMDDHHmm"; + var _checkNumAndType = function(type, num2) { + if (typeof num2 == "number") { + switch (type) { + case "m": + if (num2 < 0 || num2 > 60) { + return false; + } + break; + case "h": + if (num2 < 0 || num2 > 24) { + return false; + } + break; + } + return { type, digit: num2 }; } }; - AbiEventNotFoundError = class extends BaseError2 { - constructor(eventName, { docsPath: docsPath6 } = {}) { - super([ - `Event ${eventName ? `"${eventName}" ` : ""}not found on ABI.`, - "Make sure you are using the correct ABI and that the event exists on it." - ].join("\n"), { - docsPath: docsPath6, - name: "AbiEventNotFoundError" - }); + var _checkDailyAndTest = function(freqType) { + switch (freqType) { + case "custom": + case "daily": + return { type: freqType, digit: void 0 }; + break; + case "test": + return { type: freqType, digit: 0 }; } + return false; }; - AbiFunctionNotFoundError = class extends BaseError2 { - constructor(functionName, { docsPath: docsPath6 } = {}) { - super([ - `Function ${functionName ? `"${functionName}" ` : ""}not found on ABI.`, - "Make sure you are using the correct ABI and that the function exists on it." - ].join("\n"), { - docsPath: docsPath6, - name: "AbiFunctionNotFoundError" - }); + FileStreamRotator.getFrequency = function(frequency) { + var _f = frequency.toLowerCase().match(/^(\d+)([mh])$/); + if (_f) { + return _checkNumAndType(_f[2], parseInt(_f[1])); } - }; - AbiFunctionOutputsNotFoundError = class extends BaseError2 { - constructor(functionName, { docsPath: docsPath6 }) { - super([ - `Function "${functionName}" does not contain any \`outputs\` on ABI.`, - "Cannot decode function result without knowing what the parameter types are.", - "Make sure you are using the correct ABI and that the function exists on it." - ].join("\n"), { - docsPath: docsPath6, - name: "AbiFunctionOutputsNotFoundError" - }); + var dailyOrTest = _checkDailyAndTest(frequency); + if (dailyOrTest) { + return dailyOrTest; } + return false; }; - AbiItemAmbiguityError = class extends BaseError2 { - constructor(x2, y2) { - super("Found ambiguous types in overloaded ABI items.", { - metaMessages: [ - `\`${x2.type}\` in \`${formatAbiItem2(x2.abiItem)}\`, and`, - `\`${y2.type}\` in \`${formatAbiItem2(y2.abiItem)}\``, - "", - "These types encode differently and cannot be distinguished at runtime.", - "Remove one of the ambiguous items in the ABI." - ], - name: "AbiItemAmbiguityError" - }); + FileStreamRotator.parseFileSize = function(size5) { + if (size5 && typeof size5 == "string") { + var _s2 = size5.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/); + if (_s2) { + switch (_s2[2]) { + case "k": + return _s2[1] * 1024; + case "m": + return _s2[1] * 1024 * 1024; + case "g": + return _s2[1] * 1024 * 1024 * 1024; + } + } } + return null; }; - BytesSizeMismatchError = class extends BaseError2 { - constructor({ expectedSize, givenSize }) { - super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, { - name: "BytesSizeMismatchError" - }); + FileStreamRotator.getDate = function(format, date_format, utc) { + date_format = date_format || DATE_FORMAT; + let currentMoment = utc ? moment.utc() : moment().local(); + if (format && staticFrequency.indexOf(format.type) !== -1) { + switch (format.type) { + case "m": + var minute = Math.floor(currentMoment.minutes() / format.digit) * format.digit; + return currentMoment.minutes(minute).format(date_format); + break; + case "h": + var hour = Math.floor(currentMoment.hour() / format.digit) * format.digit; + return currentMoment.hour(hour).format(date_format); + break; + case "daily": + case "custom": + case "test": + return currentMoment.format(date_format); + } } + return currentMoment.format(date_format); }; - DecodeLogDataMismatch = class extends BaseError2 { - constructor({ abiItem, data, params, size: size5 }) { - super([ - `Data size of ${size5} bytes is too small for non-indexed event parameters.` - ].join("\n"), { - metaMessages: [ - `Params: (${formatAbiParams(params, { includeName: true })})`, - `Data: ${data} (${size5} bytes)` - ], - name: "DecodeLogDataMismatch" - }); - Object.defineProperty(this, "abiItem", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "params", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "size", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.abiItem = abiItem; - this.data = data; - this.params = params; - this.size = size5; + FileStreamRotator.setAuditLog = function(max_logs, audit_file, log_file) { + var _rtn = null; + if (max_logs) { + var use_days = max_logs.toString().substr(-1); + var _num = max_logs.toString().match(/^(\d+)/); + if (Number(_num[1]) > 0) { + var baseLog = path.dirname(log_file.replace(/%DATE%.+/, "_filename")); + try { + if (audit_file) { + var full_path = path.resolve(audit_file); + _rtn = JSON.parse(fs2.readFileSync(full_path, { encoding: "utf-8" })); + } else { + var full_path = path.resolve(baseLog + "/.audit.json"); + _rtn = JSON.parse(fs2.readFileSync(full_path, { encoding: "utf-8" })); + } + } catch (e) { + if (e.code !== "ENOENT") { + return null; + } + _rtn = { + keep: { + days: false, + amount: Number(_num[1]) + }, + auditLog: audit_file || baseLog + "/.audit.json", + files: [] + }; + } + _rtn.keep = { + days: use_days === "d", + amount: Number(_num[1]) + }; + } } + return _rtn; }; - DecodeLogTopicsMismatch = class extends BaseError2 { - constructor({ abiItem, param }) { - super([ - `Expected a topic for indexed event parameter${param.name ? ` "${param.name}"` : ""} on event "${formatAbiItem2(abiItem, { includeName: true })}".` - ].join("\n"), { name: "DecodeLogTopicsMismatch" }); - Object.defineProperty(this, "abiItem", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.abiItem = abiItem; + FileStreamRotator.writeAuditLog = function(audit, verbose) { + try { + mkDirForFile(audit.auditLog); + fs2.writeFileSync(audit.auditLog, JSON.stringify(audit, null, 4)); + } catch (e) { + if (verbose) { + console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] Failed to store log audit at:", audit.auditLog, "Error:", e); + } } }; - InvalidAbiEncodingTypeError = class extends BaseError2 { - constructor(type, { docsPath: docsPath6 }) { - super([ - `Type "${type}" is not a valid encoding type.`, - "Please provide a valid ABI type." - ].join("\n"), { docsPath: docsPath6, name: "InvalidAbiEncodingType" }); + function removeFile(file, verbose) { + if (file.hash === crypto4.createHash(file.hashType).update(file.name + "LOG_FILE" + file.date).digest("hex")) { + try { + if (fs2.existsSync(file.name)) { + fs2.unlinkSync(file.name); + } + } catch (e) { + if (verbose) { + console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] Could not remove old log file: ", file.name); + } + } } - }; - InvalidAbiDecodingTypeError = class extends BaseError2 { - constructor(type, { docsPath: docsPath6 }) { - super([ - `Type "${type}" is not a valid decoding type.`, - "Please provide a valid ABI type." - ].join("\n"), { docsPath: docsPath6, name: "InvalidAbiDecodingType" }); + } + function createCurrentSymLink(logfile, name, verbose) { + let symLinkName = name || "current.log"; + let logPath = path.dirname(logfile); + let logfileName = path.basename(logfile); + let current = logPath + "/" + symLinkName; + try { + let stats = fs2.lstatSync(current); + if (stats.isSymbolicLink()) { + fs2.unlinkSync(current); + fs2.symlinkSync(logfileName, current); + } + } catch (err) { + if (err && err.code == "ENOENT") { + try { + fs2.symlinkSync(logfileName, current); + } catch (e) { + if (verbose) { + console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] Could not create symlink file: ", current, " -> ", logfileName); + } + } + } + } + } + function createLogWatcher(logfile, verbose, cb) { + if (!logfile) return null; + try { + let stats = fs2.lstatSync(logfile); + return fs2.watch(logfile, function(event, filename) { + if (event == "rename") { + try { + let stats2 = fs2.lstatSync(logfile); + } catch (err) { + cb(err, logfile); + } + } + }); + } catch (err) { + if (verbose) { + console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Could not add watcher for " + logfile); + } } - }; - InvalidArrayError = class extends BaseError2 { - constructor(value) { - super([`Value "${value}" is not a valid array.`].join("\n"), { - name: "InvalidArrayError" + } + FileStreamRotator.addLogToAudit = function(logfile, audit, stream4, verbose) { + if (audit && audit.files) { + var index2 = audit.files.findIndex(function(file) { + return file.name === logfile; + }); + if (index2 !== -1) { + return audit; + } + var time = Date.now(); + audit.files.push({ + date: time, + name: logfile, + hash: crypto4.createHash(audit.hashType).update(logfile + "LOG_FILE" + time).digest("hex") }); + if (audit.keep.days) { + var oldestDate = moment().subtract(audit.keep.amount, "days").valueOf(); + var recentFiles = audit.files.filter(function(file) { + if (file.date > oldestDate) { + return true; + } + file.hashType = audit.hashType; + removeFile(file, verbose); + stream4.emit("logRemoved", file); + return false; + }); + audit.files = recentFiles; + } else { + var filesToKeep = audit.files.splice(-audit.keep.amount); + if (audit.files.length > 0) { + audit.files.filter(function(file) { + file.hashType = audit.hashType; + removeFile(file, verbose); + stream4.emit("logRemoved", file); + return false; + }); + } + audit.files = filesToKeep; + } + FileStreamRotator.writeAuditLog(audit, verbose); } + return audit; }; - InvalidDefinitionTypeError = class extends BaseError2 { - constructor(type) { - super([ - `"${type}" is not a valid definition type.`, - 'Valid types: "function", "event", "error"' - ].join("\n"), { name: "InvalidDefinitionTypeError" }); + FileStreamRotator.getStream = function(options) { + var frequencyMetaData = null; + var curDate = null; + var self2 = this; + if (!options.filename) { + console.error(/* @__PURE__ */ new Date(), "[FileStreamRotator] No filename supplied. Defaulting to STDOUT"); + return process.stdout; } - }; - } -}); - -// node_modules/viem/_esm/errors/data.js -var SliceOffsetOutOfBoundsError, SizeExceedsPaddingSizeError, InvalidBytesLengthError; -var init_data = __esm({ - "node_modules/viem/_esm/errors/data.js"() { - init_base(); - SliceOffsetOutOfBoundsError = class extends BaseError2 { - constructor({ offset, position, size: size5 }) { - super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size5}).`, { name: "SliceOffsetOutOfBoundsError" }); + if (options.frequency) { + frequencyMetaData = self2.getFrequency(options.frequency); } - }; - SizeExceedsPaddingSizeError = class extends BaseError2 { - constructor({ size: size5, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size5}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); + let auditLog = self2.setAuditLog(options.max_logs, options.audit_file, options.filename); + if (auditLog != null) { + auditLog.hashType = options.audit_hash_type !== void 0 ? options.audit_hash_type : "md5"; } - }; - InvalidBytesLengthError = class extends BaseError2 { - constructor({ size: size5, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size5} ${type} long.`, { name: "InvalidBytesLengthError" }); + self2.verbose = options.verbose !== void 0 ? options.verbose : true; + var fileSize = null; + var fileCount = 0; + var curSize = 0; + if (options.size) { + fileSize = FileStreamRotator.parseFileSize(options.size); } - }; - } -}); - -// node_modules/viem/_esm/utils/data/pad.js -function pad(hexOrBytes, { dir, size: size5 = 32 } = {}) { - if (typeof hexOrBytes === "string") - return padHex(hexOrBytes, { dir, size: size5 }); - return padBytes(hexOrBytes, { dir, size: size5 }); -} -function padHex(hex_, { dir, size: size5 = 32 } = {}) { - if (size5 === null) - return hex_; - const hex = hex_.replace("0x", ""); - if (hex.length > size5 * 2) - throw new SizeExceedsPaddingSizeError({ - size: Math.ceil(hex.length / 2), - targetSize: size5, - type: "hex" - }); - return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`; -} -function padBytes(bytes, { dir, size: size5 = 32 } = {}) { - if (size5 === null) - return bytes; - if (bytes.length > size5) - throw new SizeExceedsPaddingSizeError({ - size: bytes.length, - targetSize: size5, - type: "bytes" - }); - const paddedBytes = new Uint8Array(size5); - for (let i = 0; i < size5; i++) { - const padEnd = dir === "right"; - paddedBytes[padEnd ? i : size5 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; - } - return paddedBytes; -} -var init_pad = __esm({ - "node_modules/viem/_esm/utils/data/pad.js"() { - init_data(); - } -}); - -// node_modules/viem/_esm/errors/encoding.js -var IntegerOutOfRangeError, InvalidBytesBooleanError, InvalidHexBooleanError, SizeOverflowError; -var init_encoding = __esm({ - "node_modules/viem/_esm/errors/encoding.js"() { - init_base(); - IntegerOutOfRangeError = class extends BaseError2 { - constructor({ max, min, signed, size: size5, value }) { - super(`Number "${value}" is not in safe ${size5 ? `${size5 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" }); + var dateFormat = options.date_format || DATE_FORMAT; + if (frequencyMetaData && frequencyMetaData.type == "daily") { + if (!options.date_format) { + dateFormat = "YYYY-MM-DD"; + } + if (moment().format(dateFormat) != moment().endOf("day").format(dateFormat) || moment().format(dateFormat) == moment().add(1, "day").format(dateFormat)) { + if (self2.verbose) { + console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Changing type to custom as date format changes more often than once a day or not every day"); + } + frequencyMetaData.type = "custom"; + } } - }; - InvalidBytesBooleanError = class extends BaseError2 { - constructor(bytes) { - super(`Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, { - name: "InvalidBytesBooleanError" - }); + if (frequencyMetaData) { + curDate = options.frequency ? self2.getDate(frequencyMetaData, dateFormat, options.utc) : ""; } - }; - InvalidHexBooleanError = class extends BaseError2 { - constructor(hex) { - super(`Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`, { name: "InvalidHexBooleanError" }); + options.create_symlink = options.create_symlink || false; + options.extension = options.extension || ""; + var filename = options.filename; + var oldFile = null; + var logfile = filename + (curDate ? "." + curDate : ""); + if (filename.match(/%DATE%/)) { + logfile = filename.replace(/%DATE%/g, curDate ? curDate : self2.getDate(null, dateFormat, options.utc)); } - }; - SizeOverflowError = class extends BaseError2 { - constructor({ givenSize, maxSize }) { - super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" }); + if (fileSize) { + var lastLogFile = null; + var t_log = logfile; + var f = null; + if (auditLog && auditLog.files && auditLog.files instanceof Array && auditLog.files.length > 0) { + var lastEntry = auditLog.files[auditLog.files.length - 1].name; + if (lastEntry.match(t_log)) { + var lastCount = lastEntry.match(t_log + "\\.(\\d+)"); + if (lastCount) { + t_log = lastEntry; + fileCount = lastCount[1]; + } + } + } + if (fileCount == 0 && t_log == logfile) { + t_log += options.extension; + } + while (f = fs2.existsSync(t_log)) { + lastLogFile = t_log; + fileCount++; + t_log = logfile + "." + fileCount + options.extension; + } + if (lastLogFile) { + var lastLogFileStats = fs2.statSync(lastLogFile); + if (lastLogFileStats.size < fileSize) { + t_log = lastLogFile; + fileCount--; + curSize = lastLogFileStats.size; + } + } + logfile = t_log; + } else { + logfile += options.extension; + } + if (self2.verbose) { + console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Logging to: ", logfile); + } + mkDirForFile(logfile); + var file_options = options.file_options || { flags: "a" }; + var rotateStream = fs2.createWriteStream(logfile, file_options); + if (curDate && frequencyMetaData && staticFrequency.indexOf(frequencyMetaData.type) > -1 || fileSize > 0) { + if (self2.verbose) { + console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] Rotating file: ", frequencyMetaData ? frequencyMetaData.type : "", fileSize ? "size: " + fileSize : ""); + } + var stream4 = new EventEmitter3(); + stream4.auditLog = auditLog; + stream4.end = function() { + rotateStream.end.apply(rotateStream, arguments); + }; + BubbleEvents(rotateStream, stream4); + stream4.on("close", function() { + if (logWatcher) { + logWatcher.close(); + } + }); + stream4.on("new", function(newLog) { + stream4.auditLog = self2.addLogToAudit(newLog, stream4.auditLog, stream4, self2.verbose); + if (options.create_symlink) { + createCurrentSymLink(newLog, options.symlink_name, self2.verbose); + } + if (options.watch_log) { + stream4.emit("addWatcher", newLog); + } + }); + var logWatcher; + stream4.on("addWatcher", function(newLog) { + if (logWatcher) { + logWatcher.close(); + } + if (!options.watch_log) { + return; + } + logWatcher = createLogWatcher(newLog, self2.verbose, function(err, newLog2) { + stream4.emit("createLog", newLog2); + }); + }); + stream4.on("createLog", function(file) { + try { + let stats = fs2.lstatSync(file); + } catch (err) { + if (rotateStream && rotateStream.end == "function") { + rotateStream.end(); + } + rotateStream = fs2.createWriteStream(file, file_options); + stream4.emit("new", file); + BubbleEvents(rotateStream, stream4); + } + }); + stream4.write = function(str, encoding) { + var newDate = frequencyMetaData ? this.getDate(frequencyMetaData, dateFormat, options.utc) : curDate; + if (newDate != curDate || fileSize && curSize > fileSize) { + var newLogfile = filename + (curDate && frequencyMetaData ? "." + newDate : ""); + if (filename.match(/%DATE%/) && curDate) { + newLogfile = filename.replace(/%DATE%/g, newDate); + } + if (fileSize && curSize > fileSize) { + fileCount++; + newLogfile += "." + fileCount + options.extension; + } else { + fileCount = 0; + newLogfile += options.extension; + } + curSize = 0; + if (self2.verbose) { + console.log(/* @__PURE__ */ new Date(), __require("util").format("[FileStreamRotator] Changing logs from %s to %s", logfile, newLogfile)); + } + curDate = newDate; + oldFile = logfile; + logfile = newLogfile; + if (options.end_stream === true) { + rotateStream.end(); + } else { + rotateStream.destroy(); + } + mkDirForFile(logfile); + rotateStream = fs2.createWriteStream(newLogfile, file_options); + stream4.emit("new", newLogfile); + stream4.emit("rotate", oldFile, newLogfile); + BubbleEvents(rotateStream, stream4); + } + rotateStream.write(str, encoding); + curSize += Buffer.byteLength(str, encoding); + }.bind(this); + process.nextTick(function() { + stream4.emit("new", logfile); + }); + stream4.emit("new", logfile); + return stream4; + } else { + if (self2.verbose) { + console.log(/* @__PURE__ */ new Date(), "[FileStreamRotator] File won't be rotated: ", options.frequency, options.size); + } + process.nextTick(function() { + rotateStream.emit("new", logfile); + }); + return rotateStream; } }; + var mkDirForFile = function(pathWithFile) { + var _path = path.dirname(pathWithFile); + _path.split(path.sep).reduce( + function(fullPath, folder) { + fullPath += folder + path.sep; + if (!fs2.existsSync(fullPath)) { + try { + fs2.mkdirSync(fullPath); + } catch (e) { + if (e.code !== "EEXIST") { + throw e; + } + } + } + return fullPath; + }, + "" + ); + }; + var BubbleEvents = function BubbleEvents2(emitter, proxy) { + emitter.on("close", function() { + proxy.emit("close"); + }); + emitter.on("finish", function() { + proxy.emit("finish"); + }); + emitter.on("error", function(err) { + proxy.emit("error", err); + }); + emitter.on("open", function(fd2) { + proxy.emit("open", fd2); + }); + }; } }); -// node_modules/viem/_esm/utils/data/trim.js -function trim2(hexOrBytes, { dir = "left" } = {}) { - let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes; - let sliceLength = 0; - for (let i = 0; i < data.length - 1; i++) { - if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") - sliceLength++; - else - break; - } - data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); - if (typeof hexOrBytes === "string") { - if (data.length === 1 && dir === "right") - data = `${data}0`; - return `0x${data.length % 2 === 1 ? `0${data}` : data}`; - } - return data; -} -var init_trim = __esm({ - "node_modules/viem/_esm/utils/data/trim.js"() { - } -}); - -// node_modules/viem/_esm/utils/encoding/fromHex.js -function assertSize(hexOrBytes, { size: size5 }) { - if (size(hexOrBytes) > size5) - throw new SizeOverflowError({ - givenSize: size(hexOrBytes), - maxSize: size5 - }); -} -function hexToBigInt(hex, opts = {}) { - const { signed } = opts; - if (opts.size) - assertSize(hex, { size: opts.size }); - const value = BigInt(hex); - if (!signed) - return value; - const size5 = (hex.length - 2) / 2; - const max = (1n << BigInt(size5) * 8n - 1n) - 1n; - if (value <= max) - return value; - return value - BigInt(`0x${"f".padStart(size5 * 2, "f")}`) - 1n; -} -function hexToBool(hex_, opts = {}) { - let hex = hex_; - if (opts.size) { - assertSize(hex, { size: opts.size }); - hex = trim2(hex); - } - if (trim2(hex) === "0x00") - return false; - if (trim2(hex) === "0x01") - return true; - throw new InvalidHexBooleanError(hex); -} -function hexToNumber(hex, opts = {}) { - return Number(hexToBigInt(hex, opts)); -} -var init_fromHex = __esm({ - "node_modules/viem/_esm/utils/encoding/fromHex.js"() { - init_encoding(); - init_size(); - init_trim(); - } -}); - -// node_modules/viem/_esm/utils/encoding/toHex.js -function toHex(value, opts = {}) { - if (typeof value === "number" || typeof value === "bigint") - return numberToHex(value, opts); - if (typeof value === "string") { - return stringToHex(value, opts); - } - if (typeof value === "boolean") - return boolToHex(value, opts); - return bytesToHex(value, opts); -} -function boolToHex(value, opts = {}) { - const hex = `0x${Number(value)}`; - if (typeof opts.size === "number") { - assertSize(hex, { size: opts.size }); - return pad(hex, { size: opts.size }); - } - return hex; -} -function bytesToHex(value, opts = {}) { - let string = ""; - for (let i = 0; i < value.length; i++) { - string += hexes[value[i]]; - } - const hex = `0x${string}`; - if (typeof opts.size === "number") { - assertSize(hex, { size: opts.size }); - return pad(hex, { dir: "right", size: opts.size }); - } - return hex; -} -function numberToHex(value_, opts = {}) { - const { signed, size: size5 } = opts; - const value = BigInt(value_); - let maxValue; - if (size5) { - if (signed) - maxValue = (1n << BigInt(size5) * 8n - 1n) - 1n; - else - maxValue = 2n ** (BigInt(size5) * 8n) - 1n; - } else if (typeof value_ === "number") { - maxValue = BigInt(Number.MAX_SAFE_INTEGER); - } - const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0; - if (maxValue && value > maxValue || value < minValue) { - const suffix = typeof value_ === "bigint" ? "n" : ""; - throw new IntegerOutOfRangeError({ - max: maxValue ? `${maxValue}${suffix}` : void 0, - min: `${minValue}${suffix}`, - signed, - size: size5, - value: `${value_}${suffix}` - }); - } - const hex = `0x${(signed && value < 0 ? (1n << BigInt(size5 * 8)) + BigInt(value) : value).toString(16)}`; - if (size5) - return pad(hex, { size: size5 }); - return hex; -} -function stringToHex(value_, opts = {}) { - const value = encoder.encode(value_); - return bytesToHex(value, opts); -} -var hexes, encoder; -var init_toHex = __esm({ - "node_modules/viem/_esm/utils/encoding/toHex.js"() { - init_encoding(); - init_pad(); - init_fromHex(); - hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); - encoder = /* @__PURE__ */ new TextEncoder(); - } -}); - -// node_modules/viem/_esm/utils/encoding/toBytes.js -function toBytes(value, opts = {}) { - if (typeof value === "number" || typeof value === "bigint") - return numberToBytes(value, opts); - if (typeof value === "boolean") - return boolToBytes(value, opts); - if (isHex(value)) - return hexToBytes(value, opts); - return stringToBytes(value, opts); -} -function boolToBytes(value, opts = {}) { - const bytes = new Uint8Array(1); - bytes[0] = Number(value); - if (typeof opts.size === "number") { - assertSize(bytes, { size: opts.size }); - return pad(bytes, { size: opts.size }); - } - return bytes; -} -function charCodeToBase16(char) { - if (char >= charCodeMap.zero && char <= charCodeMap.nine) - return char - charCodeMap.zero; - if (char >= charCodeMap.A && char <= charCodeMap.F) - return char - (charCodeMap.A - 10); - if (char >= charCodeMap.a && char <= charCodeMap.f) - return char - (charCodeMap.a - 10); - return void 0; -} -function hexToBytes(hex_, opts = {}) { - let hex = hex_; - if (opts.size) { - assertSize(hex, { size: opts.size }); - hex = pad(hex, { dir: "right", size: opts.size }); - } - let hexString = hex.slice(2); - if (hexString.length % 2) - hexString = `0${hexString}`; - const length = hexString.length / 2; - const bytes = new Uint8Array(length); - for (let index2 = 0, j2 = 0; index2 < length; index2++) { - const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j2++)); - const nibbleRight = charCodeToBase16(hexString.charCodeAt(j2++)); - if (nibbleLeft === void 0 || nibbleRight === void 0) { - throw new BaseError2(`Invalid byte sequence ("${hexString[j2 - 2]}${hexString[j2 - 1]}" in "${hexString}").`); - } - bytes[index2] = nibbleLeft * 16 + nibbleRight; - } - return bytes; -} -function numberToBytes(value, opts) { - const hex = numberToHex(value, opts); - return hexToBytes(hex); -} -function stringToBytes(value, opts = {}) { - const bytes = encoder2.encode(value); - if (typeof opts.size === "number") { - assertSize(bytes, { size: opts.size }); - return pad(bytes, { dir: "right", size: opts.size }); - } - return bytes; -} -var encoder2, charCodeMap; -var init_toBytes = __esm({ - "node_modules/viem/_esm/utils/encoding/toBytes.js"() { - init_base(); - init_isHex(); - init_pad(); - init_fromHex(); - init_toHex(); - encoder2 = /* @__PURE__ */ new TextEncoder(); - charCodeMap = { - zero: 48, - nine: 57, - A: 65, - F: 70, - a: 97, - f: 102 - }; - } -}); - -// node_modules/viem/node_modules/@noble/hashes/esm/_assert.js -function anumber(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error("positive integer expected, got " + n); -} -function isBytes(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; -} -function abytes(b2, ...lengths) { - if (!isBytes(b2)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b2.length)) - throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b2.length); -} -function ahash(h) { - if (typeof h !== "function" || typeof h.create !== "function") - throw new Error("Hash should be wrapped by utils.wrapConstructor"); - anumber(h.outputLen); - anumber(h.blockLen); -} -function aexists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); -} -function aoutput(out, instance) { - abytes(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error("digestInto() expects output buffer of length at least " + min); - } -} -var init_assert = __esm({ - "node_modules/viem/node_modules/@noble/hashes/esm/_assert.js"() { - } -}); - -// node_modules/viem/node_modules/@noble/hashes/esm/_u64.js -function fromBig(n, le2 = false) { - if (le2) - return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; - return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; -} -function split(lst, le2 = false) { - let Ah = new Uint32Array(lst.length); - let Al2 = new Uint32Array(lst.length); - for (let i = 0; i < lst.length; i++) { - const { h, l } = fromBig(lst[i], le2); - [Ah[i], Al2[i]] = [h, l]; - } - return [Ah, Al2]; -} -var U32_MASK64, _32n, rotlSH, rotlSL, rotlBH, rotlBL; -var init_u64 = __esm({ - "node_modules/viem/node_modules/@noble/hashes/esm/_u64.js"() { - U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); - _32n = /* @__PURE__ */ BigInt(32); - rotlSH = (h, l, s) => h << s | l >>> 32 - s; - rotlSL = (h, l, s) => l << s | h >>> 32 - s; - rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; - rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; - } -}); - -// node_modules/viem/node_modules/@noble/hashes/esm/cryptoNode.js -import * as nc from "node:crypto"; -var crypto3; -var init_cryptoNode = __esm({ - "node_modules/viem/node_modules/@noble/hashes/esm/cryptoNode.js"() { - crypto3 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0; - } -}); - -// node_modules/viem/node_modules/@noble/hashes/esm/utils.js -function u32(arr) { - return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -} -function createView(arr) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -} -function rotr(word, shift) { - return word << 32 - shift | word >>> shift; -} -function byteSwap(word) { - return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; -} -function byteSwap32(arr) { - for (let i = 0; i < arr.length; i++) { - arr[i] = byteSwap(arr[i]); - } -} -function utf8ToBytes(str) { - if (typeof str !== "string") - throw new Error("utf8ToBytes expected string, got " + typeof str); - return new Uint8Array(new TextEncoder().encode(str)); -} -function toBytes2(data) { - if (typeof data === "string") - data = utf8ToBytes(data); - abytes(data); - return data; -} -function concatBytes(...arrays) { - let sum = 0; - for (let i = 0; i < arrays.length; i++) { - const a = arrays[i]; - abytes(a); - sum += a.length; - } - const res = new Uint8Array(sum); - for (let i = 0, pad4 = 0; i < arrays.length; i++) { - const a = arrays[i]; - res.set(a, pad4); - pad4 += a.length; - } - return res; -} -function wrapConstructor(hashCons) { - const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; -} -function wrapXOFConstructorWithOpts(hashCons) { - const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest(); - const tmp = hashCons({}); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = (opts) => hashCons(opts); - return hashC; -} -function randomBytes(bytesLength = 32) { - if (crypto3 && typeof crypto3.getRandomValues === "function") { - return crypto3.getRandomValues(new Uint8Array(bytesLength)); - } - if (crypto3 && typeof crypto3.randomBytes === "function") { - return crypto3.randomBytes(bytesLength); - } - throw new Error("crypto.getRandomValues must be defined"); -} -var isLE, Hash; -var init_utils2 = __esm({ - "node_modules/viem/node_modules/@noble/hashes/esm/utils.js"() { - init_cryptoNode(); - init_assert(); - isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); - Hash = class { - // Safe version that clones internal state - clone() { - return this._cloneInto(); +// node_modules/winston-daily-rotate-file/daily-rotate-file.js +var require_daily_rotate_file = __commonJS({ + "node_modules/winston-daily-rotate-file/daily-rotate-file.js"(exports2, module2) { + var fs2 = __require("fs"); + var os2 = __require("os"); + var path = __require("path"); + var util3 = __require("util"); + var zlib2 = __require("zlib"); + var hash2 = require_object_hash(); + var MESSAGE = require_triple_beam().MESSAGE; + var PassThrough = __require("stream").PassThrough; + var Transport2 = require_winston_transport(); + var loggerDefaults = { + json: false, + colorize: false, + eol: os2.EOL, + logstash: null, + prettyPrint: false, + label: null, + stringify: false, + depth: null, + showLevel: true, + timestamp: () => { + return (/* @__PURE__ */ new Date()).toISOString(); } }; - } -}); - -// node_modules/viem/node_modules/@noble/hashes/esm/sha3.js -function keccakP(s, rounds = 24) { - const B2 = new Uint32Array(5 * 2); - for (let round = 24 - rounds; round < 24; round++) { - for (let x2 = 0; x2 < 10; x2++) - B2[x2] = s[x2] ^ s[x2 + 10] ^ s[x2 + 20] ^ s[x2 + 30] ^ s[x2 + 40]; - for (let x2 = 0; x2 < 10; x2 += 2) { - const idx1 = (x2 + 8) % 10; - const idx0 = (x2 + 2) % 10; - const B0 = B2[idx0]; - const B1 = B2[idx0 + 1]; - const Th = rotlH(B0, B1, 1) ^ B2[idx1]; - const Tl2 = rotlL(B0, B1, 1) ^ B2[idx1 + 1]; - for (let y2 = 0; y2 < 50; y2 += 10) { - s[x2 + y2] ^= Th; - s[x2 + y2 + 1] ^= Tl2; + var DailyRotateFile2 = function(options) { + options = options || {}; + Transport2.call(this, options); + function throwIf(target) { + Array.prototype.slice.call(arguments, 1).forEach((name) => { + if (options[name]) { + throw new Error("Cannot set " + name + " and " + target + " together"); + } + }); } - } - let curH = s[2]; - let curL = s[3]; - for (let t = 0; t < 24; t++) { - const shift = SHA3_ROTL[t]; - const Th = rotlH(curH, curL, shift); - const Tl2 = rotlL(curH, curL, shift); - const PI = SHA3_PI[t]; - curH = s[PI]; - curL = s[PI + 1]; - s[PI] = Th; - s[PI + 1] = Tl2; - } - for (let y2 = 0; y2 < 50; y2 += 10) { - for (let x2 = 0; x2 < 10; x2++) - B2[x2] = s[y2 + x2]; - for (let x2 = 0; x2 < 10; x2++) - s[y2 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10]; - } - s[0] ^= SHA3_IOTA_H[round]; - s[1] ^= SHA3_IOTA_L[round]; - } - B2.fill(0); -} -var SHA3_PI, SHA3_ROTL, _SHA3_IOTA, _0n, _1n, _2n, _7n, _256n, _0x71n, SHA3_IOTA_H, SHA3_IOTA_L, rotlH, rotlL, Keccak, gen, sha3_224, sha3_256, sha3_384, sha3_512, keccak_224, keccak_256, keccak_384, keccak_512, genShake, shake128, shake256; -var init_sha3 = __esm({ - "node_modules/viem/node_modules/@noble/hashes/esm/sha3.js"() { - init_assert(); - init_u64(); - init_utils2(); - SHA3_PI = []; - SHA3_ROTL = []; - _SHA3_IOTA = []; - _0n = /* @__PURE__ */ BigInt(0); - _1n = /* @__PURE__ */ BigInt(1); - _2n = /* @__PURE__ */ BigInt(2); - _7n = /* @__PURE__ */ BigInt(7); - _256n = /* @__PURE__ */ BigInt(256); - _0x71n = /* @__PURE__ */ BigInt(113); - for (let round = 0, R2 = _1n, x2 = 1, y2 = 0; round < 24; round++) { - [x2, y2] = [y2, (2 * x2 + 3 * y2) % 5]; - SHA3_PI.push(2 * (5 * y2 + x2)); - SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); - let t = _0n; - for (let j2 = 0; j2 < 7; j2++) { - R2 = (R2 << _1n ^ (R2 >> _7n) * _0x71n) % _256n; - if (R2 & _2n) - t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j2)) - _1n; + function getMaxSize(size5) { + if (size5 && typeof size5 === "string") { + if (size5.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/)) { + return size5; + } + } else if (size5 && Number.isInteger(size5)) { + const sizeK = Math.round(size5 / 1024); + return sizeK === 0 ? "1k" : sizeK + "k"; + } + return null; } - _SHA3_IOTA.push(t); - } - [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); - rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); - rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); - Keccak = class _Keccak extends Hash { - // NOTE: we accept arguments in bytes instead of bits here. - constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { - super(); - this.blockLen = blockLen; - this.suffix = suffix; - this.outputLen = outputLen; - this.enableXOF = enableXOF; - this.rounds = rounds; - this.pos = 0; - this.posOut = 0; - this.finished = false; - this.destroyed = false; - anumber(outputLen); - if (0 >= this.blockLen || this.blockLen >= 200) - throw new Error("Sha3 supports only keccak-f1600 function"); - this.state = new Uint8Array(200); - this.state32 = u32(this.state); + function isValidFileName(filename) { + return !/["<>|:*?\\/\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test( + filename + ); } - keccak() { - if (!isLE) - byteSwap32(this.state32); - keccakP(this.state32, this.rounds); - if (!isLE) - byteSwap32(this.state32); - this.posOut = 0; - this.pos = 0; + function isValidDirName(dirname2) { + return !/["<>|\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test( + dirname2 + ); } - update(data) { - aexists(this); - const { blockLen, state } = this; - data = toBytes2(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - for (let i = 0; i < take; i++) - state[this.pos++] ^= data[pos++]; - if (this.pos === blockLen) - this.keccak(); + this.options = Object.assign({}, loggerDefaults, options); + if (options.stream) { + throwIf("stream", "filename", "maxsize"); + this.logStream = new PassThrough(); + this.logStream.pipe(options.stream); + } else { + this.filename = options.filename ? path.basename(options.filename) : "winston.log"; + this.dirname = options.dirname || path.dirname(options.filename); + if (!isValidFileName(this.filename) || !isValidDirName(this.dirname)) { + throw new Error("Your path or filename contain an invalid character."); } - return this; - } - finish() { - if (this.finished) - return; - this.finished = true; - const { state, suffix, pos, blockLen } = this; - state[pos] ^= suffix; - if ((suffix & 128) !== 0 && pos === blockLen - 1) - this.keccak(); - state[blockLen - 1] ^= 128; - this.keccak(); - } - writeInto(out) { - aexists(this, false); - abytes(out); - this.finish(); - const bufferOut = this.state; - const { blockLen } = this; - for (let pos = 0, len = out.length; pos < len; ) { - if (this.posOut >= blockLen) - this.keccak(); - const take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; + this.logStream = require_FileStreamRotator().getStream({ + filename: path.join(this.dirname, this.filename), + frequency: options.frequency ? options.frequency : "custom", + date_format: options.datePattern ? options.datePattern : "YYYY-MM-DD", + verbose: false, + size: getMaxSize(options.maxSize), + max_logs: options.maxFiles, + end_stream: true, + audit_file: options.auditFile ? options.auditFile : path.join(this.dirname, "." + hash2(options) + "-audit.json"), + file_options: options.options ? options.options : { flags: "a" }, + utc: options.utc ? options.utc : false, + extension: options.extension ? options.extension : "", + create_symlink: options.createSymlink ? options.createSymlink : false, + symlink_name: options.symlinkName ? options.symlinkName : "current.log", + watch_log: options.watchLog ? options.watchLog : false, + audit_hash_type: options.auditHashType ? options.auditHashType : "sha256" + }); + this.logStream.on("new", (newFile) => { + this.emit("new", newFile); + }); + this.logStream.on("rotate", (oldFile, newFile) => { + this.emit("rotate", oldFile, newFile); + }); + this.logStream.on("logRemoved", (params) => { + if (options.zippedArchive) { + const gzName = params.name + ".gz"; + try { + fs2.unlinkSync(gzName); + } catch (err) { + if (err.code !== "ENOENT") { + err.message = `Error occurred while removing ${gzName}: ${err.message}`; + this.emit("error", err); + return; + } + } + this.emit("logRemoved", gzName); + return; + } + this.emit("logRemoved", params.name); + }); + if (options.zippedArchive) { + this.logStream.on("rotate", (oldFile) => { + try { + if (!fs2.existsSync(oldFile)) { + return; + } + } catch (err) { + err.message = `Error occurred while checking existence of ${oldFile}: ${err.message}`; + this.emit("error", err); + return; + } + try { + if (fs2.existsSync(`${oldFile}.gz`)) { + return; + } + } catch (err) { + err.message = `Error occurred while checking existence of ${oldFile}.gz: ${err.message}`; + this.emit("error", err); + return; + } + const gzip = zlib2.createGzip(); + const inp = fs2.createReadStream(oldFile); + inp.on("error", (err) => { + err.message = `Error occurred while reading ${oldFile}: ${err.message}`; + this.emit("error", err); + }); + const out = fs2.createWriteStream(oldFile + ".gz"); + out.on("error", (err) => { + err.message = `Error occurred while writing ${oldFile}.gz: ${err.message}`; + this.emit("error", err); + }); + inp.pipe(gzip).pipe(out).on("finish", () => { + try { + fs2.unlinkSync(oldFile); + } catch (err) { + if (err.code !== "ENOENT") { + err.message = `Error occurred while removing ${oldFile}: ${err.message}`; + this.emit("error", err); + return; + } + } + this.emit("archive", oldFile + ".gz"); + }); + }); } - return out; + if (options.watchLog) { + this.logStream.on("addWatcher", (newFile) => { + this.emit("addWatcher", newFile); + }); + } + } + }; + module2.exports = DailyRotateFile2; + util3.inherits(DailyRotateFile2, Transport2); + DailyRotateFile2.prototype.name = "dailyRotateFile"; + var noop2 = function() { + }; + DailyRotateFile2.prototype.log = function(info, callback) { + callback = callback || noop2; + this.logStream.write(info[MESSAGE] + this.options.eol); + this.emit("logged", info); + callback(null, true); + }; + DailyRotateFile2.prototype.close = function() { + if (this.logStream) { + this.logStream.end(() => { + this.emit("finish"); + }); } - xofInto(out) { - if (!this.enableXOF) - throw new Error("XOF is not possible for this instance"); - return this.writeInto(out); + }; + DailyRotateFile2.prototype.query = function(options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; } - xof(bytes) { - anumber(bytes); - return this.xofInto(new Uint8Array(bytes)); + if (!this.options.json) { + throw new Error( + "query() may not be used without the json option being set to true" + ); } - digestInto(out) { - aoutput(out, this); - if (this.finished) - throw new Error("digest() was already called"); - this.writeInto(out); - this.destroy(); - return out; + if (!this.filename) { + throw new Error("query() may not be used when initializing with a stream"); } - digest() { - return this.digestInto(new Uint8Array(this.outputLen)); + let results = []; + options = options || {}; + options.rows = options.rows || options.limit || 10; + options.start = options.start || 0; + options.until = options.until || /* @__PURE__ */ new Date(); + if (typeof options.until !== "object") { + options.until = new Date(options.until); } - destroy() { - this.destroyed = true; - this.state.fill(0); + options.from = options.from || options.until - 24 * 60 * 60 * 1e3; + if (typeof options.from !== "object") { + options.from = new Date(options.from); } - _cloneInto(to2) { - const { blockLen, suffix, outputLen, rounds, enableXOF } = this; - to2 || (to2 = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); - to2.state32.set(this.state32); - to2.pos = this.pos; - to2.posOut = this.posOut; - to2.finished = this.finished; - to2.rounds = rounds; - to2.suffix = suffix; - to2.outputLen = outputLen; - to2.enableXOF = enableXOF; - to2.destroyed = this.destroyed; - return to2; + options.order = options.order || "desc"; + const logFiles = (() => { + const fileRegex = new RegExp(this.filename.replace("%DATE%", ".*"), "i"); + return fs2.readdirSync(this.dirname).filter((file) => path.basename(file).match(fileRegex)); + })(); + if (logFiles.length === 0 && callback) { + callback(null, results); } - }; - gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); - sha3_224 = /* @__PURE__ */ gen(6, 144, 224 / 8); - sha3_256 = /* @__PURE__ */ gen(6, 136, 256 / 8); - sha3_384 = /* @__PURE__ */ gen(6, 104, 384 / 8); - sha3_512 = /* @__PURE__ */ gen(6, 72, 512 / 8); - keccak_224 = /* @__PURE__ */ gen(1, 144, 224 / 8); - keccak_256 = /* @__PURE__ */ gen(1, 136, 256 / 8); - keccak_384 = /* @__PURE__ */ gen(1, 104, 384 / 8); - keccak_512 = /* @__PURE__ */ gen(1, 72, 512 / 8); - genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true)); - shake128 = /* @__PURE__ */ genShake(31, 168, 128 / 8); - shake256 = /* @__PURE__ */ genShake(31, 136, 256 / 8); - } -}); - -// node_modules/viem/_esm/utils/hash/keccak256.js -function keccak256(value, to_) { - const to2 = to_ || "hex"; - const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value); - if (to2 === "bytes") - return bytes; - return toHex(bytes); -} -var init_keccak256 = __esm({ - "node_modules/viem/_esm/utils/hash/keccak256.js"() { - init_sha3(); - init_isHex(); - init_toBytes(); - init_toHex(); - } -}); - -// node_modules/viem/_esm/utils/hash/hashSignature.js -function hashSignature(sig) { - return hash(sig); -} -var hash; -var init_hashSignature = __esm({ - "node_modules/viem/_esm/utils/hash/hashSignature.js"() { - init_toBytes(); - init_keccak256(); - hash = (value) => keccak256(toBytes(value)); - } -}); - -// node_modules/viem/_esm/utils/hash/normalizeSignature.js -function normalizeSignature(signature) { - let active = true; - let current = ""; - let level = 0; - let result = ""; - let valid = false; - for (let i = 0; i < signature.length; i++) { - const char = signature[i]; - if (["(", ")", ","].includes(char)) - active = true; - if (char === "(") - level++; - if (char === ")") - level--; - if (!active) - continue; - if (level === 0) { - if (char === " " && ["event", "function", ""].includes(result)) - result = ""; - else { - result += char; - if (char === ")") { - valid = true; - break; + const processLogFile = (file) => { + if (!file) { + return; } - } - continue; - } - if (char === " ") { - if (signature[i - 1] !== "," && current !== "," && current !== ",(") { - current = ""; - active = false; - } - continue; - } - result += char; - current += char; - } - if (!valid) - throw new BaseError2("Unable to normalize signature."); - return result; -} -var init_normalizeSignature = __esm({ - "node_modules/viem/_esm/utils/hash/normalizeSignature.js"() { - init_base(); - } -}); - -// node_modules/viem/_esm/utils/hash/toSignature.js -var toSignature; -var init_toSignature = __esm({ - "node_modules/viem/_esm/utils/hash/toSignature.js"() { - init_exports(); - init_normalizeSignature(); - toSignature = (def) => { - const def_ = (() => { - if (typeof def === "string") - return def; - return formatAbiItem(def); - })(); - return normalizeSignature(def_); + const logFile = path.join(this.dirname, file); + let buff = ""; + let stream4; + if (file.endsWith(".gz")) { + stream4 = new PassThrough(); + const inp = fs2.createReadStream(logFile); + inp.on("error", (err) => { + err.message = `Error occurred while reading ${logFile}: ${err.message}`; + stream4.emit("error", err); + }); + inp.pipe(zlib2.createGunzip()).pipe(stream4); + } else { + stream4 = fs2.createReadStream(logFile, { + encoding: "utf8" + }); + } + stream4.on("error", (err) => { + if (stream4.readable) { + stream4.destroy(); + } + if (!callback) { + return; + } + return err.code === "ENOENT" ? callback(null, results) : callback(err); + }); + stream4.on("data", (data) => { + data = (buff + data).split(/\n+/); + const l = data.length - 1; + for (let i = 0; i < l; i++) { + add(data[i]); + } + buff = data[l]; + }); + stream4.on("end", () => { + if (buff) { + add(buff, true); + } + if (logFiles.length) { + processLogFile(logFiles.shift()); + } else if (callback) { + results.sort((a, b2) => { + const d1 = new Date(a.timestamp).getTime(); + const d2 = new Date(b2.timestamp).getTime(); + return d1 > d2 ? 1 : d1 < d2 ? -1 : 0; + }); + if (options.order === "desc") { + results = results.reverse(); + } + const start = options.start || 0; + const limit = options.limit || results.length; + results = results.slice(start, start + limit); + if (options.fields) { + results = results.map((log) => { + const obj = {}; + options.fields.forEach((key) => { + obj[key] = log[key]; + }); + return obj; + }); + } + callback(null, results); + } + }); + function add(buff2, attempt) { + try { + const log = JSON.parse(buff2); + if (!log || typeof log !== "object") { + return; + } + const time = new Date(log.timestamp); + if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) { + return; + } + results.push(log); + } catch (e) { + if (!attempt) { + stream4.emit("error", e); + } + } + } + }; + processLogFile(logFiles.shift()); }; } }); -// node_modules/viem/_esm/utils/hash/toSignatureHash.js -function toSignatureHash(fn2) { - return hashSignature(toSignature(fn2)); -} -var init_toSignatureHash = __esm({ - "node_modules/viem/_esm/utils/hash/toSignatureHash.js"() { - init_hashSignature(); - init_toSignature(); +// node_modules/winston-daily-rotate-file/index.js +var require_winston_daily_rotate_file = __commonJS({ + "node_modules/winston-daily-rotate-file/index.js"(exports2, module2) { + var winston2 = require_winston(); + var DailyRotateFile2 = require_daily_rotate_file(); + winston2.transports.DailyRotateFile = DailyRotateFile2; + module2.exports = DailyRotateFile2; } }); -// node_modules/viem/_esm/utils/hash/toEventSelector.js -var toEventSelector; -var init_toEventSelector = __esm({ - "node_modules/viem/_esm/utils/hash/toEventSelector.js"() { - init_toSignatureHash(); - toEventSelector = toSignatureHash; +// node_modules/abitype/dist/esm/version.js +var version; +var init_version = __esm({ + "node_modules/abitype/dist/esm/version.js"() { + version = "1.0.8"; } }); -// node_modules/viem/_esm/errors/address.js -var InvalidAddressError; -var init_address = __esm({ - "node_modules/viem/_esm/errors/address.js"() { - init_base(); - InvalidAddressError = class extends BaseError2 { - constructor({ address }) { - super(`Address "${address}" is invalid.`, { - metaMessages: [ - "- Address must be a hex value of 20 bytes (40 hex characters).", - "- Address must match its checksum counterpart." - ], - name: "InvalidAddressError" +// node_modules/abitype/dist/esm/errors.js +var BaseError; +var init_errors = __esm({ + "node_modules/abitype/dist/esm/errors.js"() { + init_version(); + BaseError = class _BaseError extends Error { + constructor(shortMessage, args = {}) { + const details = args.cause instanceof _BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details; + const docsPath6 = args.cause instanceof _BaseError ? args.cause.docsPath || args.docsPath : args.docsPath; + const message = [ + shortMessage || "An error occurred.", + "", + ...args.metaMessages ? [...args.metaMessages, ""] : [], + ...docsPath6 ? [`Docs: https://abitype.dev${docsPath6}`] : [], + ...details ? [`Details: ${details}`] : [], + `Version: abitype@${version}` + ].join("\n"); + super(message); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - } - }; - } -}); - -// node_modules/viem/_esm/utils/lru.js -var LruMap; -var init_lru = __esm({ - "node_modules/viem/_esm/utils/lru.js"() { - LruMap = class extends Map { - constructor(size5) { - super(); - Object.defineProperty(this, "maxSize", { + Object.defineProperty(this, "docsPath", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.maxSize = size5; - } - get(key) { - const value = super.get(key); - if (super.has(key) && value !== void 0) { - this.delete(key); - super.set(key, value); - } - return value; - } - set(key, value) { - super.set(key, value); - if (this.maxSize && this.size > this.maxSize) { - const firstKey = this.keys().next().value; - if (firstKey) - this.delete(firstKey); - } - return this; - } - }; - } -}); - -// node_modules/viem/_esm/utils/address/getAddress.js -function checksumAddress(address_, chainId) { - if (checksumAddressCache.has(`${address_}.${chainId}`)) - return checksumAddressCache.get(`${address_}.${chainId}`); - const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase(); - const hash2 = keccak256(stringToBytes(hexAddress), "bytes"); - const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split(""); - for (let i = 0; i < 40; i += 2) { - if (hash2[i >> 1] >> 4 >= 8 && address[i]) { - address[i] = address[i].toUpperCase(); - } - if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) { - address[i + 1] = address[i + 1].toUpperCase(); - } - } - const result = `0x${address.join("")}`; - checksumAddressCache.set(`${address_}.${chainId}`, result); - return result; -} -function getAddress(address, chainId) { - if (!isAddress(address, { strict: false })) - throw new InvalidAddressError({ address }); - return checksumAddress(address, chainId); -} -var checksumAddressCache; -var init_getAddress = __esm({ - "node_modules/viem/_esm/utils/address/getAddress.js"() { - init_address(); - init_toBytes(); - init_keccak256(); - init_lru(); - init_isAddress(); - checksumAddressCache = /* @__PURE__ */ new LruMap(8192); - } -}); - -// node_modules/viem/_esm/utils/address/isAddress.js -function isAddress(address, options) { - const { strict = true } = options ?? {}; - const cacheKey2 = `${address}.${strict}`; - if (isAddressCache.has(cacheKey2)) - return isAddressCache.get(cacheKey2); - const result = (() => { - if (!addressRegex.test(address)) - return false; - if (address.toLowerCase() === address) - return true; - if (strict) - return checksumAddress(address) === address; - return true; - })(); - isAddressCache.set(cacheKey2, result); - return result; -} -var addressRegex, isAddressCache; -var init_isAddress = __esm({ - "node_modules/viem/_esm/utils/address/isAddress.js"() { - init_lru(); - init_getAddress(); - addressRegex = /^0x[a-fA-F0-9]{40}$/; - isAddressCache = /* @__PURE__ */ new LruMap(8192); - } -}); - -// node_modules/viem/_esm/utils/data/concat.js -function concat(values) { - if (typeof values[0] === "string") - return concatHex(values); - return concatBytes2(values); -} -function concatBytes2(values) { - let length = 0; - for (const arr of values) { - length += arr.length; - } - const result = new Uint8Array(length); - let offset = 0; - for (const arr of values) { - result.set(arr, offset); - offset += arr.length; - } - return result; -} -function concatHex(values) { - return `0x${values.reduce((acc, x2) => acc + x2.replace("0x", ""), "")}`; -} -var init_concat = __esm({ - "node_modules/viem/_esm/utils/data/concat.js"() { - } -}); - -// node_modules/viem/_esm/utils/data/slice.js -function slice(value, start, end, { strict } = {}) { - if (isHex(value, { strict: false })) - return sliceHex(value, start, end, { - strict - }); - return sliceBytes(value, start, end, { - strict - }); -} -function assertStartOffset(value, start) { - if (typeof start === "number" && start > 0 && start > size(value) - 1) - throw new SliceOffsetOutOfBoundsError({ - offset: start, - position: "start", - size: size(value) - }); -} -function assertEndOffset(value, start, end) { - if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) { - throw new SliceOffsetOutOfBoundsError({ - offset: end, - position: "end", - size: size(value) - }); - } -} -function sliceBytes(value_, start, end, { strict } = {}) { - assertStartOffset(value_, start); - const value = value_.slice(start, end); - if (strict) - assertEndOffset(value, start, end); - return value; -} -function sliceHex(value_, start, end, { strict } = {}) { - assertStartOffset(value_, start); - const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`; - if (strict) - assertEndOffset(value, start, end); - return value; -} -var init_slice = __esm({ - "node_modules/viem/_esm/utils/data/slice.js"() { - init_data(); - init_isHex(); - init_size(); + Object.defineProperty(this, "metaMessages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "shortMessage", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiTypeError" + }); + if (args.cause) + this.cause = args.cause; + this.details = details; + this.docsPath = docsPath6; + this.metaMessages = args.metaMessages; + this.shortMessage = shortMessage; + } + }; } }); -// node_modules/viem/_esm/utils/regex.js -var bytesRegex2, integerRegex2; -var init_regex2 = __esm({ - "node_modules/viem/_esm/utils/regex.js"() { - bytesRegex2 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; - integerRegex2 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; +// node_modules/abitype/dist/esm/regex.js +function execTyped(regex, string) { + const match = regex.exec(string); + return match?.groups; +} +var bytesRegex, integerRegex, isTupleRegex; +var init_regex = __esm({ + "node_modules/abitype/dist/esm/regex.js"() { + bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; + integerRegex = /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; + isTupleRegex = /^\(.+?\).*?$/; } }); -// node_modules/viem/_esm/utils/abi/encodeAbiParameters.js -function encodeAbiParameters(params, values) { - if (params.length !== values.length) - throw new AbiEncodingLengthMismatchError({ - expectedLength: params.length, - givenLength: values.length +// node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js +function formatAbiParameter(abiParameter) { + let type = abiParameter.type; + if (tupleRegex.test(abiParameter.type) && "components" in abiParameter) { + type = "("; + const length = abiParameter.components.length; + for (let i = 0; i < length; i++) { + const component = abiParameter.components[i]; + type += formatAbiParameter(component); + if (i < length - 1) + type += ", "; + } + const result = execTyped(tupleRegex, abiParameter.type); + type += `)${result?.array ?? ""}`; + return formatAbiParameter({ + ...abiParameter, + type }); - const preparedParams = prepareParams({ - params, - values - }); - const data = encodeParams(preparedParams); - if (data.length === 0) - return "0x"; - return data; -} -function prepareParams({ params, values }) { - const preparedParams = []; - for (let i = 0; i < params.length; i++) { - preparedParams.push(prepareParam({ param: params[i], value: values[i] })); } - return preparedParams; + if ("indexed" in abiParameter && abiParameter.indexed) + type = `${type} indexed`; + if (abiParameter.name) + return `${type} ${abiParameter.name}`; + return type; } -function prepareParam({ param, value }) { - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents) { - const [length, type] = arrayComponents; - return encodeArray(value, { length, param: { ...param, type } }); - } - if (param.type === "tuple") { - return encodeTuple(value, { - param - }); - } - if (param.type === "address") { - return encodeAddress(value); - } - if (param.type === "bool") { - return encodeBool(value); - } - if (param.type.startsWith("uint") || param.type.startsWith("int")) { - const signed = param.type.startsWith("int"); - const [, , size5 = "256"] = integerRegex2.exec(param.type) ?? []; - return encodeNumber(value, { - signed, - size: Number(size5) - }); - } - if (param.type.startsWith("bytes")) { - return encodeBytes(value, { param }); +var tupleRegex; +var init_formatAbiParameter = __esm({ + "node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js"() { + init_regex(); + tupleRegex = /^tuple(?(\[(\d*)\])*)$/; } - if (param.type === "string") { - return encodeString(value); +}); + +// node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js +function formatAbiParameters(abiParameters) { + let params = ""; + const length = abiParameters.length; + for (let i = 0; i < length; i++) { + const abiParameter = abiParameters[i]; + params += formatAbiParameter(abiParameter); + if (i !== length - 1) + params += ", "; } - throw new InvalidAbiEncodingTypeError(param.type, { - docsPath: "/docs/contract/encodeAbiParameters" - }); + return params; } -function encodeParams(preparedParams) { - let staticSize = 0; - for (let i = 0; i < preparedParams.length; i++) { - const { dynamic, encoded } = preparedParams[i]; - if (dynamic) - staticSize += 32; - else - staticSize += size(encoded); - } - const staticParams = []; - const dynamicParams = []; - let dynamicSize = 0; - for (let i = 0; i < preparedParams.length; i++) { - const { dynamic, encoded } = preparedParams[i]; - if (dynamic) { - staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 })); - dynamicParams.push(encoded); - dynamicSize += size(encoded); - } else { - staticParams.push(encoded); - } +var init_formatAbiParameters = __esm({ + "node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js"() { + init_formatAbiParameter(); } - return concat([...staticParams, ...dynamicParams]); -} -function encodeAddress(value) { - if (!isAddress(value)) - throw new InvalidAddressError({ address: value }); - return { dynamic: false, encoded: padHex(value.toLowerCase()) }; +}); + +// node_modules/abitype/dist/esm/human-readable/formatAbiItem.js +function formatAbiItem(abiItem) { + if (abiItem.type === "function") + return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== "nonpayable" ? ` ${abiItem.stateMutability}` : ""}${abiItem.outputs?.length ? ` returns (${formatAbiParameters(abiItem.outputs)})` : ""}`; + if (abiItem.type === "event") + return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; + if (abiItem.type === "error") + return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; + if (abiItem.type === "constructor") + return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === "payable" ? " payable" : ""}`; + if (abiItem.type === "fallback") + return `fallback() external${abiItem.stateMutability === "payable" ? " payable" : ""}`; + return "receive() external payable"; } -function encodeArray(value, { length, param }) { - const dynamic = length === null; - if (!Array.isArray(value)) - throw new InvalidArrayError(value); - if (!dynamic && value.length !== length) - throw new AbiEncodingArrayLengthMismatchError({ - expectedLength: length, - givenLength: value.length, - type: `${param.type}[${length}]` - }); - let dynamicChild = false; - const preparedParams = []; - for (let i = 0; i < value.length; i++) { - const preparedParam = prepareParam({ param, value: value[i] }); - if (preparedParam.dynamic) - dynamicChild = true; - preparedParams.push(preparedParam); - } - if (dynamic || dynamicChild) { - const data = encodeParams(preparedParams); - if (dynamic) { - const length2 = numberToHex(preparedParams.length, { size: 32 }); - return { - dynamic: true, - encoded: preparedParams.length > 0 ? concat([length2, data]) : length2 - }; - } - if (dynamicChild) - return { dynamic: true, encoded: data }; +var init_formatAbiItem = __esm({ + "node_modules/abitype/dist/esm/human-readable/formatAbiItem.js"() { + init_formatAbiParameters(); } - return { - dynamic: false, - encoded: concat(preparedParams.map(({ encoded }) => encoded)) - }; +}); + +// node_modules/abitype/dist/esm/human-readable/runtime/signatures.js +function isErrorSignature(signature) { + return errorSignatureRegex.test(signature); } -function encodeBytes(value, { param }) { - const [, paramSize] = param.type.split("bytes"); - const bytesSize = size(value); - if (!paramSize) { - let value_ = value; - if (bytesSize % 32 !== 0) - value_ = padHex(value_, { - dir: "right", - size: Math.ceil((value.length - 2) / 2 / 32) * 32 - }); - return { - dynamic: true, - encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]) - }; - } - if (bytesSize !== Number.parseInt(paramSize)) - throw new AbiEncodingBytesSizeMismatchError({ - expectedSize: Number.parseInt(paramSize), - value - }); - return { dynamic: false, encoded: padHex(value, { dir: "right" }) }; +function execErrorSignature(signature) { + return execTyped(errorSignatureRegex, signature); } -function encodeBool(value) { - if (typeof value !== "boolean") - throw new BaseError2(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); - return { dynamic: false, encoded: padHex(boolToHex(value)) }; +function isEventSignature(signature) { + return eventSignatureRegex.test(signature); } -function encodeNumber(value, { signed, size: size5 = 256 }) { - if (typeof size5 === "number") { - const max = 2n ** (BigInt(size5) - (signed ? 1n : 0n)) - 1n; - const min = signed ? -max - 1n : 0n; - if (value > max || value < min) - throw new IntegerOutOfRangeError({ - max: max.toString(), - min: min.toString(), - signed, - size: size5 / 8, - value: value.toString() - }); - } - return { - dynamic: false, - encoded: numberToHex(value, { - size: 32, - signed - }) - }; +function execEventSignature(signature) { + return execTyped(eventSignatureRegex, signature); } -function encodeString(value) { - const hexValue = stringToHex(value); - const partsLength = Math.ceil(size(hexValue) / 32); - const parts = []; - for (let i = 0; i < partsLength; i++) { - parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), { - dir: "right" - })); - } - return { - dynamic: true, - encoded: concat([ - padHex(numberToHex(size(hexValue), { size: 32 })), - ...parts - ]) - }; +function isFunctionSignature(signature) { + return functionSignatureRegex.test(signature); } -function encodeTuple(value, { param }) { - let dynamic = false; - const preparedParams = []; - for (let i = 0; i < param.components.length; i++) { - const param_ = param.components[i]; - const index2 = Array.isArray(value) ? i : param_.name; - const preparedParam = prepareParam({ - param: param_, - value: value[index2] - }); - preparedParams.push(preparedParam); - if (preparedParam.dynamic) - dynamic = true; - } - return { - dynamic, - encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded)) - }; +function execFunctionSignature(signature) { + return execTyped(functionSignatureRegex, signature); } -function getArrayComponents(type) { - const matches = type.match(/^(.*)\[(\d+)?\]$/); - return matches ? ( - // Return `null` if the array is dynamic. - [matches[2] ? Number(matches[2]) : null, matches[1]] - ) : void 0; +function isStructSignature(signature) { + return structSignatureRegex.test(signature); } -var init_encodeAbiParameters = __esm({ - "node_modules/viem/_esm/utils/abi/encodeAbiParameters.js"() { - init_abi(); - init_address(); - init_base(); - init_encoding(); - init_isAddress(); - init_concat(); - init_pad(); - init_size(); - init_slice(); - init_toHex(); - init_regex2(); - } -}); - -// node_modules/viem/_esm/utils/hash/toFunctionSelector.js -var toFunctionSelector; -var init_toFunctionSelector = __esm({ - "node_modules/viem/_esm/utils/hash/toFunctionSelector.js"() { - init_slice(); - init_toSignatureHash(); - toFunctionSelector = (fn2) => slice(toSignatureHash(fn2), 0, 4); - } -}); - -// node_modules/viem/_esm/utils/abi/getAbiItem.js -function getAbiItem(parameters) { - const { abi: abi4, args = [], name } = parameters; - const isSelector = isHex(name, { strict: false }); - const abiItems = abi4.filter((abiItem) => { - if (isSelector) { - if (abiItem.type === "function") - return toFunctionSelector(abiItem) === name; - if (abiItem.type === "event") - return toEventSelector(abiItem) === name; - return false; - } - return "name" in abiItem && abiItem.name === name; - }); - if (abiItems.length === 0) - return void 0; - if (abiItems.length === 1) - return abiItems[0]; - let matchedAbiItem = void 0; - for (const abiItem of abiItems) { - if (!("inputs" in abiItem)) - continue; - if (!args || args.length === 0) { - if (!abiItem.inputs || abiItem.inputs.length === 0) - return abiItem; - continue; - } - if (!abiItem.inputs) - continue; - if (abiItem.inputs.length === 0) - continue; - if (abiItem.inputs.length !== args.length) - continue; - const matched = args.every((arg, index2) => { - const abiParameter = "inputs" in abiItem && abiItem.inputs[index2]; - if (!abiParameter) - return false; - return isArgOfType(arg, abiParameter); - }); - if (matched) { - if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { - const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args); - if (ambiguousTypes) - throw new AbiItemAmbiguityError({ - abiItem, - type: ambiguousTypes[0] - }, { - abiItem: matchedAbiItem, - type: ambiguousTypes[1] - }); - } - matchedAbiItem = abiItem; - } - } - if (matchedAbiItem) - return matchedAbiItem; - return abiItems[0]; +function execStructSignature(signature) { + return execTyped(structSignatureRegex, signature); } -function isArgOfType(arg, abiParameter) { - const argType = typeof arg; - const abiParameterType = abiParameter.type; - switch (abiParameterType) { - case "address": - return isAddress(arg, { strict: false }); - case "bool": - return argType === "boolean"; - case "function": - return argType === "string"; - case "string": - return argType === "string"; - default: { - if (abiParameterType === "tuple" && "components" in abiParameter) - return Object.values(abiParameter.components).every((component, index2) => { - return isArgOfType(Object.values(arg)[index2], component); - }); - if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) - return argType === "number" || argType === "bigint"; - if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) - return argType === "string" || arg instanceof Uint8Array; - if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { - return Array.isArray(arg) && arg.every((x2) => isArgOfType(x2, { - ...abiParameter, - // Pop off `[]` or `[M]` from end of type - type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") - })); - } - return false; - } - } +function isConstructorSignature(signature) { + return constructorSignatureRegex.test(signature); } -function getAmbiguousTypes(sourceParameters, targetParameters, args) { - for (const parameterIndex in sourceParameters) { - const sourceParameter = sourceParameters[parameterIndex]; - const targetParameter = targetParameters[parameterIndex]; - if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) - return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]); - const types = [sourceParameter.type, targetParameter.type]; - const ambiguous = (() => { - if (types.includes("address") && types.includes("bytes20")) - return true; - if (types.includes("address") && types.includes("string")) - return isAddress(args[parameterIndex], { strict: false }); - if (types.includes("address") && types.includes("bytes")) - return isAddress(args[parameterIndex], { strict: false }); - return false; - })(); - if (ambiguous) - return types; - } - return; +function execConstructorSignature(signature) { + return execTyped(constructorSignatureRegex, signature); } -var init_getAbiItem = __esm({ - "node_modules/viem/_esm/utils/abi/getAbiItem.js"() { - init_abi(); - init_isHex(); - init_isAddress(); - init_toEventSelector(); - init_toFunctionSelector(); - } -}); - -// node_modules/viem/_esm/accounts/utils/parseAccount.js -function parseAccount(account) { - if (typeof account === "string") - return { address: account, type: "json-rpc" }; - return account; +function isFallbackSignature(signature) { + return fallbackSignatureRegex.test(signature); } -var init_parseAccount = __esm({ - "node_modules/viem/_esm/accounts/utils/parseAccount.js"() { - } -}); - -// node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js -function prepareEncodeFunctionData(parameters) { - const { abi: abi4, args, functionName } = parameters; - let abiItem = abi4[0]; - if (functionName) { - const item = getAbiItem({ - abi: abi4, - args, - name: functionName - }); - if (!item) - throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath2 }); - abiItem = item; - } - if (abiItem.type !== "function") - throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath2 }); - return { - abi: [abiItem], - functionName: toFunctionSelector(formatAbiItem2(abiItem)) - }; +function execFallbackSignature(signature) { + return execTyped(fallbackSignatureRegex, signature); } -var docsPath2; -var init_prepareEncodeFunctionData = __esm({ - "node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js"() { - init_abi(); - init_toFunctionSelector(); - init_formatAbiItem2(); - init_getAbiItem(); - docsPath2 = "/docs/contract/encodeFunctionData"; +function isReceiveSignature(signature) { + return receiveSignatureRegex.test(signature); +} +var errorSignatureRegex, eventSignatureRegex, functionSignatureRegex, structSignatureRegex, constructorSignatureRegex, fallbackSignatureRegex, receiveSignatureRegex, modifiers, eventModifiers, functionModifiers; +var init_signatures = __esm({ + "node_modules/abitype/dist/esm/human-readable/runtime/signatures.js"() { + init_regex(); + errorSignatureRegex = /^error (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; + eventSignatureRegex = /^event (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)$/; + functionSignatureRegex = /^function (?[a-zA-Z$_][a-zA-Z0-9$_]*)\((?.*?)\)(?: (?external|public{1}))?(?: (?pure|view|nonpayable|payable{1}))?(?: returns\s?\((?.*?)\))?$/; + structSignatureRegex = /^struct (?[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?.*?)\}$/; + constructorSignatureRegex = /^constructor\((?.*?)\)(?:\s(?payable{1}))?$/; + fallbackSignatureRegex = /^fallback\(\) external(?:\s(?payable{1}))?$/; + receiveSignatureRegex = /^receive\(\) external payable$/; + modifiers = /* @__PURE__ */ new Set([ + "memory", + "indexed", + "storage", + "calldata" + ]); + eventModifiers = /* @__PURE__ */ new Set(["indexed"]); + functionModifiers = /* @__PURE__ */ new Set([ + "calldata", + "memory", + "storage" + ]); } }); -// node_modules/viem/_esm/utils/abi/encodeFunctionData.js -function encodeFunctionData(parameters) { - const { args } = parameters; - const { abi: abi4, functionName } = (() => { - if (parameters.abi.length === 1 && parameters.functionName?.startsWith("0x")) - return parameters; - return prepareEncodeFunctionData(parameters); - })(); - const abiItem = abi4[0]; - const signature = functionName; - const data = "inputs" in abiItem && abiItem.inputs ? encodeAbiParameters(abiItem.inputs, args ?? []) : void 0; - return concatHex([signature, data ?? "0x"]); -} -var init_encodeFunctionData = __esm({ - "node_modules/viem/_esm/utils/abi/encodeFunctionData.js"() { - init_concat(); - init_encodeAbiParameters(); - init_prepareEncodeFunctionData(); +// node_modules/abitype/dist/esm/human-readable/errors/abiItem.js +var InvalidAbiItemError, UnknownTypeError, UnknownSolidityTypeError; +var init_abiItem = __esm({ + "node_modules/abitype/dist/esm/human-readable/errors/abiItem.js"() { + init_errors(); + InvalidAbiItemError = class extends BaseError { + constructor({ signature }) { + super("Failed to parse ABI item.", { + details: `parseAbiItem(${JSON.stringify(signature, null, 2)})`, + docsPath: "/api/human#parseabiitem-1" + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidAbiItemError" + }); + } + }; + UnknownTypeError = class extends BaseError { + constructor({ type }) { + super("Unknown type.", { + metaMessages: [ + `Type "${type}" is not a valid ABI type. Perhaps you forgot to include a struct signature?` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownTypeError" + }); + } + }; + UnknownSolidityTypeError = class extends BaseError { + constructor({ type }) { + super("Unknown type.", { + metaMessages: [`Type "${type}" is not a valid ABI type.`] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownSolidityTypeError" + }); + } + }; } }); -// node_modules/viem/_esm/constants/solidity.js -var panicReasons, solidityError, solidityPanic; -var init_solidity = __esm({ - "node_modules/viem/_esm/constants/solidity.js"() { - panicReasons = { - 1: "An `assert` condition failed.", - 17: "Arithmetic operation resulted in underflow or overflow.", - 18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).", - 33: "Attempted to convert to an invalid type.", - 34: "Attempted to access a storage byte array that is incorrectly encoded.", - 49: "Performed `.pop()` on an empty array", - 50: "Array index is out of bounds.", - 65: "Allocated too much memory or created an array which is too large.", - 81: "Attempted to call a zero-initialized variable of internal function type." +// node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js +var InvalidAbiParametersError, InvalidParameterError, SolidityProtectedKeywordError, InvalidModifierError, InvalidFunctionModifierError, InvalidAbiTypeParameterError; +var init_abiParameter = __esm({ + "node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js"() { + init_errors(); + InvalidAbiParametersError = class extends BaseError { + constructor({ params }) { + super("Failed to parse ABI parameters.", { + details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`, + docsPath: "/api/human#parseabiparameters-1" + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidAbiParametersError" + }); + } }; - solidityError = { - inputs: [ - { - name: "message", - type: "string" - } - ], - name: "Error", - type: "error" + InvalidParameterError = class extends BaseError { + constructor({ param }) { + super("Invalid ABI parameter.", { + details: param + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidParameterError" + }); + } }; - solidityPanic = { - inputs: [ - { - name: "reason", - type: "uint256" - } - ], - name: "Panic", - type: "error" + SolidityProtectedKeywordError = class extends BaseError { + constructor({ param, name }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `"${name}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "SolidityProtectedKeywordError" + }); + } + }; + InvalidModifierError = class extends BaseError { + constructor({ param, type, modifier }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidModifierError" + }); + } + }; + InvalidFunctionModifierError = class extends BaseError { + constructor({ param, type, modifier }) { + super("Invalid ABI parameter.", { + details: param, + metaMessages: [ + `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.`, + `Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.` + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidFunctionModifierError" + }); + } + }; + InvalidAbiTypeParameterError = class extends BaseError { + constructor({ abiParameter }) { + super("Invalid ABI parameter.", { + details: JSON.stringify(abiParameter, null, 2), + metaMessages: ["ABI parameter type is invalid."] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidAbiTypeParameterError" + }); + } }; } }); -// node_modules/viem/_esm/errors/cursor.js -var NegativeOffsetError, PositionOutOfBoundsError, RecursiveReadLimitExceededError; -var init_cursor = __esm({ - "node_modules/viem/_esm/errors/cursor.js"() { - init_base(); - NegativeOffsetError = class extends BaseError2 { - constructor({ offset }) { - super(`Offset \`${offset}\` cannot be negative.`, { - name: "NegativeOffsetError" +// node_modules/abitype/dist/esm/human-readable/errors/signature.js +var InvalidSignatureError, UnknownSignatureError, InvalidStructSignatureError; +var init_signature = __esm({ + "node_modules/abitype/dist/esm/human-readable/errors/signature.js"() { + init_errors(); + InvalidSignatureError = class extends BaseError { + constructor({ signature, type }) { + super(`Invalid ${type} signature.`, { + details: signature + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidSignatureError" }); } }; - PositionOutOfBoundsError = class extends BaseError2 { - constructor({ length, position }) { - super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" }); + UnknownSignatureError = class extends BaseError { + constructor({ signature }) { + super("Unknown signature.", { + details: signature + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "UnknownSignatureError" + }); } }; - RecursiveReadLimitExceededError = class extends BaseError2 { - constructor({ count, limit }) { - super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: "RecursiveReadLimitExceededError" }); + InvalidStructSignatureError = class extends BaseError { + constructor({ signature }) { + super("Invalid struct signature.", { + details: signature, + metaMessages: ["No properties exist."] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidStructSignatureError" + }); } }; } }); -// node_modules/viem/_esm/utils/cursor.js -function createCursor(bytes, { recursiveReadLimit = 8192 } = {}) { - const cursor = Object.create(staticCursor); - cursor.bytes = bytes; - cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - cursor.positionReadCount = /* @__PURE__ */ new Map(); - cursor.recursiveReadLimit = recursiveReadLimit; - return cursor; -} -var staticCursor; -var init_cursor2 = __esm({ - "node_modules/viem/_esm/utils/cursor.js"() { - init_cursor(); - staticCursor = { - bytes: new Uint8Array(), - dataView: new DataView(new ArrayBuffer(0)), - position: 0, - positionReadCount: /* @__PURE__ */ new Map(), - recursiveReadCount: 0, - recursiveReadLimit: Number.POSITIVE_INFINITY, - assertReadLimit() { - if (this.recursiveReadCount >= this.recursiveReadLimit) - throw new RecursiveReadLimitExceededError({ - count: this.recursiveReadCount + 1, - limit: this.recursiveReadLimit - }); - }, - assertPosition(position) { - if (position < 0 || position > this.bytes.length - 1) - throw new PositionOutOfBoundsError({ - length: this.bytes.length, - position - }); - }, - decrementPosition(offset) { - if (offset < 0) - throw new NegativeOffsetError({ offset }); - const position = this.position - offset; - this.assertPosition(position); - this.position = position; - }, - getReadCount(position) { - return this.positionReadCount.get(position || this.position) || 0; - }, - incrementPosition(offset) { - if (offset < 0) - throw new NegativeOffsetError({ offset }); - const position = this.position + offset; - this.assertPosition(position); - this.position = position; - }, - inspectByte(position_) { - const position = position_ ?? this.position; - this.assertPosition(position); - return this.bytes[position]; - }, - inspectBytes(length, position_) { - const position = position_ ?? this.position; - this.assertPosition(position + length - 1); - return this.bytes.subarray(position, position + length); - }, - inspectUint8(position_) { - const position = position_ ?? this.position; - this.assertPosition(position); - return this.bytes[position]; - }, - inspectUint16(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 1); - return this.dataView.getUint16(position); - }, - inspectUint24(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 2); - return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); - }, - inspectUint32(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 3); - return this.dataView.getUint32(position); - }, - pushByte(byte) { - this.assertPosition(this.position); - this.bytes[this.position] = byte; - this.position++; - }, - pushBytes(bytes) { - this.assertPosition(this.position + bytes.length - 1); - this.bytes.set(bytes, this.position); - this.position += bytes.length; - }, - pushUint8(value) { - this.assertPosition(this.position); - this.bytes[this.position] = value; - this.position++; - }, - pushUint16(value) { - this.assertPosition(this.position + 1); - this.dataView.setUint16(this.position, value); - this.position += 2; - }, - pushUint24(value) { - this.assertPosition(this.position + 2); - this.dataView.setUint16(this.position, value >> 8); - this.dataView.setUint8(this.position + 2, value & ~4294967040); - this.position += 3; - }, - pushUint32(value) { - this.assertPosition(this.position + 3); - this.dataView.setUint32(this.position, value); - this.position += 4; - }, - readByte() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectByte(); - this.position++; - return value; - }, - readBytes(length, size5) { - this.assertReadLimit(); - this._touch(); - const value = this.inspectBytes(length); - this.position += size5 ?? length; - return value; - }, - readUint8() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint8(); - this.position += 1; - return value; - }, - readUint16() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint16(); - this.position += 2; - return value; - }, - readUint24() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint24(); - this.position += 3; - return value; - }, - readUint32() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint32(); - this.position += 4; - return value; - }, - get remaining() { - return this.bytes.length - this.position; - }, - setPosition(position) { - const oldPosition = this.position; - this.assertPosition(position); - this.position = position; - return () => this.position = oldPosition; - }, - _touch() { - if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) - return; - const count = this.getReadCount(); - this.positionReadCount.set(this.position, count + 1); - if (count > 0) - this.recursiveReadCount++; +// node_modules/abitype/dist/esm/human-readable/errors/struct.js +var CircularReferenceError; +var init_struct = __esm({ + "node_modules/abitype/dist/esm/human-readable/errors/struct.js"() { + init_errors(); + CircularReferenceError = class extends BaseError { + constructor({ type }) { + super("Circular reference detected.", { + metaMessages: [`Struct "${type}" is a circular reference.`] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "CircularReferenceError" + }); + } + }; + } +}); + +// node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js +var InvalidParenthesisError; +var init_splitParameters = __esm({ + "node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js"() { + init_errors(); + InvalidParenthesisError = class extends BaseError { + constructor({ current, depth }) { + super("Unbalanced parentheses.", { + metaMessages: [ + `"${current.trim()}" has too many ${depth > 0 ? "opening" : "closing"} parentheses.` + ], + details: `Depth "${depth}"` + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "InvalidParenthesisError" + }); } }; } }); -// node_modules/viem/_esm/utils/encoding/fromBytes.js -function bytesToBigInt(bytes, opts = {}) { - if (typeof opts.size !== "undefined") - assertSize(bytes, { size: opts.size }); - const hex = bytesToHex(bytes, opts); - return hexToBigInt(hex, opts); +// node_modules/abitype/dist/esm/human-readable/runtime/cache.js +function getParameterCacheKey(param, type, structs) { + let structKey = ""; + if (structs) + for (const struct of Object.entries(structs)) { + if (!struct) + continue; + let propertyKey = ""; + for (const property of struct[1]) { + propertyKey += `[${property.type}${property.name ? `:${property.name}` : ""}]`; + } + structKey += `(${struct[0]}{${propertyKey}})`; + } + if (type) + return `${type}:${param}${structKey}`; + return param; +} +var parameterCache; +var init_cache = __esm({ + "node_modules/abitype/dist/esm/human-readable/runtime/cache.js"() { + parameterCache = /* @__PURE__ */ new Map([ + // Unnamed + ["address", { type: "address" }], + ["bool", { type: "bool" }], + ["bytes", { type: "bytes" }], + ["bytes32", { type: "bytes32" }], + ["int", { type: "int256" }], + ["int256", { type: "int256" }], + ["string", { type: "string" }], + ["uint", { type: "uint256" }], + ["uint8", { type: "uint8" }], + ["uint16", { type: "uint16" }], + ["uint24", { type: "uint24" }], + ["uint32", { type: "uint32" }], + ["uint64", { type: "uint64" }], + ["uint96", { type: "uint96" }], + ["uint112", { type: "uint112" }], + ["uint160", { type: "uint160" }], + ["uint192", { type: "uint192" }], + ["uint256", { type: "uint256" }], + // Named + ["address owner", { type: "address", name: "owner" }], + ["address to", { type: "address", name: "to" }], + ["bool approved", { type: "bool", name: "approved" }], + ["bytes _data", { type: "bytes", name: "_data" }], + ["bytes data", { type: "bytes", name: "data" }], + ["bytes signature", { type: "bytes", name: "signature" }], + ["bytes32 hash", { type: "bytes32", name: "hash" }], + ["bytes32 r", { type: "bytes32", name: "r" }], + ["bytes32 root", { type: "bytes32", name: "root" }], + ["bytes32 s", { type: "bytes32", name: "s" }], + ["string name", { type: "string", name: "name" }], + ["string symbol", { type: "string", name: "symbol" }], + ["string tokenURI", { type: "string", name: "tokenURI" }], + ["uint tokenId", { type: "uint256", name: "tokenId" }], + ["uint8 v", { type: "uint8", name: "v" }], + ["uint256 balance", { type: "uint256", name: "balance" }], + ["uint256 tokenId", { type: "uint256", name: "tokenId" }], + ["uint256 value", { type: "uint256", name: "value" }], + // Indexed + [ + "event:address indexed from", + { type: "address", name: "from", indexed: true } + ], + ["event:address indexed to", { type: "address", name: "to", indexed: true }], + [ + "event:uint indexed tokenId", + { type: "uint256", name: "tokenId", indexed: true } + ], + [ + "event:uint256 indexed tokenId", + { type: "uint256", name: "tokenId", indexed: true } + ] + ]); + } +}); + +// node_modules/abitype/dist/esm/human-readable/runtime/utils.js +function parseSignature(signature, structs = {}) { + if (isFunctionSignature(signature)) + return parseFunctionSignature(signature, structs); + if (isEventSignature(signature)) + return parseEventSignature(signature, structs); + if (isErrorSignature(signature)) + return parseErrorSignature(signature, structs); + if (isConstructorSignature(signature)) + return parseConstructorSignature(signature, structs); + if (isFallbackSignature(signature)) + return parseFallbackSignature(signature); + if (isReceiveSignature(signature)) + return { + type: "receive", + stateMutability: "payable" + }; + throw new UnknownSignatureError({ signature }); } -function bytesToBool(bytes_, opts = {}) { - let bytes = bytes_; - if (typeof opts.size !== "undefined") { - assertSize(bytes, { size: opts.size }); - bytes = trim2(bytes); +function parseFunctionSignature(signature, structs = {}) { + const match = execFunctionSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "function" }); + const inputParams = splitParameters(match.parameters); + const inputs = []; + const inputLength = inputParams.length; + for (let i = 0; i < inputLength; i++) { + inputs.push(parseAbiParameter(inputParams[i], { + modifiers: functionModifiers, + structs, + type: "function" + })); } - if (bytes.length > 1 || bytes[0] > 1) - throw new InvalidBytesBooleanError(bytes); - return Boolean(bytes[0]); -} -function bytesToNumber(bytes, opts = {}) { - if (typeof opts.size !== "undefined") - assertSize(bytes, { size: opts.size }); - const hex = bytesToHex(bytes, opts); - return hexToNumber(hex, opts); -} -function bytesToString(bytes_, opts = {}) { - let bytes = bytes_; - if (typeof opts.size !== "undefined") { - assertSize(bytes, { size: opts.size }); - bytes = trim2(bytes, { dir: "right" }); + const outputs = []; + if (match.returns) { + const outputParams = splitParameters(match.returns); + const outputLength = outputParams.length; + for (let i = 0; i < outputLength; i++) { + outputs.push(parseAbiParameter(outputParams[i], { + modifiers: functionModifiers, + structs, + type: "function" + })); + } } - return new TextDecoder().decode(bytes); + return { + name: match.name, + type: "function", + stateMutability: match.stateMutability ?? "nonpayable", + inputs, + outputs + }; } -var init_fromBytes = __esm({ - "node_modules/viem/_esm/utils/encoding/fromBytes.js"() { - init_encoding(); - init_trim(); - init_fromHex(); - init_toHex(); - } -}); - -// node_modules/viem/_esm/utils/abi/decodeAbiParameters.js -function decodeAbiParameters(params, data) { - const bytes = typeof data === "string" ? hexToBytes(data) : data; - const cursor = createCursor(bytes); - if (size(bytes) === 0 && params.length > 0) - throw new AbiDecodingZeroDataError(); - if (size(data) && size(data) < 32) - throw new AbiDecodingDataSizeTooSmallError({ - data: typeof data === "string" ? data : bytesToHex(data), - params, - size: size(data) - }); - let consumed = 0; - const values = []; - for (let i = 0; i < params.length; ++i) { - const param = params[i]; - cursor.setPosition(consumed); - const [data2, consumed_] = decodeParameter(cursor, param, { - staticPosition: 0 - }); - consumed += consumed_; - values.push(data2); - } - return values; +function parseEventSignature(signature, structs = {}) { + const match = execEventSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "event" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) + abiParameters.push(parseAbiParameter(params[i], { + modifiers: eventModifiers, + structs, + type: "event" + })); + return { name: match.name, type: "event", inputs: abiParameters }; } -function decodeParameter(cursor, param, { staticPosition }) { - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents) { - const [length, type] = arrayComponents; - return decodeArray(cursor, { ...param, type }, { length, staticPosition }); - } - if (param.type === "tuple") - return decodeTuple(cursor, param, { staticPosition }); - if (param.type === "address") - return decodeAddress(cursor); - if (param.type === "bool") - return decodeBool(cursor); - if (param.type.startsWith("bytes")) - return decodeBytes(cursor, param, { staticPosition }); - if (param.type.startsWith("uint") || param.type.startsWith("int")) - return decodeNumber(cursor, param); - if (param.type === "string") - return decodeString(cursor, { staticPosition }); - throw new InvalidAbiDecodingTypeError(param.type, { - docsPath: "/docs/contract/decodeAbiParameters" - }); +function parseErrorSignature(signature, structs = {}) { + const match = execErrorSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "error" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) + abiParameters.push(parseAbiParameter(params[i], { structs, type: "error" })); + return { name: match.name, type: "error", inputs: abiParameters }; } -function decodeAddress(cursor) { - const value = cursor.readBytes(32); - return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]; +function parseConstructorSignature(signature, structs = {}) { + const match = execConstructorSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "constructor" }); + const params = splitParameters(match.parameters); + const abiParameters = []; + const length = params.length; + for (let i = 0; i < length; i++) + abiParameters.push(parseAbiParameter(params[i], { structs, type: "constructor" })); + return { + type: "constructor", + stateMutability: match.stateMutability ?? "nonpayable", + inputs: abiParameters + }; } -function decodeArray(cursor, param, { length, staticPosition }) { - if (!length) { - const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset; - const startOfData = start + sizeOfLength; - cursor.setPosition(start); - const length2 = bytesToNumber(cursor.readBytes(sizeOfLength)); - const dynamicChild = hasDynamicChild(param); - let consumed2 = 0; - const value2 = []; - for (let i = 0; i < length2; ++i) { - cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); - const [data, consumed_] = decodeParameter(cursor, param, { - staticPosition: startOfData - }); - consumed2 += consumed_; - value2.push(data); +function parseFallbackSignature(signature) { + const match = execFallbackSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "fallback" }); + return { + type: "fallback", + stateMutability: match.stateMutability ?? "nonpayable" + }; +} +function parseAbiParameter(param, options) { + const parameterCacheKey = getParameterCacheKey(param, options?.type, options?.structs); + if (parameterCache.has(parameterCacheKey)) + return parameterCache.get(parameterCacheKey); + const isTuple = isTupleRegex.test(param); + const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param); + if (!match) + throw new InvalidParameterError({ param }); + if (match.name && isSolidityKeyword(match.name)) + throw new SolidityProtectedKeywordError({ param, name: match.name }); + const name = match.name ? { name: match.name } : {}; + const indexed = match.modifier === "indexed" ? { indexed: true } : {}; + const structs = options?.structs ?? {}; + let type; + let components = {}; + if (isTuple) { + type = "tuple"; + const params = splitParameters(match.type); + const components_ = []; + const length = params.length; + for (let i = 0; i < length; i++) { + components_.push(parseAbiParameter(params[i], { structs })); } - cursor.setPosition(staticPosition + 32); - return [value2, 32]; + components = { components: components_ }; + } else if (match.type in structs) { + type = "tuple"; + components = { components: structs[match.type] }; + } else if (dynamicIntegerRegex.test(match.type)) { + type = `${match.type}256`; + } else { + type = match.type; + if (!(options?.type === "struct") && !isSolidityType(type)) + throw new UnknownSolidityTypeError({ type }); } - if (hasDynamicChild(param)) { - const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset; - const value2 = []; - for (let i = 0; i < length; ++i) { - cursor.setPosition(start + i * 32); - const [data] = decodeParameter(cursor, param, { - staticPosition: start + if (match.modifier) { + if (!options?.modifiers?.has?.(match.modifier)) + throw new InvalidModifierError({ + param, + type: options?.type, + modifier: match.modifier + }); + if (functionModifiers.has(match.modifier) && !isValidDataLocation(type, !!match.array)) + throw new InvalidFunctionModifierError({ + param, + type: options?.type, + modifier: match.modifier }); - value2.push(data); - } - cursor.setPosition(staticPosition + 32); - return [value2, 32]; - } - let consumed = 0; - const value = []; - for (let i = 0; i < length; ++i) { - const [data, consumed_] = decodeParameter(cursor, param, { - staticPosition: staticPosition + consumed - }); - consumed += consumed_; - value.push(data); } - return [value, consumed]; -} -function decodeBool(cursor) { - return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]; + const abiParameter = { + type: `${type}${match.array ?? ""}`, + ...name, + ...indexed, + ...components + }; + parameterCache.set(parameterCacheKey, abiParameter); + return abiParameter; } -function decodeBytes(cursor, param, { staticPosition }) { - const [_, size5] = param.type.split("bytes"); - if (!size5) { - const offset = bytesToNumber(cursor.readBytes(32)); - cursor.setPosition(staticPosition + offset); - const length = bytesToNumber(cursor.readBytes(32)); - if (length === 0) { - cursor.setPosition(staticPosition + 32); - return ["0x", 32]; +function splitParameters(params, result = [], current = "", depth = 0) { + const length = params.trim().length; + for (let i = 0; i < length; i++) { + const char = params[i]; + const tail = params.slice(i + 1); + switch (char) { + case ",": + return depth === 0 ? splitParameters(tail, [...result, current.trim()]) : splitParameters(tail, result, `${current}${char}`, depth); + case "(": + return splitParameters(tail, result, `${current}${char}`, depth + 1); + case ")": + return splitParameters(tail, result, `${current}${char}`, depth - 1); + default: + return splitParameters(tail, result, `${current}${char}`, depth); } - const data = cursor.readBytes(length); - cursor.setPosition(staticPosition + 32); - return [bytesToHex(data), 32]; } - const value = bytesToHex(cursor.readBytes(Number.parseInt(size5), 32)); - return [value, 32]; + if (current === "") + return result; + if (depth !== 0) + throw new InvalidParenthesisError({ current, depth }); + result.push(current.trim()); + return result; } -function decodeNumber(cursor, param) { - const signed = param.type.startsWith("int"); - const size5 = Number.parseInt(param.type.split("int")[1] || "256"); - const value = cursor.readBytes(32); - return [ - size5 > 48 ? bytesToBigInt(value, { signed }) : bytesToNumber(value, { signed }), - 32 - ]; +function isSolidityType(type) { + return type === "address" || type === "bool" || type === "function" || type === "string" || bytesRegex.test(type) || integerRegex.test(type); } -function decodeTuple(cursor, param, { staticPosition }) { - const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name); - const value = hasUnnamedChild ? [] : {}; - let consumed = 0; - if (hasDynamicChild(param)) { - const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset; - for (let i = 0; i < param.components.length; ++i) { - const component = param.components[i]; - cursor.setPosition(start + consumed); - const [data, consumed_] = decodeParameter(cursor, component, { - staticPosition: start +function isSolidityKeyword(name) { + return name === "address" || name === "bool" || name === "function" || name === "string" || name === "tuple" || bytesRegex.test(name) || integerRegex.test(name) || protectedKeywordsRegex.test(name); +} +function isValidDataLocation(type, isArray2) { + return isArray2 || type === "bytes" || type === "string" || type === "tuple"; +} +var abiParameterWithoutTupleRegex, abiParameterWithTupleRegex, dynamicIntegerRegex, protectedKeywordsRegex; +var init_utils = __esm({ + "node_modules/abitype/dist/esm/human-readable/runtime/utils.js"() { + init_regex(); + init_abiItem(); + init_abiParameter(); + init_signature(); + init_splitParameters(); + init_cache(); + init_signatures(); + abiParameterWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; + abiParameterWithTupleRegex = /^\((?.+?)\)(?(?:\[\d*?\])+?)?(?:\s(?calldata|indexed|memory|storage{1}))?(?:\s(?[a-zA-Z$_][a-zA-Z0-9$_]*))?$/; + dynamicIntegerRegex = /^u?int$/; + protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/; + } +}); + +// node_modules/abitype/dist/esm/human-readable/runtime/structs.js +function parseStructs(signatures) { + const shallowStructs = {}; + const signaturesLength = signatures.length; + for (let i = 0; i < signaturesLength; i++) { + const signature = signatures[i]; + if (!isStructSignature(signature)) + continue; + const match = execStructSignature(signature); + if (!match) + throw new InvalidSignatureError({ signature, type: "struct" }); + const properties = match.properties.split(";"); + const components = []; + const propertiesLength = properties.length; + for (let k2 = 0; k2 < propertiesLength; k2++) { + const property = properties[k2]; + const trimmed = property.trim(); + if (!trimmed) + continue; + const abiParameter = parseAbiParameter(trimmed, { + type: "struct" }); - consumed += consumed_; - value[hasUnnamedChild ? i : component?.name] = data; + components.push(abiParameter); } - cursor.setPosition(staticPosition + 32); - return [value, 32]; + if (!components.length) + throw new InvalidStructSignatureError({ signature }); + shallowStructs[match.name] = components; } - for (let i = 0; i < param.components.length; ++i) { - const component = param.components[i]; - const [data, consumed_] = decodeParameter(cursor, component, { - staticPosition - }); - value[hasUnnamedChild ? i : component?.name] = data; - consumed += consumed_; + const resolvedStructs = {}; + const entries = Object.entries(shallowStructs); + const entriesLength = entries.length; + for (let i = 0; i < entriesLength; i++) { + const [name, parameters] = entries[i]; + resolvedStructs[name] = resolveStructs(parameters, shallowStructs); } - return [value, consumed]; + return resolvedStructs; } -function decodeString(cursor, { staticPosition }) { - const offset = bytesToNumber(cursor.readBytes(32)); - const start = staticPosition + offset; - cursor.setPosition(start); - const length = bytesToNumber(cursor.readBytes(32)); - if (length === 0) { - cursor.setPosition(staticPosition + 32); - return ["", 32]; +function resolveStructs(abiParameters, structs, ancestors = /* @__PURE__ */ new Set()) { + const components = []; + const length = abiParameters.length; + for (let i = 0; i < length; i++) { + const abiParameter = abiParameters[i]; + const isTuple = isTupleRegex.test(abiParameter.type); + if (isTuple) + components.push(abiParameter); + else { + const match = execTyped(typeWithoutTupleRegex, abiParameter.type); + if (!match?.type) + throw new InvalidAbiTypeParameterError({ abiParameter }); + const { array, type } = match; + if (type in structs) { + if (ancestors.has(type)) + throw new CircularReferenceError({ type }); + components.push({ + ...abiParameter, + type: `tuple${array ?? ""}`, + components: resolveStructs(structs[type] ?? [], structs, /* @__PURE__ */ new Set([...ancestors, type])) + }); + } else { + if (isSolidityType(type)) + components.push(abiParameter); + else + throw new UnknownTypeError({ type }); + } + } } - const data = cursor.readBytes(length, 32); - const value = bytesToString(trim2(data)); - cursor.setPosition(staticPosition + 32); - return [value, 32]; -} -function hasDynamicChild(param) { - const { type } = param; - if (type === "string") - return true; - if (type === "bytes") - return true; - if (type.endsWith("[]")) - return true; - if (type === "tuple") - return param.components?.some(hasDynamicChild); - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] })) - return true; - return false; + return components; } -var sizeOfLength, sizeOfOffset; -var init_decodeAbiParameters = __esm({ - "node_modules/viem/_esm/utils/abi/decodeAbiParameters.js"() { - init_abi(); - init_getAddress(); - init_cursor2(); - init_size(); - init_slice(); - init_trim(); - init_fromBytes(); - init_toBytes(); - init_toHex(); - init_encodeAbiParameters(); - sizeOfLength = 32; - sizeOfOffset = 32; +var typeWithoutTupleRegex; +var init_structs = __esm({ + "node_modules/abitype/dist/esm/human-readable/runtime/structs.js"() { + init_regex(); + init_abiItem(); + init_abiParameter(); + init_signature(); + init_struct(); + init_signatures(); + init_utils(); + typeWithoutTupleRegex = /^(?[a-zA-Z$_][a-zA-Z0-9$_]*)(?(?:\[\d*?\])+?)?$/; + } +}); + +// node_modules/abitype/dist/esm/human-readable/parseAbi.js +function parseAbi(signatures) { + const structs = parseStructs(signatures); + const abi4 = []; + const length = signatures.length; + for (let i = 0; i < length; i++) { + const signature = signatures[i]; + if (isStructSignature(signature)) + continue; + abi4.push(parseSignature(signature, structs)); + } + return abi4; +} +var init_parseAbi = __esm({ + "node_modules/abitype/dist/esm/human-readable/parseAbi.js"() { + init_signatures(); + init_structs(); + init_utils(); } }); -// node_modules/viem/_esm/utils/abi/decodeErrorResult.js -function decodeErrorResult(parameters) { - const { abi: abi4, data } = parameters; - const signature = slice(data, 0, 4); - if (signature === "0x") - throw new AbiDecodingZeroDataError(); - const abi_ = [...abi4 || [], solidityError, solidityPanic]; - const abiItem = abi_.find((x2) => x2.type === "error" && signature === toFunctionSelector(formatAbiItem2(x2))); +// node_modules/abitype/dist/esm/human-readable/parseAbiItem.js +function parseAbiItem(signature) { + let abiItem; + if (typeof signature === "string") + abiItem = parseSignature(signature); + else { + const structs = parseStructs(signature); + const length = signature.length; + for (let i = 0; i < length; i++) { + const signature_ = signature[i]; + if (isStructSignature(signature_)) + continue; + abiItem = parseSignature(signature_, structs); + break; + } + } if (!abiItem) - throw new AbiErrorSignatureNotFoundError(signature, { - docsPath: "/docs/contract/decodeErrorResult" - }); - return { - abiItem, - args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : void 0, - errorName: abiItem.name - }; + throw new InvalidAbiItemError({ signature }); + return abiItem; } -var init_decodeErrorResult = __esm({ - "node_modules/viem/_esm/utils/abi/decodeErrorResult.js"() { - init_solidity(); - init_abi(); - init_slice(); - init_toFunctionSelector(); - init_decodeAbiParameters(); - init_formatAbiItem2(); +var init_parseAbiItem = __esm({ + "node_modules/abitype/dist/esm/human-readable/parseAbiItem.js"() { + init_abiItem(); + init_signatures(); + init_structs(); + init_utils(); } }); -// node_modules/viem/_esm/utils/stringify.js -var stringify; -var init_stringify = __esm({ - "node_modules/viem/_esm/utils/stringify.js"() { - stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => { - const value2 = typeof value_ === "bigint" ? value_.toString() : value_; - return typeof replacer === "function" ? replacer(key, value2) : value2; - }, space); +// node_modules/abitype/dist/esm/human-readable/parseAbiParameters.js +function parseAbiParameters(params) { + const abiParameters = []; + if (typeof params === "string") { + const parameters = splitParameters(params); + const length = parameters.length; + for (let i = 0; i < length; i++) { + abiParameters.push(parseAbiParameter(parameters[i], { modifiers })); + } + } else { + const structs = parseStructs(params); + const length = params.length; + for (let i = 0; i < length; i++) { + const signature = params[i]; + if (isStructSignature(signature)) + continue; + const parameters = splitParameters(signature); + const length2 = parameters.length; + for (let k2 = 0; k2 < length2; k2++) { + abiParameters.push(parseAbiParameter(parameters[k2], { modifiers, structs })); + } + } } -}); - -// node_modules/viem/_esm/utils/abi/formatAbiItemWithArgs.js -function formatAbiItemWithArgs({ abiItem, args, includeFunctionName = true, includeName = false }) { - if (!("name" in abiItem)) - return; - if (!("inputs" in abiItem)) - return; - if (!abiItem.inputs) - return; - return `${includeFunctionName ? abiItem.name : ""}(${abiItem.inputs.map((input, i) => `${includeName && input.name ? `${input.name}: ` : ""}${typeof args[i] === "object" ? stringify(args[i]) : args[i]}`).join(", ")})`; + if (abiParameters.length === 0) + throw new InvalidAbiParametersError({ params }); + return abiParameters; } -var init_formatAbiItemWithArgs = __esm({ - "node_modules/viem/_esm/utils/abi/formatAbiItemWithArgs.js"() { - init_stringify(); +var init_parseAbiParameters = __esm({ + "node_modules/abitype/dist/esm/human-readable/parseAbiParameters.js"() { + init_abiParameter(); + init_signatures(); + init_structs(); + init_utils(); + init_utils(); } }); -// node_modules/viem/_esm/constants/unit.js -var etherUnits, gweiUnits; -var init_unit = __esm({ - "node_modules/viem/_esm/constants/unit.js"() { - etherUnits = { - gwei: 9, - wei: 18 - }; - gweiUnits = { - ether: -9, - wei: 9 - }; +// node_modules/abitype/dist/esm/exports/index.js +var init_exports = __esm({ + "node_modules/abitype/dist/esm/exports/index.js"() { + init_formatAbiItem(); + init_parseAbi(); + init_parseAbiItem(); + init_parseAbiParameters(); } }); -// node_modules/viem/_esm/utils/unit/formatUnits.js -function formatUnits(value, decimals) { - let display = value.toString(); - const negative = display.startsWith("-"); - if (negative) - display = display.slice(1); - display = display.padStart(decimals, "0"); - let [integer, fraction] = [ - display.slice(0, display.length - decimals), - display.slice(display.length - decimals) - ]; - fraction = fraction.replace(/(0+)$/, ""); - return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`; +// node_modules/viem/_esm/utils/abi/formatAbiItem.js +function formatAbiItem2(abiItem, { includeName = false } = {}) { + if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error") + throw new InvalidDefinitionTypeError(abiItem.type); + return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`; } -var init_formatUnits = __esm({ - "node_modules/viem/_esm/utils/unit/formatUnits.js"() { - } -}); - -// node_modules/viem/_esm/utils/unit/formatEther.js -function formatEther(wei, unit = "wei") { - return formatUnits(wei, etherUnits[unit]); +function formatAbiParams(params, { includeName = false } = {}) { + if (!params) + return ""; + return params.map((param) => formatAbiParam(param, { includeName })).join(includeName ? ", " : ","); } -var init_formatEther = __esm({ - "node_modules/viem/_esm/utils/unit/formatEther.js"() { - init_unit(); - init_formatUnits(); +function formatAbiParam(param, { includeName }) { + if (param.type.startsWith("tuple")) { + return `(${formatAbiParams(param.components, { includeName })})${param.type.slice("tuple".length)}`; } -}); - -// node_modules/viem/_esm/utils/unit/formatGwei.js -function formatGwei(wei, unit = "wei") { - return formatUnits(wei, gweiUnits[unit]); + return param.type + (includeName && param.name ? ` ${param.name}` : ""); } -var init_formatGwei = __esm({ - "node_modules/viem/_esm/utils/unit/formatGwei.js"() { - init_unit(); - init_formatUnits(); +var init_formatAbiItem2 = __esm({ + "node_modules/viem/_esm/utils/abi/formatAbiItem.js"() { + init_abi(); } }); -// node_modules/viem/_esm/errors/stateOverride.js -function prettyStateMapping(stateMapping) { - return stateMapping.reduce((pretty, { slot, value }) => { - return `${pretty} ${slot}: ${value} -`; - }, ""); -} -function prettyStateOverride(stateOverride) { - return stateOverride.reduce((pretty, { address, ...state }) => { - let val = `${pretty} ${address}: -`; - if (state.nonce) - val += ` nonce: ${state.nonce} -`; - if (state.balance) - val += ` balance: ${state.balance} -`; - if (state.code) - val += ` code: ${state.code} -`; - if (state.state) { - val += " state:\n"; - val += prettyStateMapping(state.state); - } - if (state.stateDiff) { - val += " stateDiff:\n"; - val += prettyStateMapping(state.stateDiff); - } - return val; - }, " State Override:\n").slice(0, -1); +// node_modules/viem/_esm/utils/data/isHex.js +function isHex(value, { strict = true } = {}) { + if (!value) + return false; + if (typeof value !== "string") + return false; + return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x"); } -var AccountStateConflictError, StateAssignmentConflictError; -var init_stateOverride = __esm({ - "node_modules/viem/_esm/errors/stateOverride.js"() { - init_base(); - AccountStateConflictError = class extends BaseError2 { - constructor({ address }) { - super(`State for account "${address}" is set multiple times.`, { - name: "AccountStateConflictError" - }); - } - }; - StateAssignmentConflictError = class extends BaseError2 { - constructor() { - super("state and stateDiff are set on the same account.", { - name: "StateAssignmentConflictError" - }); - } - }; +var init_isHex = __esm({ + "node_modules/viem/_esm/utils/data/isHex.js"() { } }); -// node_modules/viem/_esm/errors/transaction.js -function prettyPrint(args) { - const entries = Object.entries(args).map(([key, value]) => { - if (value === void 0 || value === false) - return null; - return [key, value]; - }).filter(Boolean); - const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0); - return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n"); +// node_modules/viem/_esm/utils/data/size.js +function size(value) { + if (isHex(value, { strict: false })) + return Math.ceil((value.length - 2) / 2); + return value.length; } -var FeeConflictError, InvalidLegacyVError, InvalidSerializableTransactionError, InvalidStorageKeySizeError, TransactionExecutionError, TransactionNotFoundError, TransactionReceiptNotFoundError, WaitForTransactionReceiptTimeoutError; -var init_transaction = __esm({ - "node_modules/viem/_esm/errors/transaction.js"() { - init_formatEther(); - init_formatGwei(); - init_base(); - FeeConflictError = class extends BaseError2 { - constructor() { - super([ - "Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.", - "Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others." - ].join("\n"), { name: "FeeConflictError" }); - } - }; - InvalidLegacyVError = class extends BaseError2 { - constructor({ v }) { - super(`Invalid \`v\` value "${v}". Expected 27 or 28.`, { - name: "InvalidLegacyVError" - }); - } - }; - InvalidSerializableTransactionError = class extends BaseError2 { - constructor({ transaction }) { - super("Cannot infer a transaction type from provided transaction.", { - metaMessages: [ - "Provided Transaction:", - "{", - prettyPrint(transaction), - "}", - "", - "To infer the type, either provide:", - "- a `type` to the Transaction, or", - "- an EIP-1559 Transaction with `maxFeePerGas`, or", - "- an EIP-2930 Transaction with `gasPrice` & `accessList`, or", - "- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or", - "- an EIP-7702 Transaction with `authorizationList`, or", - "- a Legacy Transaction with `gasPrice`" - ], - name: "InvalidSerializableTransactionError" - }); - } - }; - InvalidStorageKeySizeError = class extends BaseError2 { - constructor({ storageKey }) { - super(`Size for storage key "${storageKey}" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: "InvalidStorageKeySizeError" }); - } - }; - TransactionExecutionError = class extends BaseError2 { - constructor(cause, { account, docsPath: docsPath6, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value }) { - const prettyArgs = prettyPrint({ - chain: chain && `${chain?.name} (id: ${chain?.id})`, - from: account?.address, - to: to2, - value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, - data, - gas, - gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, - maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, - maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, - nonce - }); - super(cause.shortMessage, { - cause, - docsPath: docsPath6, - metaMessages: [ - ...cause.metaMessages ? [...cause.metaMessages, " "] : [], - "Request Arguments:", - prettyArgs - ].filter(Boolean), - name: "TransactionExecutionError" - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.cause = cause; - } - }; - TransactionNotFoundError = class extends BaseError2 { - constructor({ blockHash, blockNumber, blockTag, hash: hash2, index: index2 }) { - let identifier = "Transaction"; - if (blockTag && index2 !== void 0) - identifier = `Transaction at block time "${blockTag}" at index "${index2}"`; - if (blockHash && index2 !== void 0) - identifier = `Transaction at block hash "${blockHash}" at index "${index2}"`; - if (blockNumber && index2 !== void 0) - identifier = `Transaction at block number "${blockNumber}" at index "${index2}"`; - if (hash2) - identifier = `Transaction with hash "${hash2}"`; - super(`${identifier} could not be found.`, { - name: "TransactionNotFoundError" - }); - } - }; - TransactionReceiptNotFoundError = class extends BaseError2 { - constructor({ hash: hash2 }) { - super(`Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`, { - name: "TransactionReceiptNotFoundError" - }); - } - }; - WaitForTransactionReceiptTimeoutError = class extends BaseError2 { - constructor({ hash: hash2 }) { - super(`Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`, { name: "WaitForTransactionReceiptTimeoutError" }); - } - }; +var init_size = __esm({ + "node_modules/viem/_esm/utils/data/size.js"() { + init_isHex(); } }); -// node_modules/viem/_esm/errors/utils.js -var getContractAddress, getUrl; -var init_utils3 = __esm({ - "node_modules/viem/_esm/errors/utils.js"() { - getContractAddress = (address) => address; - getUrl = (url2) => url2; +// node_modules/viem/_esm/errors/version.js +var version2; +var init_version2 = __esm({ + "node_modules/viem/_esm/errors/version.js"() { + version2 = "2.24.1"; } }); -// node_modules/viem/_esm/errors/contract.js -var CallExecutionError, ContractFunctionExecutionError, ContractFunctionRevertedError, ContractFunctionZeroDataError, CounterfactualDeploymentFailedError, RawContractError; -var init_contract = __esm({ - "node_modules/viem/_esm/errors/contract.js"() { - init_parseAccount(); - init_solidity(); - init_decodeErrorResult(); - init_formatAbiItem2(); - init_formatAbiItemWithArgs(); - init_getAbiItem(); - init_formatEther(); - init_formatGwei(); - init_abi(); - init_base(); - init_stateOverride(); - init_transaction(); - init_utils3(); - CallExecutionError = class extends BaseError2 { - constructor(cause, { account: account_, docsPath: docsPath6, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value, stateOverride }) { - const account = account_ ? parseAccount(account_) : void 0; - let prettyArgs = prettyPrint({ - from: account?.address, - to: to2, - value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, - data, - gas, - gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, - maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, - maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, - nonce - }); - if (stateOverride) { - prettyArgs += ` -${prettyStateOverride(stateOverride)}`; - } - super(cause.shortMessage, { - cause, - docsPath: docsPath6, - metaMessages: [ - ...cause.metaMessages ? [...cause.metaMessages, " "] : [], - "Raw Call Arguments:", - prettyArgs - ].filter(Boolean), - name: "CallExecutionError" - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.cause = cause; - } +// node_modules/viem/_esm/errors/base.js +function walk(err, fn2) { + if (fn2?.(err)) + return err; + if (err && typeof err === "object" && "cause" in err && err.cause !== void 0) + return walk(err.cause, fn2); + return fn2 ? null : err; +} +var errorConfig, BaseError2; +var init_base = __esm({ + "node_modules/viem/_esm/errors/base.js"() { + init_version2(); + errorConfig = { + getDocsUrl: ({ docsBaseUrl, docsPath: docsPath6 = "", docsSlug }) => docsPath6 ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath6}${docsSlug ? `#${docsSlug}` : ""}` : void 0, + version: `viem@${version2}` }; - ContractFunctionExecutionError = class extends BaseError2 { - constructor(cause, { abi: abi4, args, contractAddress, docsPath: docsPath6, functionName, sender }) { - const abiItem = getAbiItem({ abi: abi4, args, name: functionName }); - const formattedArgs = abiItem ? formatAbiItemWithArgs({ - abiItem, - args, - includeFunctionName: false, - includeName: false - }) : void 0; - const functionWithParams = abiItem ? formatAbiItem2(abiItem, { includeName: true }) : void 0; - const prettyArgs = prettyPrint({ - address: contractAddress && getContractAddress(contractAddress), - function: functionWithParams, - args: formattedArgs && formattedArgs !== "()" && `${[...Array(functionName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`, - sender - }); - super(cause.shortMessage || `An unknown error occurred while executing the contract function "${functionName}".`, { - cause, - docsPath: docsPath6, - metaMessages: [ - ...cause.metaMessages ? [...cause.metaMessages, " "] : [], - prettyArgs && "Contract Call:", - prettyArgs - ].filter(Boolean), - name: "ContractFunctionExecutionError" - }); - Object.defineProperty(this, "abi", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "args", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "contractAddress", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "formattedArgs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "functionName", { + BaseError2 = class _BaseError extends Error { + constructor(shortMessage, args = {}) { + const details = (() => { + if (args.cause instanceof _BaseError) + return args.cause.details; + if (args.cause?.message) + return args.cause.message; + return args.details; + })(); + const docsPath6 = (() => { + if (args.cause instanceof _BaseError) + return args.cause.docsPath || args.docsPath; + return args.docsPath; + })(); + const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath: docsPath6 }); + const message = [ + shortMessage || "An error occurred.", + "", + ...args.metaMessages ? [...args.metaMessages, ""] : [], + ...docsUrl ? [`Docs: ${docsUrl}`] : [], + ...details ? [`Details: ${details}`] : [], + ...errorConfig.version ? [`Version: ${errorConfig.version}`] : [] + ].join("\n"); + super(message, args.cause ? { cause: args.cause } : void 0); + Object.defineProperty(this, "details", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "sender", { + Object.defineProperty(this, "docsPath", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.abi = abi4; - this.args = args; - this.cause = cause; - this.contractAddress = contractAddress; - this.functionName = functionName; - this.sender = sender; - } - }; - ContractFunctionRevertedError = class extends BaseError2 { - constructor({ abi: abi4, data, functionName, message }) { - let cause; - let decodedData = void 0; - let metaMessages; - let reason; - if (data && data !== "0x") { - try { - decodedData = decodeErrorResult({ abi: abi4, data }); - const { abiItem, errorName, args: errorArgs } = decodedData; - if (errorName === "Error") { - reason = errorArgs[0]; - } else if (errorName === "Panic") { - const [firstArg] = errorArgs; - reason = panicReasons[firstArg]; - } else { - const errorWithParams = abiItem ? formatAbiItem2(abiItem, { includeName: true }) : void 0; - const formattedArgs = abiItem && errorArgs ? formatAbiItemWithArgs({ - abiItem, - args: errorArgs, - includeFunctionName: false, - includeName: false - }) : void 0; - metaMessages = [ - errorWithParams ? `Error: ${errorWithParams}` : "", - formattedArgs && formattedArgs !== "()" ? ` ${[...Array(errorName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : "" - ]; - } - } catch (err) { - cause = err; - } - } else if (message) - reason = message; - let signature; - if (cause instanceof AbiErrorSignatureNotFoundError) { - signature = cause.signature; - metaMessages = [ - `Unable to decode signature "${signature}" as it was not found on the provided ABI.`, - "Make sure you are using the correct ABI and that the error exists on it.", - `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.` - ]; - } - super(reason && reason !== "execution reverted" || signature ? [ - `The contract function "${functionName}" reverted with the following ${signature ? "signature" : "reason"}:`, - reason || signature - ].join("\n") : `The contract function "${functionName}" reverted.`, { - cause, - metaMessages, - name: "ContractFunctionRevertedError" - }); - Object.defineProperty(this, "data", { + Object.defineProperty(this, "metaMessages", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "raw", { + Object.defineProperty(this, "shortMessage", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "reason", { + Object.defineProperty(this, "version", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "signature", { + Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: void 0 - }); - this.data = decodedData; - this.raw = data; - this.reason = reason; - this.signature = signature; - } - }; - ContractFunctionZeroDataError = class extends BaseError2 { - constructor({ functionName }) { - super(`The contract function "${functionName}" returned no data ("0x").`, { - metaMessages: [ - "This could be due to any of the following:", - ` - The contract does not have the function "${functionName}",`, - " - The parameters passed to the contract function may be invalid, or", - " - The address is not a contract." - ], - name: "ContractFunctionZeroDataError" - }); - } - }; - CounterfactualDeploymentFailedError = class extends BaseError2 { - constructor({ factory }) { - super(`Deployment for counterfactual contract call failed${factory ? ` for factory "${factory}".` : ""}`, { - metaMessages: [ - "Please ensure:", - "- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).", - "- The `factoryData` is a valid encoded function call for contract deployment function on the factory." - ], - name: "CounterfactualDeploymentFailedError" + value: "BaseError" }); + this.details = details; + this.docsPath = docsPath6; + this.metaMessages = args.metaMessages; + this.name = args.name ?? this.name; + this.shortMessage = shortMessage; + this.version = version2; } - }; - RawContractError = class extends BaseError2 { - constructor({ data, message }) { - super(message || "", { name: "RawContractError" }); - Object.defineProperty(this, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 3 - }); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.data = data; + walk(fn2) { + return walk(this, fn2); } }; } }); -// node_modules/viem/_esm/errors/request.js -var HttpRequestError, RpcRequestError, TimeoutError; -var init_request = __esm({ - "node_modules/viem/_esm/errors/request.js"() { - init_stringify(); +// node_modules/viem/_esm/errors/abi.js +var AbiConstructorNotFoundError, AbiConstructorParamsNotFoundError, AbiDecodingDataSizeTooSmallError, AbiDecodingZeroDataError, AbiEncodingArrayLengthMismatchError, AbiEncodingBytesSizeMismatchError, AbiEncodingLengthMismatchError, AbiErrorSignatureNotFoundError, AbiEventSignatureEmptyTopicsError, AbiEventSignatureNotFoundError, AbiEventNotFoundError, AbiFunctionNotFoundError, AbiFunctionOutputsNotFoundError, AbiItemAmbiguityError, BytesSizeMismatchError, DecodeLogDataMismatch, DecodeLogTopicsMismatch, InvalidAbiEncodingTypeError, InvalidAbiDecodingTypeError, InvalidArrayError, InvalidDefinitionTypeError; +var init_abi = __esm({ + "node_modules/viem/_esm/errors/abi.js"() { + init_formatAbiItem2(); + init_size(); init_base(); - init_utils3(); - HttpRequestError = class extends BaseError2 { - constructor({ body, cause, details, headers, status, url: url2 }) { - super("HTTP request failed.", { - cause, - details, - metaMessages: [ - status && `Status: ${status}`, - `URL: ${getUrl(url2)}`, - body && `Request body: ${stringify(body)}` - ].filter(Boolean), - name: "HttpRequestError" - }); - Object.defineProperty(this, "body", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "headers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "url", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + AbiConstructorNotFoundError = class extends BaseError2 { + constructor({ docsPath: docsPath6 }) { + super([ + "A constructor was not found on the ABI.", + "Make sure you are using the correct ABI and that the constructor exists on it." + ].join("\n"), { + docsPath: docsPath6, + name: "AbiConstructorNotFoundError" }); - this.body = body; - this.headers = headers; - this.status = status; - this.url = url2; } }; - RpcRequestError = class extends BaseError2 { - constructor({ body, error, url: url2 }) { - super("RPC Request failed.", { - cause: error, - details: error.message, - metaMessages: [`URL: ${getUrl(url2)}`, `Request body: ${stringify(body)}`], - name: "RpcRequestError" + AbiConstructorParamsNotFoundError = class extends BaseError2 { + constructor({ docsPath: docsPath6 }) { + super([ + "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.", + "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists." + ].join("\n"), { + docsPath: docsPath6, + name: "AbiConstructorParamsNotFoundError" }); - Object.defineProperty(this, "code", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + } + }; + AbiDecodingDataSizeTooSmallError = class extends BaseError2 { + constructor({ data, params, size: size5 }) { + super([`Data size of ${size5} bytes is too small for given parameters.`].join("\n"), { + metaMessages: [ + `Params: (${formatAbiParams(params, { includeName: true })})`, + `Data: ${data} (${size5} bytes)` + ], + name: "AbiDecodingDataSizeTooSmallError" }); Object.defineProperty(this, "data", { enumerable: true, @@ -31748,20704 +17509,31634 @@ var init_request = __esm({ writable: true, value: void 0 }); - this.code = error.code; - this.data = error.data; - } - }; - TimeoutError = class extends BaseError2 { - constructor({ body, url: url2 }) { - super("The request took too long to respond.", { - details: "The request timed out.", - metaMessages: [`URL: ${getUrl(url2)}`, `Request body: ${stringify(body)}`], - name: "TimeoutError" - }); - } - }; - } -}); - -// node_modules/viem/_esm/errors/rpc.js -var unknownErrorCode, RpcError, ProviderRpcError, ParseRpcError, InvalidRequestRpcError, MethodNotFoundRpcError, InvalidParamsRpcError, InternalRpcError, InvalidInputRpcError, ResourceNotFoundRpcError, ResourceUnavailableRpcError, TransactionRejectedRpcError, MethodNotSupportedRpcError, LimitExceededRpcError, JsonRpcVersionUnsupportedError, UserRejectedRequestError, UnauthorizedProviderError, UnsupportedProviderMethodError, ProviderDisconnectedError, ChainDisconnectedError, SwitchChainError, UnknownRpcError; -var init_rpc = __esm({ - "node_modules/viem/_esm/errors/rpc.js"() { - init_base(); - init_request(); - unknownErrorCode = -1; - RpcError = class extends BaseError2 { - constructor(cause, { code, docsPath: docsPath6, metaMessages, name, shortMessage }) { - super(shortMessage, { - cause, - docsPath: docsPath6, - metaMessages: metaMessages || cause?.metaMessages, - name: name || "RpcError" - }); - Object.defineProperty(this, "code", { + Object.defineProperty(this, "params", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.name = name || cause.name; - this.code = cause instanceof RpcRequestError ? cause.code : code ?? unknownErrorCode; - } - }; - ProviderRpcError = class extends RpcError { - constructor(cause, options) { - super(cause, options); - Object.defineProperty(this, "data", { + Object.defineProperty(this, "size", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.data = options.data; - } - }; - ParseRpcError = class _ParseRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: _ParseRpcError.code, - name: "ParseRpcError", - shortMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text." - }); - } - }; - Object.defineProperty(ParseRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32700 - }); - InvalidRequestRpcError = class _InvalidRequestRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: _InvalidRequestRpcError.code, - name: "InvalidRequestRpcError", - shortMessage: "JSON is not a valid request object." - }); + this.data = data; + this.params = params; + this.size = size5; } }; - Object.defineProperty(InvalidRequestRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32600 - }); - MethodNotFoundRpcError = class _MethodNotFoundRpcError extends RpcError { - constructor(cause, { method } = {}) { - super(cause, { - code: _MethodNotFoundRpcError.code, - name: "MethodNotFoundRpcError", - shortMessage: `The method${method ? ` "${method}"` : ""} does not exist / is not available.` + AbiDecodingZeroDataError = class extends BaseError2 { + constructor() { + super('Cannot decode zero data ("0x") with ABI parameters.', { + name: "AbiDecodingZeroDataError" }); } }; - Object.defineProperty(MethodNotFoundRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32601 - }); - InvalidParamsRpcError = class _InvalidParamsRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: _InvalidParamsRpcError.code, - name: "InvalidParamsRpcError", - shortMessage: [ - "Invalid parameters were provided to the RPC method.", - "Double check you have provided the correct parameters." - ].join("\n") - }); + AbiEncodingArrayLengthMismatchError = class extends BaseError2 { + constructor({ expectedLength, givenLength, type }) { + super([ + `ABI encoding array length mismatch for type ${type}.`, + `Expected length: ${expectedLength}`, + `Given length: ${givenLength}` + ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" }); } }; - Object.defineProperty(InvalidParamsRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32602 - }); - InternalRpcError = class _InternalRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: _InternalRpcError.code, - name: "InternalRpcError", - shortMessage: "An internal error was received." - }); + AbiEncodingBytesSizeMismatchError = class extends BaseError2 { + constructor({ expectedSize, value }) { + super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); } }; - Object.defineProperty(InternalRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32603 - }); - InvalidInputRpcError = class _InvalidInputRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: _InvalidInputRpcError.code, - name: "InvalidInputRpcError", - shortMessage: [ - "Missing or invalid parameters.", - "Double check you have provided the correct parameters." - ].join("\n") - }); + AbiEncodingLengthMismatchError = class extends BaseError2 { + constructor({ expectedLength, givenLength }) { + super([ + "ABI encoding params/values length mismatch.", + `Expected length (params): ${expectedLength}`, + `Given length (values): ${givenLength}` + ].join("\n"), { name: "AbiEncodingLengthMismatchError" }); } }; - Object.defineProperty(InvalidInputRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32e3 - }); - ResourceNotFoundRpcError = class _ResourceNotFoundRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: _ResourceNotFoundRpcError.code, - name: "ResourceNotFoundRpcError", - shortMessage: "Requested resource not found." + AbiErrorSignatureNotFoundError = class extends BaseError2 { + constructor(signature, { docsPath: docsPath6 }) { + super([ + `Encoded error signature "${signature}" not found on ABI.`, + "Make sure you are using the correct ABI and that the error exists on it.", + `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.` + ].join("\n"), { + docsPath: docsPath6, + name: "AbiErrorSignatureNotFoundError" }); - Object.defineProperty(this, "name", { + Object.defineProperty(this, "signature", { enumerable: true, configurable: true, writable: true, - value: "ResourceNotFoundRpcError" - }); - } - }; - Object.defineProperty(ResourceNotFoundRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32001 - }); - ResourceUnavailableRpcError = class _ResourceUnavailableRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: _ResourceUnavailableRpcError.code, - name: "ResourceUnavailableRpcError", - shortMessage: "Requested resource not available." - }); - } - }; - Object.defineProperty(ResourceUnavailableRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32002 - }); - TransactionRejectedRpcError = class _TransactionRejectedRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: _TransactionRejectedRpcError.code, - name: "TransactionRejectedRpcError", - shortMessage: "Transaction creation failed." - }); - } - }; - Object.defineProperty(TransactionRejectedRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32003 - }); - MethodNotSupportedRpcError = class _MethodNotSupportedRpcError extends RpcError { - constructor(cause, { method } = {}) { - super(cause, { - code: _MethodNotSupportedRpcError.code, - name: "MethodNotSupportedRpcError", - shortMessage: `Method${method ? ` "${method}"` : ""} is not supported.` - }); - } - }; - Object.defineProperty(MethodNotSupportedRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32004 - }); - LimitExceededRpcError = class _LimitExceededRpcError extends RpcError { - constructor(cause) { - super(cause, { - code: _LimitExceededRpcError.code, - name: "LimitExceededRpcError", - shortMessage: "Request exceeds defined limit." + value: void 0 }); + this.signature = signature; } }; - Object.defineProperty(LimitExceededRpcError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32005 - }); - JsonRpcVersionUnsupportedError = class _JsonRpcVersionUnsupportedError extends RpcError { - constructor(cause) { - super(cause, { - code: _JsonRpcVersionUnsupportedError.code, - name: "JsonRpcVersionUnsupportedError", - shortMessage: "Version of JSON-RPC protocol is not supported." + AbiEventSignatureEmptyTopicsError = class extends BaseError2 { + constructor({ docsPath: docsPath6 }) { + super("Cannot extract event signature from empty topics.", { + docsPath: docsPath6, + name: "AbiEventSignatureEmptyTopicsError" }); } }; - Object.defineProperty(JsonRpcVersionUnsupportedError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: -32006 - }); - UserRejectedRequestError = class _UserRejectedRequestError extends ProviderRpcError { - constructor(cause) { - super(cause, { - code: _UserRejectedRequestError.code, - name: "UserRejectedRequestError", - shortMessage: "User rejected the request." + AbiEventSignatureNotFoundError = class extends BaseError2 { + constructor(signature, { docsPath: docsPath6 }) { + super([ + `Encoded event signature "${signature}" not found on ABI.`, + "Make sure you are using the correct ABI and that the event exists on it.", + `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.` + ].join("\n"), { + docsPath: docsPath6, + name: "AbiEventSignatureNotFoundError" }); } }; - Object.defineProperty(UserRejectedRequestError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4001 - }); - UnauthorizedProviderError = class _UnauthorizedProviderError extends ProviderRpcError { - constructor(cause) { - super(cause, { - code: _UnauthorizedProviderError.code, - name: "UnauthorizedProviderError", - shortMessage: "The requested method and/or account has not been authorized by the user." + AbiEventNotFoundError = class extends BaseError2 { + constructor(eventName, { docsPath: docsPath6 } = {}) { + super([ + `Event ${eventName ? `"${eventName}" ` : ""}not found on ABI.`, + "Make sure you are using the correct ABI and that the event exists on it." + ].join("\n"), { + docsPath: docsPath6, + name: "AbiEventNotFoundError" }); } }; - Object.defineProperty(UnauthorizedProviderError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4100 - }); - UnsupportedProviderMethodError = class _UnsupportedProviderMethodError extends ProviderRpcError { - constructor(cause, { method } = {}) { - super(cause, { - code: _UnsupportedProviderMethodError.code, - name: "UnsupportedProviderMethodError", - shortMessage: `The Provider does not support the requested method${method ? ` " ${method}"` : ""}.` + AbiFunctionNotFoundError = class extends BaseError2 { + constructor(functionName, { docsPath: docsPath6 } = {}) { + super([ + `Function ${functionName ? `"${functionName}" ` : ""}not found on ABI.`, + "Make sure you are using the correct ABI and that the function exists on it." + ].join("\n"), { + docsPath: docsPath6, + name: "AbiFunctionNotFoundError" }); } }; - Object.defineProperty(UnsupportedProviderMethodError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4200 - }); - ProviderDisconnectedError = class _ProviderDisconnectedError extends ProviderRpcError { - constructor(cause) { - super(cause, { - code: _ProviderDisconnectedError.code, - name: "ProviderDisconnectedError", - shortMessage: "The Provider is disconnected from all chains." + AbiFunctionOutputsNotFoundError = class extends BaseError2 { + constructor(functionName, { docsPath: docsPath6 }) { + super([ + `Function "${functionName}" does not contain any \`outputs\` on ABI.`, + "Cannot decode function result without knowing what the parameter types are.", + "Make sure you are using the correct ABI and that the function exists on it." + ].join("\n"), { + docsPath: docsPath6, + name: "AbiFunctionOutputsNotFoundError" }); } }; - Object.defineProperty(ProviderDisconnectedError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4900 - }); - ChainDisconnectedError = class _ChainDisconnectedError extends ProviderRpcError { - constructor(cause) { - super(cause, { - code: _ChainDisconnectedError.code, - name: "ChainDisconnectedError", - shortMessage: "The Provider is not connected to the requested chain." + AbiItemAmbiguityError = class extends BaseError2 { + constructor(x2, y2) { + super("Found ambiguous types in overloaded ABI items.", { + metaMessages: [ + `\`${x2.type}\` in \`${formatAbiItem2(x2.abiItem)}\`, and`, + `\`${y2.type}\` in \`${formatAbiItem2(y2.abiItem)}\``, + "", + "These types encode differently and cannot be distinguished at runtime.", + "Remove one of the ambiguous items in the ABI." + ], + name: "AbiItemAmbiguityError" }); } }; - Object.defineProperty(ChainDisconnectedError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4901 - }); - SwitchChainError = class _SwitchChainError extends ProviderRpcError { - constructor(cause) { - super(cause, { - code: _SwitchChainError.code, - name: "SwitchChainError", - shortMessage: "An error occurred when attempting to switch chain." + BytesSizeMismatchError = class extends BaseError2 { + constructor({ expectedSize, givenSize }) { + super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, { + name: "BytesSizeMismatchError" }); } }; - Object.defineProperty(SwitchChainError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 4902 - }); - UnknownRpcError = class extends RpcError { - constructor(cause) { - super(cause, { - name: "UnknownRpcError", - shortMessage: "An unknown RPC error occurred." + DecodeLogDataMismatch = class extends BaseError2 { + constructor({ abiItem, data, params, size: size5 }) { + super([ + `Data size of ${size5} bytes is too small for non-indexed event parameters.` + ].join("\n"), { + metaMessages: [ + `Params: (${formatAbiParams(params, { includeName: true })})`, + `Data: ${data} (${size5} bytes)` + ], + name: "DecodeLogDataMismatch" + }); + Object.defineProperty(this, "abiItem", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "params", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "size", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); + this.abiItem = abiItem; + this.data = data; + this.params = params; + this.size = size5; } }; - } -}); - -// node_modules/viem/node_modules/@noble/hashes/esm/_md.js -function setBigUint64(view, byteOffset, value, isLE3) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE3); - const _32n3 = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n3 & _u32_max); - const wl2 = Number(value & _u32_max); - const h = isLE3 ? 4 : 0; - const l = isLE3 ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE3); - view.setUint32(byteOffset + l, wl2, isLE3); -} -function Chi(a, b2, c) { - return a & b2 ^ ~a & c; -} -function Maj(a, b2, c) { - return a & b2 ^ a & c ^ b2 & c; -} -var HashMD; -var init_md = __esm({ - "node_modules/viem/node_modules/@noble/hashes/esm/_md.js"() { - init_assert(); - init_utils2(); - HashMD = class extends Hash { - constructor(blockLen, outputLen, padOffset, isLE3) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE3; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); + DecodeLogTopicsMismatch = class extends BaseError2 { + constructor({ abiItem, param }) { + super([ + `Expected a topic for indexed event parameter${param.name ? ` "${param.name}"` : ""} on event "${formatAbiItem2(abiItem, { includeName: true })}".` + ].join("\n"), { name: "DecodeLogTopicsMismatch" }); + Object.defineProperty(this, "abiItem", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.abiItem = abiItem; } - update(data) { - aexists(this); - const { view, buffer: buffer2, blockLen } = this; - data = toBytes2(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer2.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; + }; + InvalidAbiEncodingTypeError = class extends BaseError2 { + constructor(type, { docsPath: docsPath6 }) { + super([ + `Type "${type}" is not a valid encoding type.`, + "Please provide a valid ABI type." + ].join("\n"), { docsPath: docsPath6, name: "InvalidAbiEncodingType" }); } - digestInto(out) { - aexists(this); - aoutput(out, this); - this.finished = true; - const { buffer: buffer2, view, blockLen, isLE: isLE3 } = this; - let { pos } = this; - buffer2[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i = pos; i < blockLen; i++) - buffer2[i] = 0; - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE3); + }; + InvalidAbiDecodingTypeError = class extends BaseError2 { + constructor(type, { docsPath: docsPath6 }) { + super([ + `Type "${type}" is not a valid decoding type.`, + "Please provide a valid ABI type." + ].join("\n"), { docsPath: docsPath6, name: "InvalidAbiDecodingType" }); } - digest() { - const { buffer: buffer2, outputLen } = this; - this.digestInto(buffer2); - const res = buffer2.slice(0, outputLen); - this.destroy(); - return res; + }; + InvalidArrayError = class extends BaseError2 { + constructor(value) { + super([`Value "${value}" is not a valid array.`].join("\n"), { + name: "InvalidArrayError" + }); } - _cloneInto(to2) { - to2 || (to2 = new this.constructor()); - to2.set(...this.get()); - const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; - to2.length = length; - to2.pos = pos; - to2.finished = finished; - to2.destroyed = destroyed; - if (length % blockLen) - to2.buffer.set(buffer2); - return to2; + }; + InvalidDefinitionTypeError = class extends BaseError2 { + constructor(type) { + super([ + `"${type}" is not a valid definition type.`, + 'Valid types: "function", "event", "error"' + ].join("\n"), { name: "InvalidDefinitionTypeError" }); } }; } }); -// node_modules/viem/node_modules/@noble/hashes/esm/sha256.js -var SHA256_K, SHA256_IV, SHA256_W, SHA256, sha256; -var init_sha256 = __esm({ - "node_modules/viem/node_modules/@noble/hashes/esm/sha256.js"() { - init_md(); - init_utils2(); - SHA256_K = /* @__PURE__ */ new Uint32Array([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 - ]); - SHA256_IV = /* @__PURE__ */ new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 - ]); - SHA256_W = /* @__PURE__ */ new Uint32Array(64); - SHA256 = class extends HashMD { - constructor() { - super(64, 32, 8, false); - this.A = SHA256_IV[0] | 0; - this.B = SHA256_IV[1] | 0; - this.C = SHA256_IV[2] | 0; - this.D = SHA256_IV[3] | 0; - this.E = SHA256_IV[4] | 0; - this.F = SHA256_IV[5] | 0; - this.G = SHA256_IV[6] | 0; - this.H = SHA256_IV[7] | 0; - } - get() { - const { A: A2, B: B2, C, D, E, F: F2, G: G2, H: H2 } = this; - return [A2, B2, C, D, E, F2, G2, H2]; - } - // prettier-ignore - set(A2, B2, C, D, E, F2, G2, H2) { - this.A = A2 | 0; - this.B = B2 | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F2 | 0; - this.G = G2 | 0; - this.H = H2 | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - SHA256_W[i] = view.getUint32(offset, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; - } - let { A: A2, B: B2, C, D, E, F: F2, G: G2, H: H2 } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H2 + sigma1 + Chi(E, F2, G2) + SHA256_K[i] + SHA256_W[i] | 0; - const sigma0 = rotr(A2, 2) ^ rotr(A2, 13) ^ rotr(A2, 22); - const T2 = sigma0 + Maj(A2, B2, C) | 0; - H2 = G2; - G2 = F2; - F2 = E; - E = D + T1 | 0; - D = C; - C = B2; - B2 = A2; - A2 = T1 + T2 | 0; - } - A2 = A2 + this.A | 0; - B2 = B2 + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F2 = F2 + this.F | 0; - G2 = G2 + this.G | 0; - H2 = H2 + this.H | 0; - this.set(A2, B2, C, D, E, F2, G2, H2); +// node_modules/viem/_esm/errors/data.js +var SliceOffsetOutOfBoundsError, SizeExceedsPaddingSizeError, InvalidBytesLengthError; +var init_data = __esm({ + "node_modules/viem/_esm/errors/data.js"() { + init_base(); + SliceOffsetOutOfBoundsError = class extends BaseError2 { + constructor({ offset, position, size: size5 }) { + super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size5}).`, { name: "SliceOffsetOutOfBoundsError" }); } - roundClean() { - SHA256_W.fill(0); + }; + SizeExceedsPaddingSizeError = class extends BaseError2 { + constructor({ size: size5, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size5}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); + }; + InvalidBytesLengthError = class extends BaseError2 { + constructor({ size: size5, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size5} ${type} long.`, { name: "InvalidBytesLengthError" }); } }; - sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); } }); -// node_modules/viem/node_modules/@noble/hashes/esm/hmac.js -var HMAC, hmac; -var init_hmac = __esm({ - "node_modules/viem/node_modules/@noble/hashes/esm/hmac.js"() { - init_assert(); - init_utils2(); - HMAC = class extends Hash { - constructor(hash2, _key) { - super(); - this.finished = false; - this.destroyed = false; - ahash(hash2); - const key = toBytes2(_key); - this.iHash = hash2.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad4 = new Uint8Array(blockLen); - pad4.set(key.length > blockLen ? hash2.create().update(key).digest() : key); - for (let i = 0; i < pad4.length; i++) - pad4[i] ^= 54; - this.iHash.update(pad4); - this.oHash = hash2.create(); - for (let i = 0; i < pad4.length; i++) - pad4[i] ^= 54 ^ 92; - this.oHash.update(pad4); - pad4.fill(0); - } - update(buf) { - aexists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - aexists(this); - abytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); +// node_modules/viem/_esm/utils/data/pad.js +function pad(hexOrBytes, { dir, size: size5 = 32 } = {}) { + if (typeof hexOrBytes === "string") + return padHex(hexOrBytes, { dir, size: size5 }); + return padBytes(hexOrBytes, { dir, size: size5 }); +} +function padHex(hex_, { dir, size: size5 = 32 } = {}) { + if (size5 === null) + return hex_; + const hex = hex_.replace("0x", ""); + if (hex.length > size5 * 2) + throw new SizeExceedsPaddingSizeError({ + size: Math.ceil(hex.length / 2), + targetSize: size5, + type: "hex" + }); + return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`; +} +function padBytes(bytes, { dir, size: size5 = 32 } = {}) { + if (size5 === null) + return bytes; + if (bytes.length > size5) + throw new SizeExceedsPaddingSizeError({ + size: bytes.length, + targetSize: size5, + type: "bytes" + }); + const paddedBytes = new Uint8Array(size5); + for (let i = 0; i < size5; i++) { + const padEnd = dir === "right"; + paddedBytes[padEnd ? i : size5 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; + } + return paddedBytes; +} +var init_pad = __esm({ + "node_modules/viem/_esm/utils/data/pad.js"() { + init_data(); + } +}); + +// node_modules/viem/_esm/errors/encoding.js +var IntegerOutOfRangeError, InvalidBytesBooleanError, InvalidHexBooleanError, SizeOverflowError; +var init_encoding = __esm({ + "node_modules/viem/_esm/errors/encoding.js"() { + init_base(); + IntegerOutOfRangeError = class extends BaseError2 { + constructor({ max, min, signed, size: size5, value }) { + super(`Number "${value}" is not in safe ${size5 ? `${size5 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" }); } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; + }; + InvalidBytesBooleanError = class extends BaseError2 { + constructor(bytes) { + super(`Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, { + name: "InvalidBytesBooleanError" + }); } - _cloneInto(to2) { - to2 || (to2 = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to2 = to2; - to2.finished = finished; - to2.destroyed = destroyed; - to2.blockLen = blockLen; - to2.outputLen = outputLen; - to2.oHash = oHash._cloneInto(to2.oHash); - to2.iHash = iHash._cloneInto(to2.iHash); - return to2; + }; + InvalidHexBooleanError = class extends BaseError2 { + constructor(hex) { + super(`Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`, { name: "InvalidHexBooleanError" }); } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); + }; + SizeOverflowError = class extends BaseError2 { + constructor({ givenSize, maxSize }) { + super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" }); } }; - hmac = (hash2, key, message) => new HMAC(hash2, key).update(message).digest(); - hmac.create = (hash2, key) => new HMAC(hash2, key); } }); -// node_modules/viem/node_modules/@noble/curves/esm/abstract/utils.js -var utils_exports2 = {}; -__export(utils_exports2, { - aInRange: () => aInRange, - abool: () => abool, - abytes: () => abytes2, - bitGet: () => bitGet, - bitLen: () => bitLen, - bitMask: () => bitMask, - bitSet: () => bitSet, - bytesToHex: () => bytesToHex2, - bytesToNumberBE: () => bytesToNumberBE, - bytesToNumberLE: () => bytesToNumberLE, - concatBytes: () => concatBytes3, - createHmacDrbg: () => createHmacDrbg, - ensureBytes: () => ensureBytes, - equalBytes: () => equalBytes, - hexToBytes: () => hexToBytes2, - hexToNumber: () => hexToNumber2, - inRange: () => inRange, - isBytes: () => isBytes2, - memoized: () => memoized, - notImplemented: () => notImplemented, - numberToBytesBE: () => numberToBytesBE, - numberToBytesLE: () => numberToBytesLE, - numberToHexUnpadded: () => numberToHexUnpadded, - numberToVarBytesBE: () => numberToVarBytesBE, - utf8ToBytes: () => utf8ToBytes2, - validateObject: () => validateObject -}); -function isBytes2(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; -} -function abytes2(item) { - if (!isBytes2(item)) - throw new Error("Uint8Array expected"); -} -function abool(title, value) { - if (typeof value !== "boolean") - throw new Error(title + " boolean expected, got " + value); -} -function bytesToHex2(bytes) { - abytes2(bytes); - let hex = ""; - for (let i = 0; i < bytes.length; i++) { - hex += hexes2[bytes[i]]; +// node_modules/viem/_esm/utils/data/trim.js +function trim(hexOrBytes, { dir = "left" } = {}) { + let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes; + let sliceLength = 0; + for (let i = 0; i < data.length - 1; i++) { + if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") + sliceLength++; + else + break; } - return hex; -} -function numberToHexUnpadded(num2) { - const hex = num2.toString(16); - return hex.length & 1 ? "0" + hex : hex; -} -function hexToNumber2(hex) { - if (typeof hex !== "string") - throw new Error("hex string expected, got " + typeof hex); - return hex === "" ? _0n2 : BigInt("0x" + hex); -} -function asciiToBase16(ch) { - if (ch >= asciis._0 && ch <= asciis._9) - return ch - asciis._0; - if (ch >= asciis.A && ch <= asciis.F) - return ch - (asciis.A - 10); - if (ch >= asciis.a && ch <= asciis.f) - return ch - (asciis.a - 10); - return; -} -function hexToBytes2(hex) { - if (typeof hex !== "string") - throw new Error("hex string expected, got " + typeof hex); - const hl2 = hex.length; - const al2 = hl2 / 2; - if (hl2 % 2) - throw new Error("hex string expected, got unpadded hex of length " + hl2); - const array = new Uint8Array(al2); - for (let ai2 = 0, hi2 = 0; ai2 < al2; ai2++, hi2 += 2) { - const n1 = asciiToBase16(hex.charCodeAt(hi2)); - const n2 = asciiToBase16(hex.charCodeAt(hi2 + 1)); - if (n1 === void 0 || n2 === void 0) { - const char = hex[hi2] + hex[hi2 + 1]; - throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi2); - } - array[ai2] = n1 * 16 + n2; + data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); + if (typeof hexOrBytes === "string") { + if (data.length === 1 && dir === "right") + data = `${data}0`; + return `0x${data.length % 2 === 1 ? `0${data}` : data}`; } - return array; -} -function bytesToNumberBE(bytes) { - return hexToNumber2(bytesToHex2(bytes)); -} -function bytesToNumberLE(bytes) { - abytes2(bytes); - return hexToNumber2(bytesToHex2(Uint8Array.from(bytes).reverse())); -} -function numberToBytesBE(n, len) { - return hexToBytes2(n.toString(16).padStart(len * 2, "0")); -} -function numberToBytesLE(n, len) { - return numberToBytesBE(n, len).reverse(); -} -function numberToVarBytesBE(n) { - return hexToBytes2(numberToHexUnpadded(n)); + return data; } -function ensureBytes(title, hex, expectedLength) { - let res; - if (typeof hex === "string") { - try { - res = hexToBytes2(hex); - } catch (e) { - throw new Error(title + " must be hex string or Uint8Array, cause: " + e); - } - } else if (isBytes2(hex)) { - res = Uint8Array.from(hex); - } else { - throw new Error(title + " must be hex string or Uint8Array"); +var init_trim = __esm({ + "node_modules/viem/_esm/utils/data/trim.js"() { } - const len = res.length; - if (typeof expectedLength === "number" && len !== expectedLength) - throw new Error(title + " of length " + expectedLength + " expected, got " + len); - return res; +}); + +// node_modules/viem/_esm/utils/encoding/fromHex.js +function assertSize(hexOrBytes, { size: size5 }) { + if (size(hexOrBytes) > size5) + throw new SizeOverflowError({ + givenSize: size(hexOrBytes), + maxSize: size5 + }); } -function concatBytes3(...arrays) { - let sum = 0; - for (let i = 0; i < arrays.length; i++) { - const a = arrays[i]; - abytes2(a); - sum += a.length; - } - const res = new Uint8Array(sum); - for (let i = 0, pad4 = 0; i < arrays.length; i++) { - const a = arrays[i]; - res.set(a, pad4); - pad4 += a.length; - } - return res; +function hexToBigInt(hex, opts = {}) { + const { signed } = opts; + if (opts.size) + assertSize(hex, { size: opts.size }); + const value = BigInt(hex); + if (!signed) + return value; + const size5 = (hex.length - 2) / 2; + const max = (1n << BigInt(size5) * 8n - 1n) - 1n; + if (value <= max) + return value; + return value - BigInt(`0x${"f".padStart(size5 * 2, "f")}`) - 1n; } -function equalBytes(a, b2) { - if (a.length !== b2.length) +function hexToBool(hex_, opts = {}) { + let hex = hex_; + if (opts.size) { + assertSize(hex, { size: opts.size }); + hex = trim(hex); + } + if (trim(hex) === "0x00") return false; - let diff = 0; - for (let i = 0; i < a.length; i++) - diff |= a[i] ^ b2[i]; - return diff === 0; -} -function utf8ToBytes2(str) { - if (typeof str !== "string") - throw new Error("string expected"); - return new Uint8Array(new TextEncoder().encode(str)); -} -function inRange(n, min, max) { - return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; -} -function aInRange(title, n, min, max) { - if (!inRange(n, min, max)) - throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); -} -function bitLen(n) { - let len; - for (len = 0; n > _0n2; n >>= _1n2, len += 1) - ; - return len; -} -function bitGet(n, pos) { - return n >> BigInt(pos) & _1n2; -} -function bitSet(n, pos, value) { - return n | (value ? _1n2 : _0n2) << BigInt(pos); -} -function createHmacDrbg(hashLen, qByteLen, hmacFn) { - if (typeof hashLen !== "number" || hashLen < 2) - throw new Error("hashLen must be a number"); - if (typeof qByteLen !== "number" || qByteLen < 2) - throw new Error("qByteLen must be a number"); - if (typeof hmacFn !== "function") - throw new Error("hmacFn must be a function"); - let v = u8n(hashLen); - let k2 = u8n(hashLen); - let i = 0; - const reset = () => { - v.fill(1); - k2.fill(0); - i = 0; - }; - const h = (...b2) => hmacFn(k2, v, ...b2); - const reseed = (seed = u8n()) => { - k2 = h(u8fr([0]), seed); - v = h(); - if (seed.length === 0) - return; - k2 = h(u8fr([1]), seed); - v = h(); - }; - const gen3 = () => { - if (i++ >= 1e3) - throw new Error("drbg: tried 1000 values"); - let len = 0; - const out = []; - while (len < qByteLen) { - v = h(); - const sl2 = v.slice(); - out.push(sl2); - len += v.length; - } - return concatBytes3(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); - let res = void 0; - while (!(res = pred(gen3()))) - reseed(); - reset(); - return res; - }; - return genUntil; -} -function validateObject(object, validators3, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns[type]; - if (typeof checkVal !== "function") - throw new Error("invalid validator function"); - const val = object[fieldName]; - if (isOptional && val === void 0) - return; - if (!checkVal(val, object)) { - throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val); - } - }; - for (const [fieldName, type] of Object.entries(validators3)) - checkField(fieldName, type, false); - for (const [fieldName, type] of Object.entries(optValidators)) - checkField(fieldName, type, true); - return object; + if (trim(hex) === "0x01") + return true; + throw new InvalidHexBooleanError(hex); } -function memoized(fn2) { - const map = /* @__PURE__ */ new WeakMap(); - return (arg, ...args) => { - const val = map.get(arg); - if (val !== void 0) - return val; - const computed = fn2(arg, ...args); - map.set(arg, computed); - return computed; - }; +function hexToNumber(hex, opts = {}) { + return Number(hexToBigInt(hex, opts)); } -var _0n2, _1n2, _2n2, hexes2, asciis, isPosBig, bitMask, u8n, u8fr, validatorFns, notImplemented; -var init_utils4 = __esm({ - "node_modules/viem/node_modules/@noble/curves/esm/abstract/utils.js"() { - _0n2 = /* @__PURE__ */ BigInt(0); - _1n2 = /* @__PURE__ */ BigInt(1); - _2n2 = /* @__PURE__ */ BigInt(2); - hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); - asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; - isPosBig = (n) => typeof n === "bigint" && _0n2 <= n; - bitMask = (n) => (_2n2 << BigInt(n - 1)) - _1n2; - u8n = (data) => new Uint8Array(data); - u8fr = (arr) => Uint8Array.from(arr); - validatorFns = { - bigint: (val) => typeof val === "bigint", - function: (val) => typeof val === "function", - boolean: (val) => typeof val === "boolean", - string: (val) => typeof val === "string", - stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val), - isSafeInteger: (val) => Number.isSafeInteger(val), - array: (val) => Array.isArray(val), - field: (val, object) => object.Fp.isValid(val), - hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) - }; - notImplemented = () => { - throw new Error("not implemented"); - }; +var init_fromHex = __esm({ + "node_modules/viem/_esm/utils/encoding/fromHex.js"() { + init_encoding(); + init_size(); + init_trim(); } }); -// node_modules/viem/node_modules/@noble/curves/esm/abstract/modular.js -function mod(a, b2) { - const result = a % b2; - return result >= _0n3 ? result : b2 + result; -} -function pow(num2, power, modulo) { - if (power < _0n3) - throw new Error("invalid exponent, negatives unsupported"); - if (modulo <= _0n3) - throw new Error("invalid modulus"); - if (modulo === _1n3) - return _0n3; - let res = _1n3; - while (power > _0n3) { - if (power & _1n3) - res = res * num2 % modulo; - num2 = num2 * num2 % modulo; - power >>= _1n3; - } - return res; -} -function pow2(x2, power, modulo) { - let res = x2; - while (power-- > _0n3) { - res *= res; - res %= modulo; +// node_modules/viem/_esm/utils/encoding/toHex.js +function toHex(value, opts = {}) { + if (typeof value === "number" || typeof value === "bigint") + return numberToHex(value, opts); + if (typeof value === "string") { + return stringToHex(value, opts); } - return res; + if (typeof value === "boolean") + return boolToHex(value, opts); + return bytesToHex(value, opts); } -function invert(number, modulo) { - if (number === _0n3) - throw new Error("invert: expected non-zero number"); - if (modulo <= _0n3) - throw new Error("invert: expected positive modulus, got " + modulo); - let a = mod(number, modulo); - let b2 = modulo; - let x2 = _0n3, y2 = _1n3, u = _1n3, v = _0n3; - while (a !== _0n3) { - const q2 = b2 / a; - const r = b2 % a; - const m2 = x2 - u * q2; - const n = y2 - v * q2; - b2 = a, a = r, x2 = u, y2 = v, u = m2, v = n; +function boolToHex(value, opts = {}) { + const hex = `0x${Number(value)}`; + if (typeof opts.size === "number") { + assertSize(hex, { size: opts.size }); + return pad(hex, { size: opts.size }); } - const gcd = b2; - if (gcd !== _1n3) - throw new Error("invert: does not exist"); - return mod(x2, modulo); + return hex; } -function tonelliShanks(P2) { - const legendreC = (P2 - _1n3) / _2n3; - let Q, S, Z2; - for (Q = P2 - _1n3, S = 0; Q % _2n3 === _0n3; Q /= _2n3, S++) - ; - for (Z2 = _2n3; Z2 < P2 && pow(Z2, legendreC, P2) !== P2 - _1n3; Z2++) { - if (Z2 > 1e3) - throw new Error("Cannot find square root: likely non-prime P"); +function bytesToHex(value, opts = {}) { + let string = ""; + for (let i = 0; i < value.length; i++) { + string += hexes[value[i]]; } - if (S === 1) { - const p1div4 = (P2 + _1n3) / _4n; - return function tonelliFast(Fp2, n) { - const root = Fp2.pow(n, p1div4); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; + const hex = `0x${string}`; + if (typeof opts.size === "number") { + assertSize(hex, { size: opts.size }); + return pad(hex, { dir: "right", size: opts.size }); } - const Q1div2 = (Q + _1n3) / _2n3; - return function tonelliSlow(Fp2, n) { - if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) - throw new Error("Cannot find square root"); - let r = S; - let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z2), Q); - let x2 = Fp2.pow(n, Q1div2); - let b2 = Fp2.pow(n, Q); - while (!Fp2.eql(b2, Fp2.ONE)) { - if (Fp2.eql(b2, Fp2.ZERO)) - return Fp2.ZERO; - let m2 = 1; - for (let t2 = Fp2.sqr(b2); m2 < r; m2++) { - if (Fp2.eql(t2, Fp2.ONE)) - break; - t2 = Fp2.sqr(t2); - } - const ge2 = Fp2.pow(g, _1n3 << BigInt(r - m2 - 1)); - g = Fp2.sqr(ge2); - x2 = Fp2.mul(x2, ge2); - b2 = Fp2.mul(b2, g); - r = m2; - } - return x2; - }; + return hex; } -function FpSqrt(P2) { - if (P2 % _4n === _3n) { - const p1div4 = (P2 + _1n3) / _4n; - return function sqrt3mod4(Fp2, n) { - const root = Fp2.pow(n, p1div4); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P2 % _8n === _5n) { - const c1 = (P2 - _5n) / _8n; - return function sqrt5mod8(Fp2, n) { - const n2 = Fp2.mul(n, _2n3); - const v = Fp2.pow(n2, c1); - const nv = Fp2.mul(n, v); - const i = Fp2.mul(Fp2.mul(nv, _2n3), v); - const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; +function numberToHex(value_, opts = {}) { + const { signed, size: size5 } = opts; + const value = BigInt(value_); + let maxValue; + if (size5) { + if (signed) + maxValue = (1n << BigInt(size5) * 8n - 1n) - 1n; + else + maxValue = 2n ** (BigInt(size5) * 8n) - 1n; + } else if (typeof value_ === "number") { + maxValue = BigInt(Number.MAX_SAFE_INTEGER); } - if (P2 % _16n === _9n) { + const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0; + if (maxValue && value > maxValue || value < minValue) { + const suffix = typeof value_ === "bigint" ? "n" : ""; + throw new IntegerOutOfRangeError({ + max: maxValue ? `${maxValue}${suffix}` : void 0, + min: `${minValue}${suffix}`, + signed, + size: size5, + value: `${value_}${suffix}` + }); } - return tonelliShanks(P2); + const hex = `0x${(signed && value < 0 ? (1n << BigInt(size5 * 8)) + BigInt(value) : value).toString(16)}`; + if (size5) + return pad(hex, { size: size5 }); + return hex; } -function validateField(field) { - const initial = { - ORDER: "bigint", - MASK: "bigint", - BYTES: "isSafeInteger", - BITS: "isSafeInteger" - }; - const opts = FIELD_FIELDS.reduce((map, val) => { - map[val] = "function"; - return map; - }, initial); - return validateObject(field, opts); +function stringToHex(value_, opts = {}) { + const value = encoder.encode(value_); + return bytesToHex(value, opts); } -function FpPow(f, num2, power) { - if (power < _0n3) - throw new Error("invalid exponent, negatives unsupported"); - if (power === _0n3) - return f.ONE; - if (power === _1n3) - return num2; - let p = f.ONE; - let d = num2; - while (power > _0n3) { - if (power & _1n3) - p = f.mul(p, d); - d = f.sqr(d); - power >>= _1n3; +var hexes, encoder; +var init_toHex = __esm({ + "node_modules/viem/_esm/utils/encoding/toHex.js"() { + init_encoding(); + init_pad(); + init_fromHex(); + hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); + encoder = /* @__PURE__ */ new TextEncoder(); } - return p; +}); + +// node_modules/viem/_esm/utils/encoding/toBytes.js +function toBytes(value, opts = {}) { + if (typeof value === "number" || typeof value === "bigint") + return numberToBytes(value, opts); + if (typeof value === "boolean") + return boolToBytes(value, opts); + if (isHex(value)) + return hexToBytes(value, opts); + return stringToBytes(value, opts); } -function FpInvertBatch(f, nums) { - const tmp = new Array(nums.length); - const lastMultiplied = nums.reduce((acc, num2, i) => { - if (f.is0(num2)) - return acc; - tmp[i] = acc; - return f.mul(acc, num2); - }, f.ONE); - const inverted = f.inv(lastMultiplied); - nums.reduceRight((acc, num2, i) => { - if (f.is0(num2)) - return acc; - tmp[i] = f.mul(acc, tmp[i]); - return f.mul(acc, num2); - }, inverted); - return tmp; +function boolToBytes(value, opts = {}) { + const bytes = new Uint8Array(1); + bytes[0] = Number(value); + if (typeof opts.size === "number") { + assertSize(bytes, { size: opts.size }); + return pad(bytes, { size: opts.size }); + } + return bytes; } -function nLength(n, nBitLength) { - const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; +function charCodeToBase16(char) { + if (char >= charCodeMap.zero && char <= charCodeMap.nine) + return char - charCodeMap.zero; + if (char >= charCodeMap.A && char <= charCodeMap.F) + return char - (charCodeMap.A - 10); + if (char >= charCodeMap.a && char <= charCodeMap.f) + return char - (charCodeMap.a - 10); + return void 0; } -function Field(ORDER, bitLen2, isLE3 = false, redef = {}) { - if (ORDER <= _0n3) - throw new Error("invalid field: expected ORDER > 0, got " + ORDER); - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); - if (BYTES > 2048) - throw new Error("invalid field: expected ORDER of <= 2048 bytes"); - let sqrtP; - const f = Object.freeze({ - ORDER, - isLE: isLE3, - BITS, - BYTES, - MASK: bitMask(BITS), - ZERO: _0n3, - ONE: _1n3, - create: (num2) => mod(num2, ORDER), - isValid: (num2) => { - if (typeof num2 !== "bigint") - throw new Error("invalid field element: expected bigint, got " + typeof num2); - return _0n3 <= num2 && num2 < ORDER; - }, - is0: (num2) => num2 === _0n3, - isOdd: (num2) => (num2 & _1n3) === _1n3, - neg: (num2) => mod(-num2, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num2) => mod(num2 * num2, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num2, power) => FpPow(f, num2, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - // Same as above, but doesn't normalize - sqrN: (num2) => num2 * num2, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num2) => invert(num2, ORDER), - sqrt: redef.sqrt || ((n) => { - if (!sqrtP) - sqrtP = FpSqrt(ORDER); - return sqrtP(f, n); - }), - invertBatch: (lst) => FpInvertBatch(f, lst), - // TODO: do we really need constant cmov? - // We don't have const-time bigints anyway, so probably will be not very useful - cmov: (a, b2, c) => c ? b2 : a, - toBytes: (num2) => isLE3 ? numberToBytesLE(num2, BYTES) : numberToBytesBE(num2, BYTES), - fromBytes: (bytes) => { - if (bytes.length !== BYTES) - throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); - return isLE3 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); +function hexToBytes(hex_, opts = {}) { + let hex = hex_; + if (opts.size) { + assertSize(hex, { size: opts.size }); + hex = pad(hex, { dir: "right", size: opts.size }); + } + let hexString = hex.slice(2); + if (hexString.length % 2) + hexString = `0${hexString}`; + const length = hexString.length / 2; + const bytes = new Uint8Array(length); + for (let index2 = 0, j2 = 0; index2 < length; index2++) { + const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j2++)); + const nibbleRight = charCodeToBase16(hexString.charCodeAt(j2++)); + if (nibbleLeft === void 0 || nibbleRight === void 0) { + throw new BaseError2(`Invalid byte sequence ("${hexString[j2 - 2]}${hexString[j2 - 1]}" in "${hexString}").`); } - }); - return Object.freeze(f); -} -function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== "bigint") - throw new Error("field order must be bigint"); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); + bytes[index2] = nibbleLeft * 16 + nibbleRight; + } + return bytes; } -function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); +function numberToBytes(value, opts) { + const hex = numberToHex(value, opts); + return hexToBytes(hex); } -function mapHashToField(key, fieldOrder, isLE3 = false) { - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = getMinHashLength(fieldOrder); - if (len < 16 || len < minLen || len > 1024) - throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); - const num2 = isLE3 ? bytesToNumberLE(key) : bytesToNumberBE(key); - const reduced = mod(num2, fieldOrder - _1n3) + _1n3; - return isLE3 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +function stringToBytes(value, opts = {}) { + const bytes = encoder2.encode(value); + if (typeof opts.size === "number") { + assertSize(bytes, { size: opts.size }); + return pad(bytes, { dir: "right", size: opts.size }); + } + return bytes; } -var _0n3, _1n3, _2n3, _3n, _4n, _5n, _8n, _9n, _16n, FIELD_FIELDS; -var init_modular = __esm({ - "node_modules/viem/node_modules/@noble/curves/esm/abstract/modular.js"() { - init_utils4(); - _0n3 = BigInt(0); - _1n3 = BigInt(1); - _2n3 = /* @__PURE__ */ BigInt(2); - _3n = /* @__PURE__ */ BigInt(3); - _4n = /* @__PURE__ */ BigInt(4); - _5n = /* @__PURE__ */ BigInt(5); - _8n = /* @__PURE__ */ BigInt(8); - _9n = /* @__PURE__ */ BigInt(9); - _16n = /* @__PURE__ */ BigInt(16); - FIELD_FIELDS = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" - ]; +var encoder2, charCodeMap; +var init_toBytes = __esm({ + "node_modules/viem/_esm/utils/encoding/toBytes.js"() { + init_base(); + init_isHex(); + init_pad(); + init_fromHex(); + init_toHex(); + encoder2 = /* @__PURE__ */ new TextEncoder(); + charCodeMap = { + zero: 48, + nine: 57, + A: 65, + F: 70, + a: 97, + f: 102 + }; } }); -// node_modules/viem/node_modules/@noble/curves/esm/abstract/curve.js -function constTimeNegate(condition, item) { - const neg = item.negate(); - return condition ? neg : item; -} -function validateW(W2, bits) { - if (!Number.isSafeInteger(W2) || W2 <= 0 || W2 > bits) - throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W2); -} -function calcWOpts(W2, bits) { - validateW(W2, bits); - const windows = Math.ceil(bits / W2) + 1; - const windowSize = 2 ** (W2 - 1); - return { windows, windowSize }; +// node_modules/viem/node_modules/@noble/hashes/esm/_assert.js +function anumber(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error("positive integer expected, got " + n); } -function validateMSMPoints(points, c) { - if (!Array.isArray(points)) - throw new Error("array expected"); - points.forEach((p, i) => { - if (!(p instanceof c)) - throw new Error("invalid point at index " + i); - }); +function isBytes(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } -function validateMSMScalars(scalars, field) { - if (!Array.isArray(scalars)) - throw new Error("array of scalars expected"); - scalars.forEach((s, i) => { - if (!field.isValid(s)) - throw new Error("invalid scalar at index " + i); - }); +function abytes(b2, ...lengths) { + if (!isBytes(b2)) + throw new Error("Uint8Array expected"); + if (lengths.length > 0 && !lengths.includes(b2.length)) + throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b2.length); } -function getW(P2) { - return pointWindowSizes.get(P2) || 1; +function ahash(h) { + if (typeof h !== "function" || typeof h.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + anumber(h.outputLen); + anumber(h.blockLen); } -function wNAF(c, bits) { - return { - constTimeNegate, - hasPrecomputes(elm) { - return getW(elm) !== 1; - }, - // non-const time multiplication ladder - unsafeLadder(elm, n, p = c.ZERO) { - let d = elm; - while (n > _0n4) { - if (n & _1n4) - p = p.add(d); - d = d.double(); - n >>= _1n4; - } - return p; - }, - /** - * Creates a wNAF precomputation window. Used for caching. - * Default window size is set by `utils.precompute()` and is equal to 8. - * Number of precomputed points depends on the curve size: - * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: - * - 𝑊 is the window size - * - 𝑛 is the bitlength of the curve order. - * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. - * @param elm Point instance - * @param W window size - * @returns precomputed point tables flattened to a single array - */ - precomputeWindow(elm, W2) { - const { windows, windowSize } = calcWOpts(W2, bits); - const points = []; - let p = elm; - let base = p; - for (let window2 = 0; window2 < windows; window2++) { - base = p; - points.push(base); - for (let i = 1; i < windowSize; i++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; - }, - /** - * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. - * @param W window size - * @param precomputes precomputed tables - * @param n scalar (we don't check here, but should be less than curve order) - * @returns real and fake (for const-time) points - */ - wNAF(W2, precomputes, n) { - const { windows, windowSize } = calcWOpts(W2, bits); - let p = c.ZERO; - let f = c.BASE; - const mask = BigInt(2 ** W2 - 1); - const maxNumber = 2 ** W2; - const shiftBy = BigInt(W2); - for (let window2 = 0; window2 < windows; window2++) { - const offset = window2 * windowSize; - let wbits = Number(n & mask); - n >>= shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n4; - } - const offset1 = offset; - const offset2 = offset + Math.abs(wbits) - 1; - const cond1 = window2 % 2 !== 0; - const cond2 = wbits < 0; - if (wbits === 0) { - f = f.add(constTimeNegate(cond1, precomputes[offset1])); - } else { - p = p.add(constTimeNegate(cond2, precomputes[offset2])); - } - } - return { p, f }; - }, - /** - * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form. - * @param W window size - * @param precomputes precomputed tables - * @param n scalar (we don't check here, but should be less than curve order) - * @param acc accumulator point to add result of multiplication - * @returns point - */ - wNAFUnsafe(W2, precomputes, n, acc = c.ZERO) { - const { windows, windowSize } = calcWOpts(W2, bits); - const mask = BigInt(2 ** W2 - 1); - const maxNumber = 2 ** W2; - const shiftBy = BigInt(W2); - for (let window2 = 0; window2 < windows; window2++) { - const offset = window2 * windowSize; - if (n === _0n4) - break; - let wbits = Number(n & mask); - n >>= shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n4; - } - if (wbits === 0) - continue; - let curr = precomputes[offset + Math.abs(wbits) - 1]; - if (wbits < 0) - curr = curr.negate(); - acc = acc.add(curr); - } - return acc; - }, - getPrecomputes(W2, P2, transform) { - let comp = pointPrecomputes.get(P2); - if (!comp) { - comp = this.precomputeWindow(P2, W2); - if (W2 !== 1) - pointPrecomputes.set(P2, transform(comp)); - } - return comp; - }, - wNAFCached(P2, n, transform) { - const W2 = getW(P2); - return this.wNAF(W2, this.getPrecomputes(W2, P2, transform), n); - }, - wNAFCachedUnsafe(P2, n, transform, prev) { - const W2 = getW(P2); - if (W2 === 1) - return this.unsafeLadder(P2, n, prev); - return this.wNAFUnsafe(W2, this.getPrecomputes(W2, P2, transform), n, prev); - }, - // We calculate precomputes for elliptic curve point multiplication - // using windowed method. This specifies window size and - // stores precomputed values. Usually only base point would be precomputed. - setWindowSize(P2, W2) { - validateW(W2, bits); - pointWindowSizes.set(P2, W2); - pointPrecomputes.delete(P2); - } - }; +function aexists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); } -function pippenger(c, fieldN, points, scalars) { - validateMSMPoints(points, c); - validateMSMScalars(scalars, fieldN); - if (points.length !== scalars.length) - throw new Error("arrays of points and scalars must have equal length"); - const zero = c.ZERO; - const wbits = bitLen(BigInt(points.length)); - const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; - const MASK = (1 << windowSize) - 1; - const buckets = new Array(MASK + 1).fill(zero); - const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; - let sum = zero; - for (let i = lastBits; i >= 0; i -= windowSize) { - buckets.fill(zero); - for (let j2 = 0; j2 < scalars.length; j2++) { - const scalar = scalars[j2]; - const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK)); - buckets[wbits2] = buckets[wbits2].add(points[j2]); - } - let resI = zero; - for (let j2 = buckets.length - 1, sumI = zero; j2 > 0; j2--) { - sumI = sumI.add(buckets[j2]); - resI = resI.add(sumI); - } - sum = sum.add(resI); - if (i !== 0) - for (let j2 = 0; j2 < windowSize; j2++) - sum = sum.double(); +function aoutput(out, instance) { + abytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error("digestInto() expects output buffer of length at least " + min); } - return sum; -} -function validateBasic(curve) { - validateField(curve.Fp); - validateObject(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); - return Object.freeze({ - ...nLength(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER } - }); } -var _0n4, _1n4, pointPrecomputes, pointWindowSizes; -var init_curve = __esm({ - "node_modules/viem/node_modules/@noble/curves/esm/abstract/curve.js"() { - init_modular(); - init_utils4(); - _0n4 = BigInt(0); - _1n4 = BigInt(1); - pointPrecomputes = /* @__PURE__ */ new WeakMap(); - pointWindowSizes = /* @__PURE__ */ new WeakMap(); +var init_assert = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/_assert.js"() { } -}); - -// node_modules/viem/node_modules/@noble/curves/esm/abstract/weierstrass.js -function validateSigVerOpts(opts) { - if (opts.lowS !== void 0) - abool("lowS", opts.lowS); - if (opts.prehash !== void 0) - abool("prehash", opts.prehash); +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/_u64.js +function fromBig(n, le2 = false) { + if (le2) + return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; + return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; } -function validatePointOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - a: "field", - b: "field" - }, { - allowedPrivateKeyLengths: "array", - wrapPrivateKey: "boolean", - isTorsionFree: "function", - clearCofactor: "function", - allowInfinityPoint: "boolean", - fromBytes: "function", - toBytes: "function" - }); - const { endo, Fp: Fp2, a } = opts; - if (endo) { - if (!Fp2.eql(a, Fp2.ZERO)) { - throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0"); - } - if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { - throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function"); - } +function split(lst, le2 = false) { + let Ah = new Uint32Array(lst.length); + let Al2 = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le2); + [Ah[i], Al2[i]] = [h, l]; } - return Object.freeze({ ...opts }); + return [Ah, Al2]; } -function weierstrassPoints(opts) { - const CURVE = validatePointOpts(opts); - const { Fp: Fp2 } = CURVE; - const Fn2 = Field(CURVE.n, CURVE.nBitLength); - const toBytes4 = CURVE.toBytes || ((_c2, point, _isCompressed) => { - const a = point.toAffine(); - return concatBytes3(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); - }); - const fromBytes2 = CURVE.fromBytes || ((bytes) => { - const tail = bytes.subarray(1); - const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x: x2, y: y2 }; - }); - function weierstrassEquation(x2) { - const { a, b: b2 } = CURVE; - const x22 = Fp2.sqr(x2); - const x3 = Fp2.mul(x22, x2); - return Fp2.add(Fp2.add(x3, Fp2.mul(x2, a)), b2); +var U32_MASK64, _32n, rotlSH, rotlSL, rotlBH, rotlBL; +var init_u64 = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/_u64.js"() { + U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); + _32n = /* @__PURE__ */ BigInt(32); + rotlSH = (h, l, s) => h << s | l >>> 32 - s; + rotlSL = (h, l, s) => l << s | h >>> 32 - s; + rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; + rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; } - if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) - throw new Error("bad generator point: equation left != right"); - function isWithinCurveOrder(num2) { - return inRange(num2, _1n5, CURVE.n); +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/cryptoNode.js +import * as nc from "node:crypto"; +var crypto2; +var init_cryptoNode = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/cryptoNode.js"() { + crypto2 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0; } - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N2 } = CURVE; - if (lengths && typeof key !== "bigint") { - if (isBytes2(key)) - key = bytesToHex2(key); - if (typeof key !== "string" || !lengths.includes(key.length)) - throw new Error("invalid private key"); - key = key.padStart(nByteLength * 2, "0"); - } - let num2; - try { - num2 = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); - } catch (error) { - throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key); - } - if (wrapPrivateKey) - num2 = mod(num2, N2); - aInRange("private key", num2, _1n5, N2); - return num2; +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/utils.js +function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +function rotr(word, shift) { + return word << 32 - shift | word >>> shift; +} +function byteSwap(word) { + return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; +} +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); } - function assertPrjPoint(other) { - if (!(other instanceof Point2)) - throw new Error("ProjectivePoint expected"); +} +function utf8ToBytes(str) { + if (typeof str !== "string") + throw new Error("utf8ToBytes expected string, got " + typeof str); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes2(data) { + if (typeof data === "string") + data = utf8ToBytes(data); + abytes(data); + return data; +} +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; } - const toAffineMemo = memoized((p, iz) => { - const { px: x2, py: y2, pz: z } = p; - if (Fp2.eql(z, Fp2.ONE)) - return { x: x2, y: y2 }; - const is0 = p.is0(); - if (iz == null) - iz = is0 ? Fp2.ONE : Fp2.inv(z); - const ax = Fp2.mul(x2, iz); - const ay = Fp2.mul(y2, iz); - const zz = Fp2.mul(z, iz); - if (is0) - return { x: Fp2.ZERO, y: Fp2.ZERO }; - if (!Fp2.eql(zz, Fp2.ONE)) - throw new Error("invZ was invalid"); - return { x: ax, y: ay }; - }); - const assertValidMemo = memoized((p) => { - if (p.is0()) { - if (CURVE.allowInfinityPoint && !Fp2.is0(p.py)) - return; - throw new Error("bad point: ZERO"); - } - const { x: x2, y: y2 } = p.toAffine(); - if (!Fp2.isValid(x2) || !Fp2.isValid(y2)) - throw new Error("bad point: x or y not FE"); - const left = Fp2.sqr(y2); - const right = weierstrassEquation(x2); - if (!Fp2.eql(left, right)) - throw new Error("bad point: equation left != right"); - if (!p.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - return true; - }); - class Point2 { - constructor(px, py, pz) { - this.px = px; - this.py = py; - this.pz = pz; - if (px == null || !Fp2.isValid(px)) - throw new Error("x required"); - if (py == null || !Fp2.isValid(py)) - throw new Error("y required"); - if (pz == null || !Fp2.isValid(pz)) - throw new Error("z required"); - Object.freeze(this); - } - // Does not validate if the point is on-curve. - // Use fromHex instead, or call assertValidity() later. - static fromAffine(p) { - const { x: x2, y: y2 } = p || {}; - if (!p || !Fp2.isValid(x2) || !Fp2.isValid(y2)) - throw new Error("invalid affine point"); - if (p instanceof Point2) - throw new Error("projective point not allowed"); - const is0 = (i) => Fp2.eql(i, Fp2.ZERO); - if (is0(x2) && is0(y2)) - return Point2.ZERO; - return new Point2(x2, y2, Fp2.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - /** - * Takes a bunch of Projective Points but executes only one - * inversion on all of them. Inversion is very slow operation, - * so this improves performance massively. - * Optimization: converts a list of projective points to a list of identical points with Z=1. - */ - static normalizeZ(points) { - const toInv = Fp2.invertBatch(points.map((p) => p.pz)); - return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); - } - /** - * Converts hash string or Uint8Array to Point. - * @param hex short/long ECDSA hex - */ - static fromHex(hex) { - const P2 = Point2.fromAffine(fromBytes2(ensureBytes("pointHex", hex))); - P2.assertValidity(); - return P2; - } - // Multiplies generator point by privateKey. - static fromPrivateKey(privateKey) { - return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); - } - // Multiscalar Multiplication - static msm(points, scalars) { - return pippenger(Point2, Fn2, points, scalars); - } - // "Private method", don't use it directly - _setWindowSize(windowSize) { - wnaf.setWindowSize(this, windowSize); - } - // A point on curve is valid if it conforms to equation. - assertValidity() { - assertValidMemo(this); - } - hasEvenY() { - const { y: y2 } = this.toAffine(); - if (Fp2.isOdd) - return !Fp2.isOdd(y2); - throw new Error("Field doesn't support isOdd"); - } - /** - * Compare one point to another. - */ - equals(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); - const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); - return U1 && U2; - } - /** - * Flips point to one corresponding to (x, -y) in Affine coordinates. - */ - negate() { - return new Point2(this.px, Fp2.neg(this.py), this.pz); - } - // Renes-Costello-Batina exception-free doubling formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 3 - // Cost: 8M + 3S + 3*a + 2*b3 + 15add. - double() { - const { a, b: b2 } = CURVE; - const b3 = Fp2.mul(b2, _3n2); - const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - let t0 = Fp2.mul(X1, X1); - let t1 = Fp2.mul(Y1, Y1); - let t2 = Fp2.mul(Z1, Z1); - let t3 = Fp2.mul(X1, Y1); - t3 = Fp2.add(t3, t3); - Z3 = Fp2.mul(X1, Z1); - Z3 = Fp2.add(Z3, Z3); - X3 = Fp2.mul(a, Z3); - Y3 = Fp2.mul(b3, t2); - Y3 = Fp2.add(X3, Y3); - X3 = Fp2.sub(t1, Y3); - Y3 = Fp2.add(t1, Y3); - Y3 = Fp2.mul(X3, Y3); - X3 = Fp2.mul(t3, X3); - Z3 = Fp2.mul(b3, Z3); - t2 = Fp2.mul(a, t2); - t3 = Fp2.sub(t0, t2); - t3 = Fp2.mul(a, t3); - t3 = Fp2.add(t3, Z3); - Z3 = Fp2.add(t0, t0); - t0 = Fp2.add(Z3, t0); - t0 = Fp2.add(t0, t2); - t0 = Fp2.mul(t0, t3); - Y3 = Fp2.add(Y3, t0); - t2 = Fp2.mul(Y1, Z1); - t2 = Fp2.add(t2, t2); - t0 = Fp2.mul(t2, t3); - X3 = Fp2.sub(X3, t0); - Z3 = Fp2.mul(t2, t1); - Z3 = Fp2.add(Z3, Z3); - Z3 = Fp2.add(Z3, Z3); - return new Point2(X3, Y3, Z3); - } - // Renes-Costello-Batina exception-free addition formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 1 - // Cost: 12M + 0S + 3*a + 3*b3 + 23add. - add(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - const a = CURVE.a; - const b3 = Fp2.mul(CURVE.b, _3n2); - let t0 = Fp2.mul(X1, X2); - let t1 = Fp2.mul(Y1, Y2); - let t2 = Fp2.mul(Z1, Z2); - let t3 = Fp2.add(X1, Y1); - let t4 = Fp2.add(X2, Y2); - t3 = Fp2.mul(t3, t4); - t4 = Fp2.add(t0, t1); - t3 = Fp2.sub(t3, t4); - t4 = Fp2.add(X1, Z1); - let t5 = Fp2.add(X2, Z2); - t4 = Fp2.mul(t4, t5); - t5 = Fp2.add(t0, t2); - t4 = Fp2.sub(t4, t5); - t5 = Fp2.add(Y1, Z1); - X3 = Fp2.add(Y2, Z2); - t5 = Fp2.mul(t5, X3); - X3 = Fp2.add(t1, t2); - t5 = Fp2.sub(t5, X3); - Z3 = Fp2.mul(a, t4); - X3 = Fp2.mul(b3, t2); - Z3 = Fp2.add(X3, Z3); - X3 = Fp2.sub(t1, Z3); - Z3 = Fp2.add(t1, Z3); - Y3 = Fp2.mul(X3, Z3); - t1 = Fp2.add(t0, t0); - t1 = Fp2.add(t1, t0); - t2 = Fp2.mul(a, t2); - t4 = Fp2.mul(b3, t4); - t1 = Fp2.add(t1, t2); - t2 = Fp2.sub(t0, t2); - t2 = Fp2.mul(a, t2); - t4 = Fp2.add(t4, t2); - t0 = Fp2.mul(t1, t4); - Y3 = Fp2.add(Y3, t0); - t0 = Fp2.mul(t5, t4); - X3 = Fp2.mul(t3, X3); - X3 = Fp2.sub(X3, t0); - t0 = Fp2.mul(t3, t1); - Z3 = Fp2.mul(t5, Z3); - Z3 = Fp2.add(Z3, t0); - return new Point2(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point2.ZERO); - } - wNAF(n) { - return wnaf.wNAFCached(this, n, Point2.normalizeZ); - } - /** - * Non-constant-time multiplication. Uses double-and-add algorithm. - * It's faster, but should only be used when you don't care about - * an exposed private key e.g. sig verification, which works over *public* keys. - */ - multiplyUnsafe(sc2) { - const { endo, n: N2 } = CURVE; - aInRange("scalar", sc2, _0n5, N2); - const I2 = Point2.ZERO; - if (sc2 === _0n5) - return I2; - if (this.is0() || sc2 === _1n5) - return this; - if (!endo || wnaf.hasPrecomputes(this)) - return wnaf.wNAFCachedUnsafe(this, sc2, Point2.normalizeZ); - let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc2); - let k1p = I2; - let k2p = I2; - let d = this; - while (k1 > _0n5 || k2 > _0n5) { - if (k1 & _1n5) - k1p = k1p.add(d); - if (k2 & _1n5) - k2p = k2p.add(d); - d = d.double(); - k1 >>= _1n5; - k2 >>= _1n5; - } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - return k1p.add(k2p); - } - /** - * Constant time multiplication. - * Uses wNAF method. Windowed method may be 10% faster, - * but takes 2x longer to generate and consumes 2x memory. - * Uses precomputes when available. - * Uses endomorphism for Koblitz curves. - * @param scalar by which the point would be multiplied - * @returns New point - */ - multiply(scalar) { - const { endo, n: N2 } = CURVE; - aInRange("scalar", scalar, _1n5, N2); - let point, fake; - if (endo) { - const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - const { p, f } = this.wNAF(scalar); - point = p; - fake = f; - } - return Point2.normalizeZ([point, fake])[0]; - } - /** - * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. - * Not using Strauss-Shamir trick: precomputation tables are faster. - * The trick could be useful if both P and Q are not G (not in our case). - * @returns non-zero affine point - */ - multiplyAndAddUnsafe(Q, a, b2) { - const G2 = Point2.BASE; - const mul = (P2, a2) => a2 === _0n5 || a2 === _1n5 || !P2.equals(G2) ? P2.multiplyUnsafe(a2) : P2.multiply(a2); - const sum = mul(this, a).add(mul(Q, b2)); - return sum.is0() ? void 0 : sum; - } - // Converts Projective point to affine (x, y) coordinates. - // Can accept precomputed Z^-1 - for example, from invertBatch. - // (x, y, z) ∋ (x=x/z, y=y/z) - toAffine(iz) { - return toAffineMemo(this, iz); - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n5) - return true; - if (isTorsionFree) - return isTorsionFree(Point2, this); - throw new Error("isTorsionFree() has not been declared for the elliptic curve"); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n5) - return this; - if (clearCofactor) - return clearCofactor(Point2, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - abool("isCompressed", isCompressed); - this.assertValidity(); - return toBytes4(Point2, this, isCompressed); - } - toHex(isCompressed = true) { - abool("isCompressed", isCompressed); - return bytesToHex2(this.toRawBytes(isCompressed)); - } + const res = new Uint8Array(sum); + for (let i = 0, pad4 = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad4); + pad4 += a.length; } - Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE); - Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); - const _bits = CURVE.nBitLength; - const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); - return { - CURVE, - ProjectivePoint: Point2, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder - }; + return res; } -function validateOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - hash: "hash", - hmac: "function", - randomBytes: "function" - }, { - bits2int: "function", - bits2int_modN: "function", - lowS: "boolean" - }); - return Object.freeze({ lowS: true, ...opts }); +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; } -function weierstrass(curveDef) { - const CURVE = validateOpts(curveDef); - const { Fp: Fp2, n: CURVE_ORDER } = CURVE; - const compressedLen = Fp2.BYTES + 1; - const uncompressedLen = 2 * Fp2.BYTES + 1; - function modN2(a) { - return mod(a, CURVE_ORDER); +function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; +} +function randomBytes(bytesLength = 32) { + if (crypto2 && typeof crypto2.getRandomValues === "function") { + return crypto2.getRandomValues(new Uint8Array(bytesLength)); } - function invN(a) { - return invert(a, CURVE_ORDER); + if (crypto2 && typeof crypto2.randomBytes === "function") { + return crypto2.randomBytes(bytesLength); } - const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ - ...CURVE, - toBytes(_c2, point, isCompressed) { - const a = point.toAffine(); - const x2 = Fp2.toBytes(a.x); - const cat = concatBytes3; - abool("isCompressed", isCompressed); - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x2); - } else { - return cat(Uint8Array.from([4]), x2, Fp2.toBytes(a.y)); - } - }, - fromBytes(bytes) { - const len = bytes.length; - const head = bytes[0]; - const tail = bytes.subarray(1); - if (len === compressedLen && (head === 2 || head === 3)) { - const x2 = bytesToNumberBE(tail); - if (!inRange(x2, _1n5, Fp2.ORDER)) - throw new Error("Point is not on curve"); - const y2 = weierstrassEquation(x2); - let y3; - try { - y3 = Fp2.sqrt(y2); - } catch (sqrtError) { - const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : ""; - throw new Error("Point is not on curve" + suffix); - } - const isYOdd = (y3 & _1n5) === _1n5; - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y3 = Fp2.neg(y3); - return { x: x2, y: y3 }; - } else if (len === uncompressedLen && head === 4) { - const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x: x2, y: y2 }; - } else { - const cl2 = compressedLen; - const ul2 = uncompressedLen; - throw new Error("invalid Point, expected length of " + cl2 + ", or uncompressed " + ul2 + ", got " + len); + throw new Error("crypto.getRandomValues must be defined"); +} +var isLE, Hash; +var init_utils2 = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/utils.js"() { + init_cryptoNode(); + init_assert(); + isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); + Hash = class { + // Safe version that clones internal state + clone() { + return this._cloneInto(); } - } - }); - const numToNByteStr = (num2) => bytesToHex2(numberToBytesBE(num2, CURVE.nByteLength)); - function isBiggerThanHalfOrder(number) { - const HALF = CURVE_ORDER >> _1n5; - return number > HALF; - } - function normalizeS(s) { - return isBiggerThanHalfOrder(s) ? modN2(-s) : s; + }; } - const slcNum = (b2, from5, to2) => bytesToNumberBE(b2.slice(from5, to2)); - class Signature { - constructor(r, s, recovery) { - this.r = r; - this.s = s; - this.recovery = recovery; - this.assertValidity(); - } - // pair (bytes of r, bytes of s) - static fromCompact(hex) { - const l = CURVE.nByteLength; - hex = ensureBytes("compactSignature", hex, l * 2); - return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); - } - // DER encoded ECDSA signature - // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script - static fromDER(hex) { - const { r, s } = DER.toSig(ensureBytes("DER", hex)); - return new Signature(r, s); - } - assertValidity() { - aInRange("r", this.r, _1n5, CURVE_ORDER); - aInRange("s", this.s, _1n5, CURVE_ORDER); - } - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r, s, recovery: rec } = this; - const h = bits2int_modN(ensureBytes("msgHash", msgHash)); - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error("recovery id invalid"); - const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; - if (radj >= Fp2.ORDER) - throw new Error("recovery id 2 or 3 invalid"); - const prefix = (rec & 1) === 0 ? "02" : "03"; - const R2 = Point2.fromHex(prefix + numToNByteStr(radj)); - const ir2 = invN(radj); - const u1 = modN2(-h * ir2); - const u2 = modN2(s * ir2); - const Q = Point2.BASE.multiplyAndAddUnsafe(R2, u1, u2); - if (!Q) - throw new Error("point at infinify"); - Q.assertValidity(); - return Q; - } - // Signatures should be low-s, to prevent malleability. - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - normalizeS() { - return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; - } - // DER-encoded - toDERRawBytes() { - return hexToBytes2(this.toDERHex()); - } - toDERHex() { - return DER.hexFromSig({ r: this.r, s: this.s }); +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/sha3.js +function keccakP(s, rounds = 24) { + const B2 = new Uint32Array(5 * 2); + for (let round = 24 - rounds; round < 24; round++) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s[x2] ^ s[x2 + 10] ^ s[x2 + 20] ^ s[x2 + 30] ^ s[x2 + 40]; + for (let x2 = 0; x2 < 10; x2 += 2) { + const idx1 = (x2 + 8) % 10; + const idx0 = (x2 + 2) % 10; + const B0 = B2[idx0]; + const B1 = B2[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B2[idx1]; + const Tl2 = rotlL(B0, B1, 1) ^ B2[idx1 + 1]; + for (let y2 = 0; y2 < 50; y2 += 10) { + s[x2 + y2] ^= Th; + s[x2 + y2 + 1] ^= Tl2; + } } - // padded bytes of r, then padded bytes of s - toCompactRawBytes() { - return hexToBytes2(this.toCompactHex()); + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl2 = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl2; } - toCompactHex() { - return numToNByteStr(this.r) + numToNByteStr(this.s); + for (let y2 = 0; y2 < 50; y2 += 10) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s[y2 + x2]; + for (let x2 = 0; x2 < 10; x2++) + s[y2 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10]; } + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; } - const utils = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } catch (error) { - return false; + B2.fill(0); +} +var SHA3_PI, SHA3_ROTL, _SHA3_IOTA, _0n, _1n, _2n, _7n, _256n, _0x71n, SHA3_IOTA_H, SHA3_IOTA_L, rotlH, rotlL, Keccak, gen, sha3_224, sha3_256, sha3_384, sha3_512, keccak_224, keccak_256, keccak_384, keccak_512, genShake, shake128, shake256; +var init_sha3 = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/sha3.js"() { + init_assert(); + init_u64(); + init_utils2(); + SHA3_PI = []; + SHA3_ROTL = []; + _SHA3_IOTA = []; + _0n = /* @__PURE__ */ BigInt(0); + _1n = /* @__PURE__ */ BigInt(1); + _2n = /* @__PURE__ */ BigInt(2); + _7n = /* @__PURE__ */ BigInt(7); + _256n = /* @__PURE__ */ BigInt(256); + _0x71n = /* @__PURE__ */ BigInt(113); + for (let round = 0, R2 = _1n, x2 = 1, y2 = 0; round < 24; round++) { + [x2, y2] = [y2, (2 * x2 + 3 * y2) % 5]; + SHA3_PI.push(2 * (5 * y2 + x2)); + SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); + let t = _0n; + for (let j2 = 0; j2 < 7; j2++) { + R2 = (R2 << _1n ^ (R2 >> _7n) * _0x71n) % _256n; + if (R2 & _2n) + t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j2)) - _1n; } - }, - normPrivateKeyToScalar, - /** - * Produces cryptographically secure private key from random of size - * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. - */ - randomPrivateKey: () => { - const length = getMinHashLength(CURVE.n); - return mapHashToField(CURVE.randomBytes(length), CURVE.n); - }, - /** - * Creates precompute table for an arbitrary EC point. Makes point "cached". - * Allows to massively speed-up `point.multiply(scalar)`. - * @returns cached point - * @example - * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); - * fast.multiply(privKey); // much faster ECDH now - */ - precompute(windowSize = 8, point = Point2.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); - return point; - } - }; - function getPublicKey(privateKey, isCompressed = true) { - return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } - function isProbPub(item) { - const arr = isBytes2(item); - const str = typeof item === "string"; - const len = (arr || str) && item.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item instanceof Point2) - return true; - return false; - } - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error("first arg must be private key"); - if (!isProbPub(publicB)) - throw new Error("second arg must be public key"); - const b2 = Point2.fromHex(publicB); - return b2.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); - } - const bits2int = CURVE.bits2int || function(bytes) { - if (bytes.length > 8192) - throw new Error("input is too large"); - const num2 = bytesToNumberBE(bytes); - const delta = bytes.length * 8 - CURVE.nBitLength; - return delta > 0 ? num2 >> BigInt(delta) : num2; - }; - const bits2int_modN = CURVE.bits2int_modN || function(bytes) { - return modN2(bits2int(bytes)); - }; - const ORDER_MASK = bitMask(CURVE.nBitLength); - function int2octets(num2) { - aInRange("num < 2^" + CURVE.nBitLength, num2, _0n5, ORDER_MASK); - return numberToBytesBE(num2, CURVE.nByteLength); - } - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (["recovered", "canonical"].some((k2) => k2 in opts)) - throw new Error("sign() legacy options not supported"); - const { hash: hash2, randomBytes: randomBytes2 } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; - if (lowS == null) - lowS = true; - msgHash = ensureBytes("msgHash", msgHash); - validateSigVerOpts(opts); - if (prehash) - msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); - const h1int = bits2int_modN(msgHash); - const d = normPrivateKeyToScalar(privateKey); - const seedArgs = [int2octets(d), int2octets(h1int)]; - if (ent != null && ent !== false) { - const e = ent === true ? randomBytes2(Fp2.BYTES) : ent; - seedArgs.push(ensureBytes("extraEntropy", e)); + _SHA3_IOTA.push(t); } - const seed = concatBytes3(...seedArgs); - const m2 = h1int; - function k2sig(kBytes) { - const k2 = bits2int(kBytes); - if (!isWithinCurveOrder(k2)) - return; - const ik = invN(k2); - const q2 = Point2.BASE.multiply(k2).toAffine(); - const r = modN2(q2.x); - if (r === _0n5) - return; - const s = modN2(ik * modN2(m2 + r * d)); - if (s === _0n5) - return; - let recovery = (q2.x === r ? 0 : 2) | Number(q2.y & _1n5); - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = normalizeS(s); - recovery ^= 1; + [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); + rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); + rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); + Keccak = class _Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + anumber(outputLen); + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error("Sha3 supports only keccak-f1600 function"); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); } - return new Signature(r, normS, recovery); - } - return { seed, k2sig }; + keccak() { + if (!isLE) + byteSwap32(this.state32); + keccakP(this.state32, this.rounds); + if (!isLE) + byteSwap32(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + aexists(this); + const { blockLen, state } = this; + data = toBytes2(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + state[pos] ^= suffix; + if ((suffix & 128) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 128; + this.keccak(); + } + writeInto(out) { + aexists(this, false); + abytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); + } + xof(bytes) { + anumber(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + aoutput(out, this); + if (this.finished) + throw new Error("digest() was already called"); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to2) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to2 || (to2 = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to2.state32.set(this.state32); + to2.pos = this.pos; + to2.posOut = this.posOut; + to2.finished = this.finished; + to2.rounds = rounds; + to2.suffix = suffix; + to2.outputLen = outputLen; + to2.enableXOF = enableXOF; + to2.destroyed = this.destroyed; + return to2; + } + }; + gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + sha3_224 = /* @__PURE__ */ gen(6, 144, 224 / 8); + sha3_256 = /* @__PURE__ */ gen(6, 136, 256 / 8); + sha3_384 = /* @__PURE__ */ gen(6, 104, 384 / 8); + sha3_512 = /* @__PURE__ */ gen(6, 72, 512 / 8); + keccak_224 = /* @__PURE__ */ gen(1, 144, 224 / 8); + keccak_256 = /* @__PURE__ */ gen(1, 136, 256 / 8); + keccak_384 = /* @__PURE__ */ gen(1, 104, 384 / 8); + keccak_512 = /* @__PURE__ */ gen(1, 72, 512 / 8); + genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true)); + shake128 = /* @__PURE__ */ genShake(31, 168, 128 / 8); + shake256 = /* @__PURE__ */ genShake(31, 136, 256 / 8); } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - function sign2(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); - const C = CURVE; - const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); - return drbg(seed, k2sig); +}); + +// node_modules/viem/_esm/utils/hash/keccak256.js +function keccak256(value, to_) { + const to2 = to_ || "hex"; + const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value); + if (to2 === "bytes") + return bytes; + return toHex(bytes); +} +var init_keccak256 = __esm({ + "node_modules/viem/_esm/utils/hash/keccak256.js"() { + init_sha3(); + init_isHex(); + init_toBytes(); + init_toHex(); } - Point2.BASE._setWindowSize(8); - function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { - const sg = signature; - msgHash = ensureBytes("msgHash", msgHash); - publicKey = ensureBytes("publicKey", publicKey); - const { lowS, prehash, format } = opts; - validateSigVerOpts(opts); - if ("strict" in opts) - throw new Error("options.strict was renamed to lowS"); - if (format !== void 0 && format !== "compact" && format !== "der") - throw new Error("format must be compact or der"); - const isHex2 = typeof sg === "string" || isBytes2(sg); - const isObj = !isHex2 && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint"; - if (!isHex2 && !isObj) - throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance"); - let _sig = void 0; - let P2; - try { - if (isObj) - _sig = new Signature(sg.r, sg.s); - if (isHex2) { - try { - if (format !== "compact") - _sig = Signature.fromDER(sg); - } catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; +}); + +// node_modules/viem/_esm/utils/hash/hashSignature.js +function hashSignature(sig) { + return hash(sig); +} +var hash; +var init_hashSignature = __esm({ + "node_modules/viem/_esm/utils/hash/hashSignature.js"() { + init_toBytes(); + init_keccak256(); + hash = (value) => keccak256(toBytes(value)); + } +}); + +// node_modules/viem/_esm/utils/hash/normalizeSignature.js +function normalizeSignature(signature) { + let active = true; + let current = ""; + let level = 0; + let result = ""; + let valid = false; + for (let i = 0; i < signature.length; i++) { + const char = signature[i]; + if (["(", ")", ","].includes(char)) + active = true; + if (char === "(") + level++; + if (char === ")") + level--; + if (!active) + continue; + if (level === 0) { + if (char === " " && ["event", "function", ""].includes(result)) + result = ""; + else { + result += char; + if (char === ")") { + valid = true; + break; } - if (!_sig && format !== "der") - _sig = Signature.fromCompact(sg); } - P2 = Point2.fromHex(publicKey); - } catch (error) { - return false; + continue; } - if (!_sig) - return false; - if (lowS && _sig.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r, s } = _sig; - const h = bits2int_modN(msgHash); - const is2 = invN(s); - const u1 = modN2(h * is2); - const u2 = modN2(r * is2); - const R2 = Point2.BASE.multiplyAndAddUnsafe(P2, u1, u2)?.toAffine(); - if (!R2) - return false; - const v = modN2(R2.x); - return v === r; + if (char === " ") { + if (signature[i - 1] !== "," && current !== "," && current !== ",(") { + current = ""; + active = false; + } + continue; + } + result += char; + current += char; } - return { - CURVE, - getPublicKey, - getSharedSecret, - sign: sign2, - verify, - ProjectivePoint: Point2, - Signature, - utils - }; + if (!valid) + throw new BaseError2("Unable to normalize signature."); + return result; } -function SWUFpSqrtRatio(Fp2, Z2) { - const q2 = Fp2.ORDER; - let l = _0n5; - for (let o = q2 - _1n5; o % _2n4 === _0n5; o /= _2n4) - l += _1n5; - const c1 = l; - const _2n_pow_c1_1 = _2n4 << c1 - _1n5 - _1n5; - const _2n_pow_c1 = _2n_pow_c1_1 * _2n4; - const c2 = (q2 - _1n5) / _2n_pow_c1; - const c3 = (c2 - _1n5) / _2n4; - const c4 = _2n_pow_c1 - _1n5; - const c5 = _2n_pow_c1_1; - const c6 = Fp2.pow(Z2, c2); - const c7 = Fp2.pow(Z2, (c2 + _1n5) / _2n4); - let sqrtRatio = (u, v) => { - let tv1 = c6; - let tv2 = Fp2.pow(v, c4); - let tv3 = Fp2.sqr(tv2); - tv3 = Fp2.mul(tv3, v); - let tv5 = Fp2.mul(u, tv3); - tv5 = Fp2.pow(tv5, c3); - tv5 = Fp2.mul(tv5, tv2); - tv2 = Fp2.mul(tv5, v); - tv3 = Fp2.mul(tv5, u); - let tv4 = Fp2.mul(tv3, tv2); - tv5 = Fp2.pow(tv4, c5); - let isQR = Fp2.eql(tv5, Fp2.ONE); - tv2 = Fp2.mul(tv3, c7); - tv5 = Fp2.mul(tv4, tv1); - tv3 = Fp2.cmov(tv2, tv3, isQR); - tv4 = Fp2.cmov(tv5, tv4, isQR); - for (let i = c1; i > _1n5; i--) { - let tv52 = i - _2n4; - tv52 = _2n4 << tv52 - _1n5; - let tvv5 = Fp2.pow(tv4, tv52); - const e1 = Fp2.eql(tvv5, Fp2.ONE); - tv2 = Fp2.mul(tv3, tv1); - tv1 = Fp2.mul(tv1, tv1); - tvv5 = Fp2.mul(tv4, tv1); - tv3 = Fp2.cmov(tv2, tv3, e1); - tv4 = Fp2.cmov(tvv5, tv4, e1); - } - return { isValid: isQR, value: tv3 }; - }; - if (Fp2.ORDER % _4n2 === _3n2) { - const c12 = (Fp2.ORDER - _3n2) / _4n2; - const c22 = Fp2.sqrt(Fp2.neg(Z2)); - sqrtRatio = (u, v) => { - let tv1 = Fp2.sqr(v); - const tv2 = Fp2.mul(u, v); - tv1 = Fp2.mul(tv1, tv2); - let y1 = Fp2.pow(tv1, c12); - y1 = Fp2.mul(y1, tv2); - const y2 = Fp2.mul(y1, c22); - const tv3 = Fp2.mul(Fp2.sqr(y1), v); - const isQR = Fp2.eql(tv3, u); - let y3 = Fp2.cmov(y2, y1, isQR); - return { isValid: isQR, value: y3 }; +var init_normalizeSignature = __esm({ + "node_modules/viem/_esm/utils/hash/normalizeSignature.js"() { + init_base(); + } +}); + +// node_modules/viem/_esm/utils/hash/toSignature.js +var toSignature; +var init_toSignature = __esm({ + "node_modules/viem/_esm/utils/hash/toSignature.js"() { + init_exports(); + init_normalizeSignature(); + toSignature = (def) => { + const def_ = (() => { + if (typeof def === "string") + return def; + return formatAbiItem(def); + })(); + return normalizeSignature(def_); }; } - return sqrtRatio; -} -function mapToCurveSimpleSWU(Fp2, opts) { - validateField(Fp2); - if (!Fp2.isValid(opts.A) || !Fp2.isValid(opts.B) || !Fp2.isValid(opts.Z)) - throw new Error("mapToCurveSimpleSWU: invalid opts"); - const sqrtRatio = SWUFpSqrtRatio(Fp2, opts.Z); - if (!Fp2.isOdd) - throw new Error("Fp.isOdd is not implemented!"); - return (u) => { - let tv1, tv2, tv3, tv4, tv5, tv6, x2, y2; - tv1 = Fp2.sqr(u); - tv1 = Fp2.mul(tv1, opts.Z); - tv2 = Fp2.sqr(tv1); - tv2 = Fp2.add(tv2, tv1); - tv3 = Fp2.add(tv2, Fp2.ONE); - tv3 = Fp2.mul(tv3, opts.B); - tv4 = Fp2.cmov(opts.Z, Fp2.neg(tv2), !Fp2.eql(tv2, Fp2.ZERO)); - tv4 = Fp2.mul(tv4, opts.A); - tv2 = Fp2.sqr(tv3); - tv6 = Fp2.sqr(tv4); - tv5 = Fp2.mul(tv6, opts.A); - tv2 = Fp2.add(tv2, tv5); - tv2 = Fp2.mul(tv2, tv3); - tv6 = Fp2.mul(tv6, tv4); - tv5 = Fp2.mul(tv6, opts.B); - tv2 = Fp2.add(tv2, tv5); - x2 = Fp2.mul(tv1, tv3); - const { isValid, value } = sqrtRatio(tv2, tv6); - y2 = Fp2.mul(tv1, u); - y2 = Fp2.mul(y2, value); - x2 = Fp2.cmov(x2, tv3, isValid); - y2 = Fp2.cmov(y2, value, isValid); - const e1 = Fp2.isOdd(u) === Fp2.isOdd(y2); - y2 = Fp2.cmov(Fp2.neg(y2), y2, e1); - x2 = Fp2.div(x2, tv4); - return { x: x2, y: y2 }; - }; +}); + +// node_modules/viem/_esm/utils/hash/toSignatureHash.js +function toSignatureHash(fn2) { + return hashSignature(toSignature(fn2)); } -var b2n, h2b, DERErr, DER, _0n5, _1n5, _2n4, _3n2, _4n2; -var init_weierstrass = __esm({ - "node_modules/viem/node_modules/@noble/curves/esm/abstract/weierstrass.js"() { - init_curve(); - init_modular(); - init_utils4(); - init_utils4(); - ({ bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports2); - DERErr = class extends Error { - constructor(m2 = "") { - super(m2); +var init_toSignatureHash = __esm({ + "node_modules/viem/_esm/utils/hash/toSignatureHash.js"() { + init_hashSignature(); + init_toSignature(); + } +}); + +// node_modules/viem/_esm/utils/hash/toEventSelector.js +var toEventSelector; +var init_toEventSelector = __esm({ + "node_modules/viem/_esm/utils/hash/toEventSelector.js"() { + init_toSignatureHash(); + toEventSelector = toSignatureHash; + } +}); + +// node_modules/viem/_esm/errors/address.js +var InvalidAddressError; +var init_address = __esm({ + "node_modules/viem/_esm/errors/address.js"() { + init_base(); + InvalidAddressError = class extends BaseError2 { + constructor({ address }) { + super(`Address "${address}" is invalid.`, { + metaMessages: [ + "- Address must be a hex value of 20 bytes (40 hex characters).", + "- Address must match its checksum counterpart." + ], + name: "InvalidAddressError" + }); } }; - DER = { - // asn.1 DER encoding utils - Err: DERErr, - // Basic building block is TLV (Tag-Length-Value) - _tlv: { - encode: (tag, data) => { - const { Err: E } = DER; - if (tag < 0 || tag > 256) - throw new E("tlv.encode: wrong tag"); - if (data.length & 1) - throw new E("tlv.encode: unpadded data"); - const dataLen = data.length / 2; - const len = numberToHexUnpadded(dataLen); - if (len.length / 2 & 128) - throw new E("tlv.encode: long form length too big"); - const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; - const t = numberToHexUnpadded(tag); - return t + lenLen + len + data; - }, - // v - value, l - left bytes (unparsed) - decode(tag, data) { - const { Err: E } = DER; - let pos = 0; - if (tag < 0 || tag > 256) - throw new E("tlv.encode: wrong tag"); - if (data.length < 2 || data[pos++] !== tag) - throw new E("tlv.decode: wrong tlv"); - const first = data[pos++]; - const isLong = !!(first & 128); - let length = 0; - if (!isLong) - length = first; - else { - const lenLen = first & 127; - if (!lenLen) - throw new E("tlv.decode(long): indefinite length not supported"); - if (lenLen > 4) - throw new E("tlv.decode(long): byte length is too big"); - const lengthBytes = data.subarray(pos, pos + lenLen); - if (lengthBytes.length !== lenLen) - throw new E("tlv.decode: length bytes not complete"); - if (lengthBytes[0] === 0) - throw new E("tlv.decode(long): zero leftmost byte"); - for (const b2 of lengthBytes) - length = length << 8 | b2; - pos += lenLen; - if (length < 128) - throw new E("tlv.decode(long): not minimal encoding"); - } - const v = data.subarray(pos, pos + length); - if (v.length !== length) - throw new E("tlv.decode: wrong value length"); - return { v, l: data.subarray(pos + length) }; + } +}); + +// node_modules/viem/_esm/utils/lru.js +var LruMap; +var init_lru = __esm({ + "node_modules/viem/_esm/utils/lru.js"() { + LruMap = class extends Map { + constructor(size5) { + super(); + Object.defineProperty(this, "maxSize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxSize = size5; + } + get(key) { + const value = super.get(key); + if (super.has(key) && value !== void 0) { + this.delete(key); + super.set(key, value); } - }, - // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, - // since we always use positive integers here. It must always be empty: - // - add zero byte if exists - // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) - _int: { - encode(num2) { - const { Err: E } = DER; - if (num2 < _0n5) - throw new E("integer: negative integers are not allowed"); - let hex = numberToHexUnpadded(num2); - if (Number.parseInt(hex[0], 16) & 8) - hex = "00" + hex; - if (hex.length & 1) - throw new E("unexpected DER parsing assertion: unpadded hex"); - return hex; - }, - decode(data) { - const { Err: E } = DER; - if (data[0] & 128) - throw new E("invalid signature integer: negative"); - if (data[0] === 0 && !(data[1] & 128)) - throw new E("invalid signature integer: unnecessary leading zero"); - return b2n(data); + return value; + } + set(key, value) { + super.set(key, value); + if (this.maxSize && this.size > this.maxSize) { + const firstKey = this.keys().next().value; + if (firstKey) + this.delete(firstKey); } - }, - toSig(hex) { - const { Err: E, _int: int, _tlv: tlv } = DER; - const data = typeof hex === "string" ? h2b(hex) : hex; - abytes2(data); - const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); - if (seqLeftBytes.length) - throw new E("invalid signature: left bytes after parsing"); - const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); - const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); - if (sLeftBytes.length) - throw new E("invalid signature: left bytes after parsing"); - return { r: int.decode(rBytes), s: int.decode(sBytes) }; - }, - hexFromSig(sig) { - const { _tlv: tlv, _int: int } = DER; - const rs2 = tlv.encode(2, int.encode(sig.r)); - const ss = tlv.encode(2, int.encode(sig.s)); - const seq = rs2 + ss; - return tlv.encode(48, seq); + return this; } }; - _0n5 = BigInt(0); - _1n5 = BigInt(1); - _2n4 = BigInt(2); - _3n2 = BigInt(3); - _4n2 = BigInt(4); } }); -// node_modules/viem/node_modules/@noble/curves/esm/_shortw_utils.js -function getHash(hash2) { - return { - hash: hash2, - hmac: (key, ...msgs) => hmac(hash2, key, concatBytes(...msgs)), - randomBytes - }; +// node_modules/viem/_esm/utils/address/getAddress.js +function checksumAddress(address_, chainId) { + if (checksumAddressCache.has(`${address_}.${chainId}`)) + return checksumAddressCache.get(`${address_}.${chainId}`); + const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase(); + const hash2 = keccak256(stringToBytes(hexAddress), "bytes"); + const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split(""); + for (let i = 0; i < 40; i += 2) { + if (hash2[i >> 1] >> 4 >= 8 && address[i]) { + address[i] = address[i].toUpperCase(); + } + if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) { + address[i + 1] = address[i + 1].toUpperCase(); + } + } + const result = `0x${address.join("")}`; + checksumAddressCache.set(`${address_}.${chainId}`, result); + return result; } -function createCurve(curveDef, defHash) { - const create = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) }); - return { ...create(defHash), create }; +function getAddress(address, chainId) { + if (!isAddress(address, { strict: false })) + throw new InvalidAddressError({ address }); + return checksumAddress(address, chainId); } -var init_shortw_utils = __esm({ - "node_modules/viem/node_modules/@noble/curves/esm/_shortw_utils.js"() { - init_hmac(); - init_utils2(); - init_weierstrass(); +var checksumAddressCache; +var init_getAddress = __esm({ + "node_modules/viem/_esm/utils/address/getAddress.js"() { + init_address(); + init_toBytes(); + init_keccak256(); + init_lru(); + init_isAddress(); + checksumAddressCache = /* @__PURE__ */ new LruMap(8192); } }); -// node_modules/viem/node_modules/@noble/curves/esm/abstract/hash-to-curve.js -function i2osp(value, length) { - anum(value); - anum(length); - if (value < 0 || value >= 1 << 8 * length) - throw new Error("invalid I2OSP input: " + value); - const res = Array.from({ length }).fill(0); - for (let i = length - 1; i >= 0; i--) { - res[i] = value & 255; - value >>>= 8; - } - return new Uint8Array(res); +// node_modules/viem/_esm/utils/address/isAddress.js +function isAddress(address, options) { + const { strict = true } = options ?? {}; + const cacheKey2 = `${address}.${strict}`; + if (isAddressCache.has(cacheKey2)) + return isAddressCache.get(cacheKey2); + const result = (() => { + if (!addressRegex.test(address)) + return false; + if (address.toLowerCase() === address) + return true; + if (strict) + return checksumAddress(address) === address; + return true; + })(); + isAddressCache.set(cacheKey2, result); + return result; } -function strxor(a, b2) { - const arr = new Uint8Array(a.length); - for (let i = 0; i < a.length; i++) { - arr[i] = a[i] ^ b2[i]; +var addressRegex, isAddressCache; +var init_isAddress = __esm({ + "node_modules/viem/_esm/utils/address/isAddress.js"() { + init_lru(); + init_getAddress(); + addressRegex = /^0x[a-fA-F0-9]{40}$/; + isAddressCache = /* @__PURE__ */ new LruMap(8192); } - return arr; -} -function anum(item) { - if (!Number.isSafeInteger(item)) - throw new Error("number expected"); +}); + +// node_modules/viem/_esm/utils/data/concat.js +function concat(values) { + if (typeof values[0] === "string") + return concatHex(values); + return concatBytes2(values); } -function expand_message_xmd(msg, DST, lenInBytes, H2) { - abytes2(msg); - abytes2(DST); - anum(lenInBytes); - if (DST.length > 255) - DST = H2(concatBytes3(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST)); - const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H2; - const ell = Math.ceil(lenInBytes / b_in_bytes); - if (lenInBytes > 65535 || ell > 255) - throw new Error("expand_message_xmd: invalid lenInBytes"); - const DST_prime = concatBytes3(DST, i2osp(DST.length, 1)); - const Z_pad = i2osp(0, r_in_bytes); - const l_i_b_str = i2osp(lenInBytes, 2); - const b2 = new Array(ell); - const b_0 = H2(concatBytes3(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); - b2[0] = H2(concatBytes3(b_0, i2osp(1, 1), DST_prime)); - for (let i = 1; i <= ell; i++) { - const args = [strxor(b_0, b2[i - 1]), i2osp(i + 1, 1), DST_prime]; - b2[i] = H2(concatBytes3(...args)); +function concatBytes2(values) { + let length = 0; + for (const arr of values) { + length += arr.length; } - const pseudo_random_bytes = concatBytes3(...b2); - return pseudo_random_bytes.slice(0, lenInBytes); -} -function expand_message_xof(msg, DST, lenInBytes, k2, H2) { - abytes2(msg); - abytes2(DST); - anum(lenInBytes); - if (DST.length > 255) { - const dkLen = Math.ceil(2 * k2 / 8); - DST = H2.create({ dkLen }).update(utf8ToBytes2("H2C-OVERSIZE-DST-")).update(DST).digest(); + const result = new Uint8Array(length); + let offset = 0; + for (const arr of values) { + result.set(arr, offset); + offset += arr.length; } - if (lenInBytes > 65535 || DST.length > 255) - throw new Error("expand_message_xof: invalid lenInBytes"); - return H2.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); -} -function hash_to_field(msg, count, options) { - validateObject(options, { - DST: "stringOrUint8Array", - p: "bigint", - m: "isSafeInteger", - k: "isSafeInteger", - hash: "hash" - }); - const { p, k: k2, m: m2, hash: hash2, expand, DST: _DST } = options; - abytes2(msg); - anum(count); - const DST = typeof _DST === "string" ? utf8ToBytes2(_DST) : _DST; - const log2p = p.toString(2).length; - const L2 = Math.ceil((log2p + k2) / 8); - const len_in_bytes = count * m2 * L2; - let prb; - if (expand === "xmd") { - prb = expand_message_xmd(msg, DST, len_in_bytes, hash2); - } else if (expand === "xof") { - prb = expand_message_xof(msg, DST, len_in_bytes, k2, hash2); - } else if (expand === "_internal_pass") { - prb = msg; - } else { - throw new Error('expand must be "xmd" or "xof"'); + return result; +} +function concatHex(values) { + return `0x${values.reduce((acc, x2) => acc + x2.replace("0x", ""), "")}`; +} +var init_concat = __esm({ + "node_modules/viem/_esm/utils/data/concat.js"() { } - const u = new Array(count); - for (let i = 0; i < count; i++) { - const e = new Array(m2); - for (let j2 = 0; j2 < m2; j2++) { - const elm_offset = L2 * (j2 + i * m2); - const tv = prb.subarray(elm_offset, elm_offset + L2); - e[j2] = mod(os2ip(tv), p); - } - u[i] = e; +}); + +// node_modules/viem/_esm/utils/data/slice.js +function slice(value, start, end, { strict } = {}) { + if (isHex(value, { strict: false })) + return sliceHex(value, start, end, { + strict + }); + return sliceBytes(value, start, end, { + strict + }); +} +function assertStartOffset(value, start) { + if (typeof start === "number" && start > 0 && start > size(value) - 1) + throw new SliceOffsetOutOfBoundsError({ + offset: start, + position: "start", + size: size(value) + }); +} +function assertEndOffset(value, start, end) { + if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) { + throw new SliceOffsetOutOfBoundsError({ + offset: end, + position: "end", + size: size(value) + }); } - return u; } -function isogenyMap(field, map) { - const COEFF = map.map((i) => Array.from(i).reverse()); - return (x2, y2) => { - const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x2), i))); - x2 = field.div(xNum, xDen); - y2 = field.mul(y2, field.div(yNum, yDen)); - return { x: x2, y: y2 }; - }; +function sliceBytes(value_, start, end, { strict } = {}) { + assertStartOffset(value_, start); + const value = value_.slice(start, end); + if (strict) + assertEndOffset(value, start, end); + return value; } -function createHasher(Point2, mapToCurve, def) { - if (typeof mapToCurve !== "function") - throw new Error("mapToCurve() must be defined"); - return { - // Encodes byte string to elliptic curve. - // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 - hashToCurve(msg, options) { - const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); - const u0 = Point2.fromAffine(mapToCurve(u[0])); - const u1 = Point2.fromAffine(mapToCurve(u[1])); - const P2 = u0.add(u1).clearCofactor(); - P2.assertValidity(); - return P2; - }, - // Encodes byte string to elliptic curve. - // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 - encodeToCurve(msg, options) { - const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); - const P2 = Point2.fromAffine(mapToCurve(u[0])).clearCofactor(); - P2.assertValidity(); - return P2; - }, - // Same as encodeToCurve, but without hash - mapToCurve(scalars) { - if (!Array.isArray(scalars)) - throw new Error("mapToCurve: expected array of bigints"); - for (const i of scalars) - if (typeof i !== "bigint") - throw new Error("mapToCurve: expected array of bigints"); - const P2 = Point2.fromAffine(mapToCurve(scalars)).clearCofactor(); - P2.assertValidity(); - return P2; - } - }; +function sliceHex(value_, start, end, { strict } = {}) { + assertStartOffset(value_, start); + const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`; + if (strict) + assertEndOffset(value, start, end); + return value; } -var os2ip; -var init_hash_to_curve = __esm({ - "node_modules/viem/node_modules/@noble/curves/esm/abstract/hash-to-curve.js"() { - init_modular(); - init_utils4(); - os2ip = bytesToNumberBE; +var init_slice = __esm({ + "node_modules/viem/_esm/utils/data/slice.js"() { + init_data(); + init_isHex(); + init_size(); } }); -// node_modules/viem/node_modules/@noble/curves/esm/secp256k1.js -var secp256k1_exports = {}; -__export(secp256k1_exports, { - encodeToCurve: () => encodeToCurve, - hashToCurve: () => hashToCurve, - schnorr: () => schnorr, - secp256k1: () => secp256k1 +// node_modules/viem/_esm/utils/regex.js +var bytesRegex2, integerRegex2; +var init_regex2 = __esm({ + "node_modules/viem/_esm/utils/regex.js"() { + bytesRegex2 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; + integerRegex2 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; + } }); -function sqrtMod(y2) { - const P2 = secp256k1P; - const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y2 * y2 * y2 % P2; - const b3 = b2 * b2 * y2 % P2; - const b6 = pow2(b3, _3n3, P2) * b3 % P2; - const b9 = pow2(b6, _3n3, P2) * b3 % P2; - const b11 = pow2(b9, _2n5, P2) * b2 % P2; - const b22 = pow2(b11, _11n, P2) * b11 % P2; - const b44 = pow2(b22, _22n, P2) * b22 % P2; - const b88 = pow2(b44, _44n, P2) * b44 % P2; - const b176 = pow2(b88, _88n, P2) * b88 % P2; - const b220 = pow2(b176, _44n, P2) * b44 % P2; - const b223 = pow2(b220, _3n3, P2) * b3 % P2; - const t1 = pow2(b223, _23n, P2) * b22 % P2; - const t2 = pow2(t1, _6n, P2) * b2 % P2; - const root = pow2(t2, _2n5, P2); - if (!Fpk1.eql(Fpk1.sqr(root), y2)) - throw new Error("Cannot find square root"); - return root; + +// node_modules/viem/_esm/utils/abi/encodeAbiParameters.js +function encodeAbiParameters(params, values) { + if (params.length !== values.length) + throw new AbiEncodingLengthMismatchError({ + expectedLength: params.length, + givenLength: values.length + }); + const preparedParams = prepareParams({ + params, + values + }); + const data = encodeParams(preparedParams); + if (data.length === 0) + return "0x"; + return data; } -function taggedHash(tag, ...messages) { - let tagP = TAGGED_HASH_PREFIXES[tag]; - if (tagP === void 0) { - const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); - tagP = concatBytes3(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; +function prepareParams({ params, values }) { + const preparedParams = []; + for (let i = 0; i < params.length; i++) { + preparedParams.push(prepareParam({ param: params[i], value: values[i] })); } - return sha256(concatBytes3(tagP, ...messages)); + return preparedParams; } -function schnorrGetExtPubKey(priv) { - let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); - let p = Point.fromPrivateKey(d_); - const scalar = p.hasEvenY() ? d_ : modN(-d_); - return { scalar, bytes: pointToBytes(p) }; +function prepareParam({ param, value }) { + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return encodeArray(value, { length, param: { ...param, type } }); + } + if (param.type === "tuple") { + return encodeTuple(value, { + param + }); + } + if (param.type === "address") { + return encodeAddress(value); + } + if (param.type === "bool") { + return encodeBool(value); + } + if (param.type.startsWith("uint") || param.type.startsWith("int")) { + const signed = param.type.startsWith("int"); + const [, , size5 = "256"] = integerRegex2.exec(param.type) ?? []; + return encodeNumber(value, { + signed, + size: Number(size5) + }); + } + if (param.type.startsWith("bytes")) { + return encodeBytes(value, { param }); + } + if (param.type === "string") { + return encodeString(value); + } + throw new InvalidAbiEncodingTypeError(param.type, { + docsPath: "/docs/contract/encodeAbiParameters" + }); } -function lift_x(x2) { - aInRange("x", x2, _1n6, secp256k1P); - const xx = modP(x2 * x2); - const c = modP(xx * x2 + BigInt(7)); - let y2 = sqrtMod(c); - if (y2 % _2n5 !== _0n6) - y2 = modP(-y2); - const p = new Point(x2, y2, _1n6); - p.assertValidity(); - return p; +function encodeParams(preparedParams) { + let staticSize = 0; + for (let i = 0; i < preparedParams.length; i++) { + const { dynamic, encoded } = preparedParams[i]; + if (dynamic) + staticSize += 32; + else + staticSize += size(encoded); + } + const staticParams = []; + const dynamicParams = []; + let dynamicSize = 0; + for (let i = 0; i < preparedParams.length; i++) { + const { dynamic, encoded } = preparedParams[i]; + if (dynamic) { + staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 })); + dynamicParams.push(encoded); + dynamicSize += size(encoded); + } else { + staticParams.push(encoded); + } + } + return concat([...staticParams, ...dynamicParams]); } -function challenge(...args) { - return modN(num(taggedHash("BIP0340/challenge", ...args))); +function encodeAddress(value) { + if (!isAddress(value)) + throw new InvalidAddressError({ address: value }); + return { dynamic: false, encoded: padHex(value.toLowerCase()) }; } -function schnorrGetPublicKey(privateKey) { - return schnorrGetExtPubKey(privateKey).bytes; +function encodeArray(value, { length, param }) { + const dynamic = length === null; + if (!Array.isArray(value)) + throw new InvalidArrayError(value); + if (!dynamic && value.length !== length) + throw new AbiEncodingArrayLengthMismatchError({ + expectedLength: length, + givenLength: value.length, + type: `${param.type}[${length}]` + }); + let dynamicChild = false; + const preparedParams = []; + for (let i = 0; i < value.length; i++) { + const preparedParam = prepareParam({ param, value: value[i] }); + if (preparedParam.dynamic) + dynamicChild = true; + preparedParams.push(preparedParam); + } + if (dynamic || dynamicChild) { + const data = encodeParams(preparedParams); + if (dynamic) { + const length2 = numberToHex(preparedParams.length, { size: 32 }); + return { + dynamic: true, + encoded: preparedParams.length > 0 ? concat([length2, data]) : length2 + }; + } + if (dynamicChild) + return { dynamic: true, encoded: data }; + } + return { + dynamic: false, + encoded: concat(preparedParams.map(({ encoded }) => encoded)) + }; } -function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { - const m2 = ensureBytes("message", message); - const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); - const a = ensureBytes("auxRand", auxRand, 32); - const t = numTo32b(d ^ num(taggedHash("BIP0340/aux", a))); - const rand = taggedHash("BIP0340/nonce", t, px, m2); - const k_ = modN(num(rand)); - if (k_ === _0n6) - throw new Error("sign failed: k is zero"); - const { bytes: rx, scalar: k2 } = schnorrGetExtPubKey(k_); - const e = challenge(rx, px, m2); - const sig = new Uint8Array(64); - sig.set(rx, 0); - sig.set(numTo32b(modN(k2 + e * d)), 32); - if (!schnorrVerify(sig, m2, px)) - throw new Error("sign: Invalid signature produced"); - return sig; +function encodeBytes(value, { param }) { + const [, paramSize] = param.type.split("bytes"); + const bytesSize = size(value); + if (!paramSize) { + let value_ = value; + if (bytesSize % 32 !== 0) + value_ = padHex(value_, { + dir: "right", + size: Math.ceil((value.length - 2) / 2 / 32) * 32 + }); + return { + dynamic: true, + encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]) + }; + } + if (bytesSize !== Number.parseInt(paramSize)) + throw new AbiEncodingBytesSizeMismatchError({ + expectedSize: Number.parseInt(paramSize), + value + }); + return { dynamic: false, encoded: padHex(value, { dir: "right" }) }; } -function schnorrVerify(signature, message, publicKey) { - const sig = ensureBytes("signature", signature, 64); - const m2 = ensureBytes("message", message); - const pub = ensureBytes("publicKey", publicKey, 32); - try { - const P2 = lift_x(num(pub)); - const r = num(sig.subarray(0, 32)); - if (!inRange(r, _1n6, secp256k1P)) - return false; - const s = num(sig.subarray(32, 64)); - if (!inRange(s, _1n6, secp256k1N)) - return false; - const e = challenge(numTo32b(r), pointToBytes(P2), m2); - const R2 = GmulAdd(P2, s, modN(-e)); - if (!R2 || !R2.hasEvenY() || R2.toAffine().x !== r) - return false; - return true; - } catch (error) { - return false; +function encodeBool(value) { + if (typeof value !== "boolean") + throw new BaseError2(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); + return { dynamic: false, encoded: padHex(boolToHex(value)) }; +} +function encodeNumber(value, { signed, size: size5 = 256 }) { + if (typeof size5 === "number") { + const max = 2n ** (BigInt(size5) - (signed ? 1n : 0n)) - 1n; + const min = signed ? -max - 1n : 0n; + if (value > max || value < min) + throw new IntegerOutOfRangeError({ + max: max.toString(), + min: min.toString(), + signed, + size: size5 / 8, + value: value.toString() + }); } + return { + dynamic: false, + encoded: numberToHex(value, { + size: 32, + signed + }) + }; } -var secp256k1P, secp256k1N, _1n6, _2n5, divNearest, Fpk1, secp256k1, _0n6, TAGGED_HASH_PREFIXES, pointToBytes, numTo32b, modP, modN, Point, GmulAdd, num, schnorr, isoMap, mapSWU, htf, hashToCurve, encodeToCurve; -var init_secp256k1 = __esm({ - "node_modules/viem/node_modules/@noble/curves/esm/secp256k1.js"() { - init_sha256(); - init_utils2(); - init_shortw_utils(); - init_hash_to_curve(); - init_modular(); - init_utils4(); - init_weierstrass(); - secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); - secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); - _1n6 = BigInt(1); - _2n5 = BigInt(2); - divNearest = (a, b2) => (a + b2 / _2n5) / b2; - Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); - secp256k1 = createCurve({ - a: BigInt(0), - // equation params: a, b - b: BigInt(7), - Fp: Fpk1, - // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n - n: secp256k1N, - // Curve order, total count of valid points in the field - // Base point (x, y) aka generator point - Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), - h: BigInt(1), - // Cofactor - lowS: true, - // Allow only low-S signatures by default in sign() and verify() - endo: { - // Endomorphism, see above - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - splitScalar: (k2) => { - const n = secp256k1N; - const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); - const b1 = -_1n6 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); - const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); - const b2 = a1; - const POW_2_128 = BigInt("0x100000000000000000000000000000000"); - const c1 = divNearest(b2 * k2, n); - const c2 = divNearest(-b1 * k2, n); - let k1 = mod(k2 - c1 * a1 - c2 * a2, n); - let k22 = mod(-c1 * b1 - c2 * b2, n); - const k1neg = k1 > POW_2_128; - const k2neg = k22 > POW_2_128; - if (k1neg) - k1 = n - k1; - if (k2neg) - k22 = n - k22; - if (k1 > POW_2_128 || k22 > POW_2_128) { - throw new Error("splitScalar: Endomorphism failed, k=" + k2); - } - return { k1neg, k1, k2neg, k2: k22 }; - } - } - }, sha256); - _0n6 = BigInt(0); - TAGGED_HASH_PREFIXES = {}; - pointToBytes = (point) => point.toRawBytes(true).slice(1); - numTo32b = (n) => numberToBytesBE(n, 32); - modP = (x2) => mod(x2, secp256k1P); - modN = (x2) => mod(x2, secp256k1N); - Point = secp256k1.ProjectivePoint; - GmulAdd = (Q, a, b2) => Point.BASE.multiplyAndAddUnsafe(Q, a, b2); - num = bytesToNumberBE; - schnorr = /* @__PURE__ */ (() => ({ - getPublicKey: schnorrGetPublicKey, - sign: schnorrSign, - verify: schnorrVerify, - utils: { - randomPrivateKey: secp256k1.utils.randomPrivateKey, - lift_x, - pointToBytes, - numberToBytesBE, - bytesToNumberBE, - taggedHash, - mod - } - }))(); - isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [ - // xNum - [ - "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", - "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", - "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", - "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" - ], - // xDen - [ - "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", - "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", - "0x0000000000000000000000000000000000000000000000000000000000000001" - // LAST 1 - ], - // yNum - [ - "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", - "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", - "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", - "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" - ], - // yDen - [ - "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", - "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", - "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", - "0x0000000000000000000000000000000000000000000000000000000000000001" - // LAST 1 - ] - ].map((i) => i.map((j2) => BigInt(j2)))))(); - mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, { - A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), - B: BigInt("1771"), - Z: Fpk1.create(BigInt("-11")) - }))(); - htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { - const { x: x2, y: y2 } = mapSWU(Fpk1.create(scalars[0])); - return isoMap(x2, y2); - }, { - DST: "secp256k1_XMD:SHA-256_SSWU_RO_", - encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", - p: Fpk1.ORDER, - m: 1, - k: 128, - expand: "xmd", - hash: sha256 - }))(); - hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); - encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); +function encodeString(value) { + const hexValue = stringToHex(value); + const partsLength = Math.ceil(size(hexValue) / 32); + const parts = []; + for (let i = 0; i < partsLength; i++) { + parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), { + dir: "right" + })); + } + return { + dynamic: true, + encoded: concat([ + padHex(numberToHex(size(hexValue), { size: 32 })), + ...parts + ]) + }; +} +function encodeTuple(value, { param }) { + let dynamic = false; + const preparedParams = []; + for (let i = 0; i < param.components.length; i++) { + const param_ = param.components[i]; + const index2 = Array.isArray(value) ? i : param_.name; + const preparedParam = prepareParam({ + param: param_, + value: value[index2] + }); + preparedParams.push(preparedParam); + if (preparedParam.dynamic) + dynamic = true; + } + return { + dynamic, + encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded)) + }; +} +function getArrayComponents(type) { + const matches = type.match(/^(.*)\[(\d+)?\]$/); + return matches ? ( + // Return `null` if the array is dynamic. + [matches[2] ? Number(matches[2]) : null, matches[1]] + ) : void 0; +} +var init_encodeAbiParameters = __esm({ + "node_modules/viem/_esm/utils/abi/encodeAbiParameters.js"() { + init_abi(); + init_address(); + init_base(); + init_encoding(); + init_isAddress(); + init_concat(); + init_pad(); + init_size(); + init_slice(); + init_toHex(); + init_regex2(); } }); -// node_modules/viem/_esm/errors/node.js -var ExecutionRevertedError, FeeCapTooHighError, FeeCapTooLowError, NonceTooHighError, NonceTooLowError, NonceMaxValueError, InsufficientFundsError, IntrinsicGasTooHighError, IntrinsicGasTooLowError, TransactionTypeNotSupportedError, TipAboveFeeCapError, UnknownNodeError; -var init_node = __esm({ - "node_modules/viem/_esm/errors/node.js"() { - init_formatGwei(); - init_base(); - ExecutionRevertedError = class extends BaseError2 { - constructor({ cause, message } = {}) { - const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", ""); - super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, { - cause, - name: "ExecutionRevertedError" - }); - } - }; - Object.defineProperty(ExecutionRevertedError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 3 - }); - Object.defineProperty(ExecutionRevertedError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /execution reverted/ +// node_modules/viem/_esm/utils/hash/toFunctionSelector.js +var toFunctionSelector; +var init_toFunctionSelector = __esm({ + "node_modules/viem/_esm/utils/hash/toFunctionSelector.js"() { + init_slice(); + init_toSignatureHash(); + toFunctionSelector = (fn2) => slice(toSignatureHash(fn2), 0, 4); + } +}); + +// node_modules/viem/_esm/utils/abi/getAbiItem.js +function getAbiItem(parameters) { + const { abi: abi4, args = [], name } = parameters; + const isSelector = isHex(name, { strict: false }); + const abiItems = abi4.filter((abiItem) => { + if (isSelector) { + if (abiItem.type === "function") + return toFunctionSelector(abiItem) === name; + if (abiItem.type === "event") + return toEventSelector(abiItem) === name; + return false; + } + return "name" in abiItem && abiItem.name === name; + }); + if (abiItems.length === 0) + return void 0; + if (abiItems.length === 1) + return abiItems[0]; + let matchedAbiItem = void 0; + for (const abiItem of abiItems) { + if (!("inputs" in abiItem)) + continue; + if (!args || args.length === 0) { + if (!abiItem.inputs || abiItem.inputs.length === 0) + return abiItem; + continue; + } + if (!abiItem.inputs) + continue; + if (abiItem.inputs.length === 0) + continue; + if (abiItem.inputs.length !== args.length) + continue; + const matched = args.every((arg, index2) => { + const abiParameter = "inputs" in abiItem && abiItem.inputs[index2]; + if (!abiParameter) + return false; + return isArgOfType(arg, abiParameter); }); - FeeCapTooHighError = class extends BaseError2 { - constructor({ cause, maxFeePerGas } = {}) { - super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, { - cause, - name: "FeeCapTooHighError" - }); + if (matched) { + if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { + const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args); + if (ambiguousTypes) + throw new AbiItemAmbiguityError({ + abiItem, + type: ambiguousTypes[0] + }, { + abiItem: matchedAbiItem, + type: ambiguousTypes[1] + }); } - }; - Object.defineProperty(FeeCapTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/ - }); - FeeCapTooLowError = class extends BaseError2 { - constructor({ cause, maxFeePerGas } = {}) { - super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, { - cause, - name: "FeeCapTooLowError" + matchedAbiItem = abiItem; + } + } + if (matchedAbiItem) + return matchedAbiItem; + return abiItems[0]; +} +function isArgOfType(arg, abiParameter) { + const argType = typeof arg; + const abiParameterType = abiParameter.type; + switch (abiParameterType) { + case "address": + return isAddress(arg, { strict: false }); + case "bool": + return argType === "boolean"; + case "function": + return argType === "string"; + case "string": + return argType === "string"; + default: { + if (abiParameterType === "tuple" && "components" in abiParameter) + return Object.values(abiParameter.components).every((component, index2) => { + return isArgOfType(Object.values(arg)[index2], component); }); + if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) + return argType === "number" || argType === "bigint"; + if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) + return argType === "string" || arg instanceof Uint8Array; + if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { + return Array.isArray(arg) && arg.every((x2) => isArgOfType(x2, { + ...abiParameter, + // Pop off `[]` or `[M]` from end of type + type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") + })); } - }; - Object.defineProperty(FeeCapTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/ - }); - NonceTooHighError = class extends BaseError2 { - constructor({ cause, nonce } = {}) { - super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" }); - } - }; - Object.defineProperty(NonceTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce too high/ - }); - NonceTooLowError = class extends BaseError2 { - constructor({ cause, nonce } = {}) { - super([ - `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`, - "Try increasing the nonce or find the latest nonce with `getTransactionCount`." - ].join("\n"), { cause, name: "NonceTooLowError" }); - } - }; - Object.defineProperty(NonceTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce too low|transaction already imported|already known/ + return false; + } + } +} +function getAmbiguousTypes(sourceParameters, targetParameters, args) { + for (const parameterIndex in sourceParameters) { + const sourceParameter = sourceParameters[parameterIndex]; + const targetParameter = targetParameters[parameterIndex]; + if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) + return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]); + const types = [sourceParameter.type, targetParameter.type]; + const ambiguous = (() => { + if (types.includes("address") && types.includes("bytes20")) + return true; + if (types.includes("address") && types.includes("string")) + return isAddress(args[parameterIndex], { strict: false }); + if (types.includes("address") && types.includes("bytes")) + return isAddress(args[parameterIndex], { strict: false }); + return false; + })(); + if (ambiguous) + return types; + } + return; +} +var init_getAbiItem = __esm({ + "node_modules/viem/_esm/utils/abi/getAbiItem.js"() { + init_abi(); + init_isHex(); + init_isAddress(); + init_toEventSelector(); + init_toFunctionSelector(); + } +}); + +// node_modules/viem/_esm/accounts/utils/parseAccount.js +function parseAccount(account) { + if (typeof account === "string") + return { address: account, type: "json-rpc" }; + return account; +} +var init_parseAccount = __esm({ + "node_modules/viem/_esm/accounts/utils/parseAccount.js"() { + } +}); + +// node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js +function prepareEncodeFunctionData(parameters) { + const { abi: abi4, args, functionName } = parameters; + let abiItem = abi4[0]; + if (functionName) { + const item = getAbiItem({ + abi: abi4, + args, + name: functionName }); - NonceMaxValueError = class extends BaseError2 { - constructor({ cause, nonce } = {}) { - super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" }); - } + if (!item) + throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath2 }); + abiItem = item; + } + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath2 }); + return { + abi: [abiItem], + functionName: toFunctionSelector(formatAbiItem2(abiItem)) + }; +} +var docsPath2; +var init_prepareEncodeFunctionData = __esm({ + "node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js"() { + init_abi(); + init_toFunctionSelector(); + init_formatAbiItem2(); + init_getAbiItem(); + docsPath2 = "/docs/contract/encodeFunctionData"; + } +}); + +// node_modules/viem/_esm/utils/abi/encodeFunctionData.js +function encodeFunctionData(parameters) { + const { args } = parameters; + const { abi: abi4, functionName } = (() => { + if (parameters.abi.length === 1 && parameters.functionName?.startsWith("0x")) + return parameters; + return prepareEncodeFunctionData(parameters); + })(); + const abiItem = abi4[0]; + const signature = functionName; + const data = "inputs" in abiItem && abiItem.inputs ? encodeAbiParameters(abiItem.inputs, args ?? []) : void 0; + return concatHex([signature, data ?? "0x"]); +} +var init_encodeFunctionData = __esm({ + "node_modules/viem/_esm/utils/abi/encodeFunctionData.js"() { + init_concat(); + init_encodeAbiParameters(); + init_prepareEncodeFunctionData(); + } +}); + +// node_modules/viem/_esm/constants/solidity.js +var panicReasons, solidityError, solidityPanic; +var init_solidity = __esm({ + "node_modules/viem/_esm/constants/solidity.js"() { + panicReasons = { + 1: "An `assert` condition failed.", + 17: "Arithmetic operation resulted in underflow or overflow.", + 18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).", + 33: "Attempted to convert to an invalid type.", + 34: "Attempted to access a storage byte array that is incorrectly encoded.", + 49: "Performed `.pop()` on an empty array", + 50: "Array index is out of bounds.", + 65: "Allocated too much memory or created an array which is too large.", + 81: "Attempted to call a zero-initialized variable of internal function type." }; - Object.defineProperty(NonceMaxValueError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce has max value/ - }); - InsufficientFundsError = class extends BaseError2 { - constructor({ cause } = {}) { - super([ - "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account." - ].join("\n"), { - cause, - metaMessages: [ - "This error could arise when the account does not have enough funds to:", - " - pay for the total gas fee,", - " - pay for the value to send.", - " ", - "The cost of the transaction is calculated as `gas * gas fee + value`, where:", - " - `gas` is the amount of gas needed for transaction to execute,", - " - `gas fee` is the gas fee,", - " - `value` is the amount of ether to send to the recipient." - ], - name: "InsufficientFundsError" - }); - } + solidityError = { + inputs: [ + { + name: "message", + type: "string" + } + ], + name: "Error", + type: "error" }; - Object.defineProperty(InsufficientFundsError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /insufficient funds|exceeds transaction sender account balance/ - }); - IntrinsicGasTooHighError = class extends BaseError2 { - constructor({ cause, gas } = {}) { - super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, { - cause, - name: "IntrinsicGasTooHighError" - }); - } + solidityPanic = { + inputs: [ + { + name: "reason", + type: "uint256" + } + ], + name: "Panic", + type: "error" }; - Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /intrinsic gas too high|gas limit reached/ - }); - IntrinsicGasTooLowError = class extends BaseError2 { - constructor({ cause, gas } = {}) { - super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, { - cause, - name: "IntrinsicGasTooLowError" + } +}); + +// node_modules/viem/_esm/errors/cursor.js +var NegativeOffsetError, PositionOutOfBoundsError, RecursiveReadLimitExceededError; +var init_cursor = __esm({ + "node_modules/viem/_esm/errors/cursor.js"() { + init_base(); + NegativeOffsetError = class extends BaseError2 { + constructor({ offset }) { + super(`Offset \`${offset}\` cannot be negative.`, { + name: "NegativeOffsetError" }); } }; - Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /intrinsic gas too low/ - }); - TransactionTypeNotSupportedError = class extends BaseError2 { - constructor({ cause }) { - super("The transaction type is not supported for this chain.", { - cause, - name: "TransactionTypeNotSupportedError" - }); + PositionOutOfBoundsError = class extends BaseError2 { + constructor({ length, position }) { + super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" }); } }; - Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /transaction type not valid/ - }); - TipAboveFeeCapError = class extends BaseError2 { - constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) { - super([ - `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).` - ].join("\n"), { - cause, - name: "TipAboveFeeCapError" - }); + RecursiveReadLimitExceededError = class extends BaseError2 { + constructor({ count, limit }) { + super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: "RecursiveReadLimitExceededError" }); } }; - Object.defineProperty(TipAboveFeeCapError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/ - }); - UnknownNodeError = class extends BaseError2 { - constructor({ cause }) { - super(`An error occurred while executing: ${cause?.shortMessage}`, { - cause, - name: "UnknownNodeError" - }); + } +}); + +// node_modules/viem/_esm/utils/cursor.js +function createCursor(bytes, { recursiveReadLimit = 8192 } = {}) { + const cursor = Object.create(staticCursor); + cursor.bytes = bytes; + cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + cursor.positionReadCount = /* @__PURE__ */ new Map(); + cursor.recursiveReadLimit = recursiveReadLimit; + return cursor; +} +var staticCursor; +var init_cursor2 = __esm({ + "node_modules/viem/_esm/utils/cursor.js"() { + init_cursor(); + staticCursor = { + bytes: new Uint8Array(), + dataView: new DataView(new ArrayBuffer(0)), + position: 0, + positionReadCount: /* @__PURE__ */ new Map(), + recursiveReadCount: 0, + recursiveReadLimit: Number.POSITIVE_INFINITY, + assertReadLimit() { + if (this.recursiveReadCount >= this.recursiveReadLimit) + throw new RecursiveReadLimitExceededError({ + count: this.recursiveReadCount + 1, + limit: this.recursiveReadLimit + }); + }, + assertPosition(position) { + if (position < 0 || position > this.bytes.length - 1) + throw new PositionOutOfBoundsError({ + length: this.bytes.length, + position + }); + }, + decrementPosition(offset) { + if (offset < 0) + throw new NegativeOffsetError({ offset }); + const position = this.position - offset; + this.assertPosition(position); + this.position = position; + }, + getReadCount(position) { + return this.positionReadCount.get(position || this.position) || 0; + }, + incrementPosition(offset) { + if (offset < 0) + throw new NegativeOffsetError({ offset }); + const position = this.position + offset; + this.assertPosition(position); + this.position = position; + }, + inspectByte(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectBytes(length, position_) { + const position = position_ ?? this.position; + this.assertPosition(position + length - 1); + return this.bytes.subarray(position, position + length); + }, + inspectUint8(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectUint16(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 1); + return this.dataView.getUint16(position); + }, + inspectUint24(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 2); + return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); + }, + inspectUint32(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 3); + return this.dataView.getUint32(position); + }, + pushByte(byte) { + this.assertPosition(this.position); + this.bytes[this.position] = byte; + this.position++; + }, + pushBytes(bytes) { + this.assertPosition(this.position + bytes.length - 1); + this.bytes.set(bytes, this.position); + this.position += bytes.length; + }, + pushUint8(value) { + this.assertPosition(this.position); + this.bytes[this.position] = value; + this.position++; + }, + pushUint16(value) { + this.assertPosition(this.position + 1); + this.dataView.setUint16(this.position, value); + this.position += 2; + }, + pushUint24(value) { + this.assertPosition(this.position + 2); + this.dataView.setUint16(this.position, value >> 8); + this.dataView.setUint8(this.position + 2, value & ~4294967040); + this.position += 3; + }, + pushUint32(value) { + this.assertPosition(this.position + 3); + this.dataView.setUint32(this.position, value); + this.position += 4; + }, + readByte() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectByte(); + this.position++; + return value; + }, + readBytes(length, size5) { + this.assertReadLimit(); + this._touch(); + const value = this.inspectBytes(length); + this.position += size5 ?? length; + return value; + }, + readUint8() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint8(); + this.position += 1; + return value; + }, + readUint16() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint16(); + this.position += 2; + return value; + }, + readUint24() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint24(); + this.position += 3; + return value; + }, + readUint32() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint32(); + this.position += 4; + return value; + }, + get remaining() { + return this.bytes.length - this.position; + }, + setPosition(position) { + const oldPosition = this.position; + this.assertPosition(position); + this.position = position; + return () => this.position = oldPosition; + }, + _touch() { + if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) + return; + const count = this.getReadCount(); + this.positionReadCount.set(this.position, count + 1); + if (count > 0) + this.recursiveReadCount++; } }; } }); -// node_modules/viem/_esm/utils/errors/getNodeError.js -function getNodeError(err, args) { - const message = (err.details || "").toLowerCase(); - const executionRevertedError = err instanceof BaseError2 ? err.walk((e) => e?.code === ExecutionRevertedError.code) : err; - if (executionRevertedError instanceof BaseError2) - return new ExecutionRevertedError({ - cause: err, - message: executionRevertedError.details - }); - if (ExecutionRevertedError.nodeMessage.test(message)) - return new ExecutionRevertedError({ - cause: err, - message: err.details - }); - if (FeeCapTooHighError.nodeMessage.test(message)) - return new FeeCapTooHighError({ - cause: err, - maxFeePerGas: args?.maxFeePerGas - }); - if (FeeCapTooLowError.nodeMessage.test(message)) - return new FeeCapTooLowError({ - cause: err, - maxFeePerGas: args?.maxFeePerGas +// node_modules/viem/_esm/utils/encoding/fromBytes.js +function bytesToBigInt(bytes, opts = {}) { + if (typeof opts.size !== "undefined") + assertSize(bytes, { size: opts.size }); + const hex = bytesToHex(bytes, opts); + return hexToBigInt(hex, opts); +} +function bytesToBool(bytes_, opts = {}) { + let bytes = bytes_; + if (typeof opts.size !== "undefined") { + assertSize(bytes, { size: opts.size }); + bytes = trim(bytes); + } + if (bytes.length > 1 || bytes[0] > 1) + throw new InvalidBytesBooleanError(bytes); + return Boolean(bytes[0]); +} +function bytesToNumber(bytes, opts = {}) { + if (typeof opts.size !== "undefined") + assertSize(bytes, { size: opts.size }); + const hex = bytesToHex(bytes, opts); + return hexToNumber(hex, opts); +} +function bytesToString(bytes_, opts = {}) { + let bytes = bytes_; + if (typeof opts.size !== "undefined") { + assertSize(bytes, { size: opts.size }); + bytes = trim(bytes, { dir: "right" }); + } + return new TextDecoder().decode(bytes); +} +var init_fromBytes = __esm({ + "node_modules/viem/_esm/utils/encoding/fromBytes.js"() { + init_encoding(); + init_trim(); + init_fromHex(); + init_toHex(); + } +}); + +// node_modules/viem/_esm/utils/abi/decodeAbiParameters.js +function decodeAbiParameters(params, data) { + const bytes = typeof data === "string" ? hexToBytes(data) : data; + const cursor = createCursor(bytes); + if (size(bytes) === 0 && params.length > 0) + throw new AbiDecodingZeroDataError(); + if (size(data) && size(data) < 32) + throw new AbiDecodingDataSizeTooSmallError({ + data: typeof data === "string" ? data : bytesToHex(data), + params, + size: size(data) }); - if (NonceTooHighError.nodeMessage.test(message)) - return new NonceTooHighError({ cause: err, nonce: args?.nonce }); - if (NonceTooLowError.nodeMessage.test(message)) - return new NonceTooLowError({ cause: err, nonce: args?.nonce }); - if (NonceMaxValueError.nodeMessage.test(message)) - return new NonceMaxValueError({ cause: err, nonce: args?.nonce }); - if (InsufficientFundsError.nodeMessage.test(message)) - return new InsufficientFundsError({ cause: err }); - if (IntrinsicGasTooHighError.nodeMessage.test(message)) - return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas }); - if (IntrinsicGasTooLowError.nodeMessage.test(message)) - return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas }); - if (TransactionTypeNotSupportedError.nodeMessage.test(message)) - return new TransactionTypeNotSupportedError({ cause: err }); - if (TipAboveFeeCapError.nodeMessage.test(message)) - return new TipAboveFeeCapError({ - cause: err, - maxFeePerGas: args?.maxFeePerGas, - maxPriorityFeePerGas: args?.maxPriorityFeePerGas + let consumed = 0; + const values = []; + for (let i = 0; i < params.length; ++i) { + const param = params[i]; + cursor.setPosition(consumed); + const [data2, consumed_] = decodeParameter(cursor, param, { + staticPosition: 0 }); - return new UnknownNodeError({ - cause: err + consumed += consumed_; + values.push(data2); + } + return values; +} +function decodeParameter(cursor, param, { staticPosition }) { + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return decodeArray(cursor, { ...param, type }, { length, staticPosition }); + } + if (param.type === "tuple") + return decodeTuple(cursor, param, { staticPosition }); + if (param.type === "address") + return decodeAddress(cursor); + if (param.type === "bool") + return decodeBool(cursor); + if (param.type.startsWith("bytes")) + return decodeBytes(cursor, param, { staticPosition }); + if (param.type.startsWith("uint") || param.type.startsWith("int")) + return decodeNumber(cursor, param); + if (param.type === "string") + return decodeString(cursor, { staticPosition }); + throw new InvalidAbiDecodingTypeError(param.type, { + docsPath: "/docs/contract/decodeAbiParameters" }); } -var init_getNodeError = __esm({ - "node_modules/viem/_esm/utils/errors/getNodeError.js"() { - init_base(); - init_node(); +function decodeAddress(cursor) { + const value = cursor.readBytes(32); + return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]; +} +function decodeArray(cursor, param, { length, staticPosition }) { + if (!length) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + const startOfData = start + sizeOfLength; + cursor.setPosition(start); + const length2 = bytesToNumber(cursor.readBytes(sizeOfLength)); + const dynamicChild = hasDynamicChild(param); + let consumed2 = 0; + const value2 = []; + for (let i = 0; i < length2; ++i) { + cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); + const [data, consumed_] = decodeParameter(cursor, param, { + staticPosition: startOfData + }); + consumed2 += consumed_; + value2.push(data); + } + cursor.setPosition(staticPosition + 32); + return [value2, 32]; } -}); - -// node_modules/viem/_esm/utils/formatters/extract.js -function extract(value_, { format }) { - if (!format) - return {}; - const value = {}; - function extract_(formatted2) { - const keys = Object.keys(formatted2); - for (const key of keys) { - if (key in value_) - value[key] = value_[key]; - if (formatted2[key] && typeof formatted2[key] === "object" && !Array.isArray(formatted2[key])) - extract_(formatted2[key]); + if (hasDynamicChild(param)) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + const value2 = []; + for (let i = 0; i < length; ++i) { + cursor.setPosition(start + i * 32); + const [data] = decodeParameter(cursor, param, { + staticPosition: start + }); + value2.push(data); } + cursor.setPosition(staticPosition + 32); + return [value2, 32]; } - const formatted = format(value_ || {}); - extract_(formatted); - return value; + let consumed = 0; + const value = []; + for (let i = 0; i < length; ++i) { + const [data, consumed_] = decodeParameter(cursor, param, { + staticPosition: staticPosition + consumed + }); + consumed += consumed_; + value.push(data); + } + return [value, consumed]; } -var init_extract = __esm({ - "node_modules/viem/_esm/utils/formatters/extract.js"() { +function decodeBool(cursor) { + return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]; +} +function decodeBytes(cursor, param, { staticPosition }) { + const [_, size5] = param.type.split("bytes"); + if (!size5) { + const offset = bytesToNumber(cursor.readBytes(32)); + cursor.setPosition(staticPosition + offset); + const length = bytesToNumber(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["0x", 32]; + } + const data = cursor.readBytes(length); + cursor.setPosition(staticPosition + 32); + return [bytesToHex(data), 32]; } -}); - -// node_modules/viem/_esm/utils/formatters/transactionRequest.js -function formatTransactionRequest(request) { - const rpcRequest = {}; - if (typeof request.authorizationList !== "undefined") - rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList); - if (typeof request.accessList !== "undefined") - rpcRequest.accessList = request.accessList; - if (typeof request.blobVersionedHashes !== "undefined") - rpcRequest.blobVersionedHashes = request.blobVersionedHashes; - if (typeof request.blobs !== "undefined") { - if (typeof request.blobs[0] !== "string") - rpcRequest.blobs = request.blobs.map((x2) => bytesToHex(x2)); - else - rpcRequest.blobs = request.blobs; + const value = bytesToHex(cursor.readBytes(Number.parseInt(size5), 32)); + return [value, 32]; +} +function decodeNumber(cursor, param) { + const signed = param.type.startsWith("int"); + const size5 = Number.parseInt(param.type.split("int")[1] || "256"); + const value = cursor.readBytes(32); + return [ + size5 > 48 ? bytesToBigInt(value, { signed }) : bytesToNumber(value, { signed }), + 32 + ]; +} +function decodeTuple(cursor, param, { staticPosition }) { + const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name); + const value = hasUnnamedChild ? [] : {}; + let consumed = 0; + if (hasDynamicChild(param)) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + for (let i = 0; i < param.components.length; ++i) { + const component = param.components[i]; + cursor.setPosition(start + consumed); + const [data, consumed_] = decodeParameter(cursor, component, { + staticPosition: start + }); + consumed += consumed_; + value[hasUnnamedChild ? i : component?.name] = data; + } + cursor.setPosition(staticPosition + 32); + return [value, 32]; } - if (typeof request.data !== "undefined") - rpcRequest.data = request.data; - if (typeof request.from !== "undefined") - rpcRequest.from = request.from; - if (typeof request.gas !== "undefined") - rpcRequest.gas = numberToHex(request.gas); - if (typeof request.gasPrice !== "undefined") - rpcRequest.gasPrice = numberToHex(request.gasPrice); - if (typeof request.maxFeePerBlobGas !== "undefined") - rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas); - if (typeof request.maxFeePerGas !== "undefined") - rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas); - if (typeof request.maxPriorityFeePerGas !== "undefined") - rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas); - if (typeof request.nonce !== "undefined") - rpcRequest.nonce = numberToHex(request.nonce); - if (typeof request.to !== "undefined") - rpcRequest.to = request.to; - if (typeof request.type !== "undefined") - rpcRequest.type = rpcTransactionType[request.type]; - if (typeof request.value !== "undefined") - rpcRequest.value = numberToHex(request.value); - return rpcRequest; + for (let i = 0; i < param.components.length; ++i) { + const component = param.components[i]; + const [data, consumed_] = decodeParameter(cursor, component, { + staticPosition + }); + value[hasUnnamedChild ? i : component?.name] = data; + consumed += consumed_; + } + return [value, consumed]; } -function formatAuthorizationList(authorizationList) { - return authorizationList.map((authorization) => ({ - address: authorization.address, - r: authorization.r ? numberToHex(BigInt(authorization.r)) : authorization.r, - s: authorization.s ? numberToHex(BigInt(authorization.s)) : authorization.s, - chainId: numberToHex(authorization.chainId), - nonce: numberToHex(authorization.nonce), - ...typeof authorization.yParity !== "undefined" ? { yParity: numberToHex(authorization.yParity) } : {}, - ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: numberToHex(authorization.v) } : {} - })); +function decodeString(cursor, { staticPosition }) { + const offset = bytesToNumber(cursor.readBytes(32)); + const start = staticPosition + offset; + cursor.setPosition(start); + const length = bytesToNumber(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["", 32]; + } + const data = cursor.readBytes(length, 32); + const value = bytesToString(trim(data)); + cursor.setPosition(staticPosition + 32); + return [value, 32]; } -var rpcTransactionType; -var init_transactionRequest = __esm({ - "node_modules/viem/_esm/utils/formatters/transactionRequest.js"() { +function hasDynamicChild(param) { + const { type } = param; + if (type === "string") + return true; + if (type === "bytes") + return true; + if (type.endsWith("[]")) + return true; + if (type === "tuple") + return param.components?.some(hasDynamicChild); + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] })) + return true; + return false; +} +var sizeOfLength, sizeOfOffset; +var init_decodeAbiParameters = __esm({ + "node_modules/viem/_esm/utils/abi/decodeAbiParameters.js"() { + init_abi(); + init_getAddress(); + init_cursor2(); + init_size(); + init_slice(); + init_trim(); + init_fromBytes(); + init_toBytes(); init_toHex(); - rpcTransactionType = { - legacy: "0x0", - eip2930: "0x1", - eip1559: "0x2", - eip4844: "0x3", - eip7702: "0x4" - }; + init_encodeAbiParameters(); + sizeOfLength = 32; + sizeOfOffset = 32; } }); -// node_modules/viem/_esm/utils/stateOverride.js -function serializeStateMapping(stateMapping) { - if (!stateMapping || stateMapping.length === 0) - return void 0; - return stateMapping.reduce((acc, { slot, value }) => { - if (slot.length !== 66) - throw new InvalidBytesLengthError({ - size: slot.length, - targetSize: 66, - type: "hex" - }); - if (value.length !== 66) - throw new InvalidBytesLengthError({ - size: value.length, - targetSize: 66, - type: "hex" - }); - acc[slot] = value; - return acc; - }, {}); +// node_modules/viem/_esm/utils/abi/decodeErrorResult.js +function decodeErrorResult(parameters) { + const { abi: abi4, data } = parameters; + const signature = slice(data, 0, 4); + if (signature === "0x") + throw new AbiDecodingZeroDataError(); + const abi_ = [...abi4 || [], solidityError, solidityPanic]; + const abiItem = abi_.find((x2) => x2.type === "error" && signature === toFunctionSelector(formatAbiItem2(x2))); + if (!abiItem) + throw new AbiErrorSignatureNotFoundError(signature, { + docsPath: "/docs/contract/decodeErrorResult" + }); + return { + abiItem, + args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : void 0, + errorName: abiItem.name + }; } -function serializeAccountStateOverride(parameters) { - const { balance, nonce, state, stateDiff, code } = parameters; - const rpcAccountStateOverride = {}; - if (code !== void 0) - rpcAccountStateOverride.code = code; - if (balance !== void 0) - rpcAccountStateOverride.balance = numberToHex(balance); - if (nonce !== void 0) - rpcAccountStateOverride.nonce = numberToHex(nonce); - if (state !== void 0) - rpcAccountStateOverride.state = serializeStateMapping(state); - if (stateDiff !== void 0) { - if (rpcAccountStateOverride.state) - throw new StateAssignmentConflictError(); - rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff); +var init_decodeErrorResult = __esm({ + "node_modules/viem/_esm/utils/abi/decodeErrorResult.js"() { + init_solidity(); + init_abi(); + init_slice(); + init_toFunctionSelector(); + init_decodeAbiParameters(); + init_formatAbiItem2(); } - return rpcAccountStateOverride; -} -function serializeStateOverride(parameters) { - if (!parameters) - return void 0; - const rpcStateOverride = {}; - for (const { address, ...accountState } of parameters) { - if (!isAddress(address, { strict: false })) - throw new InvalidAddressError({ address }); - if (rpcStateOverride[address]) - throw new AccountStateConflictError({ address }); - rpcStateOverride[address] = serializeAccountStateOverride(accountState); +}); + +// node_modules/viem/_esm/utils/stringify.js +var stringify; +var init_stringify = __esm({ + "node_modules/viem/_esm/utils/stringify.js"() { + stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => { + const value2 = typeof value_ === "bigint" ? value_.toString() : value_; + return typeof replacer === "function" ? replacer(key, value2) : value2; + }, space); } - return rpcStateOverride; +}); + +// node_modules/viem/_esm/utils/abi/formatAbiItemWithArgs.js +function formatAbiItemWithArgs({ abiItem, args, includeFunctionName = true, includeName = false }) { + if (!("name" in abiItem)) + return; + if (!("inputs" in abiItem)) + return; + if (!abiItem.inputs) + return; + return `${includeFunctionName ? abiItem.name : ""}(${abiItem.inputs.map((input, i) => `${includeName && input.name ? `${input.name}: ` : ""}${typeof args[i] === "object" ? stringify(args[i]) : args[i]}`).join(", ")})`; } -var init_stateOverride2 = __esm({ - "node_modules/viem/_esm/utils/stateOverride.js"() { - init_address(); - init_data(); - init_stateOverride(); - init_isAddress(); - init_toHex(); +var init_formatAbiItemWithArgs = __esm({ + "node_modules/viem/_esm/utils/abi/formatAbiItemWithArgs.js"() { + init_stringify(); } }); -// node_modules/viem/_esm/constants/number.js -var maxInt8, maxInt16, maxInt24, maxInt32, maxInt40, maxInt48, maxInt56, maxInt64, maxInt72, maxInt80, maxInt88, maxInt96, maxInt104, maxInt112, maxInt120, maxInt128, maxInt136, maxInt144, maxInt152, maxInt160, maxInt168, maxInt176, maxInt184, maxInt192, maxInt200, maxInt208, maxInt216, maxInt224, maxInt232, maxInt240, maxInt248, maxInt256, minInt8, minInt16, minInt24, minInt32, minInt40, minInt48, minInt56, minInt64, minInt72, minInt80, minInt88, minInt96, minInt104, minInt112, minInt120, minInt128, minInt136, minInt144, minInt152, minInt160, minInt168, minInt176, minInt184, minInt192, minInt200, minInt208, minInt216, minInt224, minInt232, minInt240, minInt248, minInt256, maxUint8, maxUint16, maxUint24, maxUint32, maxUint40, maxUint48, maxUint56, maxUint64, maxUint72, maxUint80, maxUint88, maxUint96, maxUint104, maxUint112, maxUint120, maxUint128, maxUint136, maxUint144, maxUint152, maxUint160, maxUint168, maxUint176, maxUint184, maxUint192, maxUint200, maxUint208, maxUint216, maxUint224, maxUint232, maxUint240, maxUint248, maxUint256; -var init_number = __esm({ - "node_modules/viem/_esm/constants/number.js"() { - maxInt8 = 2n ** (8n - 1n) - 1n; - maxInt16 = 2n ** (16n - 1n) - 1n; - maxInt24 = 2n ** (24n - 1n) - 1n; - maxInt32 = 2n ** (32n - 1n) - 1n; - maxInt40 = 2n ** (40n - 1n) - 1n; - maxInt48 = 2n ** (48n - 1n) - 1n; - maxInt56 = 2n ** (56n - 1n) - 1n; - maxInt64 = 2n ** (64n - 1n) - 1n; - maxInt72 = 2n ** (72n - 1n) - 1n; - maxInt80 = 2n ** (80n - 1n) - 1n; - maxInt88 = 2n ** (88n - 1n) - 1n; - maxInt96 = 2n ** (96n - 1n) - 1n; - maxInt104 = 2n ** (104n - 1n) - 1n; - maxInt112 = 2n ** (112n - 1n) - 1n; - maxInt120 = 2n ** (120n - 1n) - 1n; - maxInt128 = 2n ** (128n - 1n) - 1n; - maxInt136 = 2n ** (136n - 1n) - 1n; - maxInt144 = 2n ** (144n - 1n) - 1n; - maxInt152 = 2n ** (152n - 1n) - 1n; - maxInt160 = 2n ** (160n - 1n) - 1n; - maxInt168 = 2n ** (168n - 1n) - 1n; - maxInt176 = 2n ** (176n - 1n) - 1n; - maxInt184 = 2n ** (184n - 1n) - 1n; - maxInt192 = 2n ** (192n - 1n) - 1n; - maxInt200 = 2n ** (200n - 1n) - 1n; - maxInt208 = 2n ** (208n - 1n) - 1n; - maxInt216 = 2n ** (216n - 1n) - 1n; - maxInt224 = 2n ** (224n - 1n) - 1n; - maxInt232 = 2n ** (232n - 1n) - 1n; - maxInt240 = 2n ** (240n - 1n) - 1n; - maxInt248 = 2n ** (248n - 1n) - 1n; - maxInt256 = 2n ** (256n - 1n) - 1n; - minInt8 = -(2n ** (8n - 1n)); - minInt16 = -(2n ** (16n - 1n)); - minInt24 = -(2n ** (24n - 1n)); - minInt32 = -(2n ** (32n - 1n)); - minInt40 = -(2n ** (40n - 1n)); - minInt48 = -(2n ** (48n - 1n)); - minInt56 = -(2n ** (56n - 1n)); - minInt64 = -(2n ** (64n - 1n)); - minInt72 = -(2n ** (72n - 1n)); - minInt80 = -(2n ** (80n - 1n)); - minInt88 = -(2n ** (88n - 1n)); - minInt96 = -(2n ** (96n - 1n)); - minInt104 = -(2n ** (104n - 1n)); - minInt112 = -(2n ** (112n - 1n)); - minInt120 = -(2n ** (120n - 1n)); - minInt128 = -(2n ** (128n - 1n)); - minInt136 = -(2n ** (136n - 1n)); - minInt144 = -(2n ** (144n - 1n)); - minInt152 = -(2n ** (152n - 1n)); - minInt160 = -(2n ** (160n - 1n)); - minInt168 = -(2n ** (168n - 1n)); - minInt176 = -(2n ** (176n - 1n)); - minInt184 = -(2n ** (184n - 1n)); - minInt192 = -(2n ** (192n - 1n)); - minInt200 = -(2n ** (200n - 1n)); - minInt208 = -(2n ** (208n - 1n)); - minInt216 = -(2n ** (216n - 1n)); - minInt224 = -(2n ** (224n - 1n)); - minInt232 = -(2n ** (232n - 1n)); - minInt240 = -(2n ** (240n - 1n)); - minInt248 = -(2n ** (248n - 1n)); - minInt256 = -(2n ** (256n - 1n)); - maxUint8 = 2n ** 8n - 1n; - maxUint16 = 2n ** 16n - 1n; - maxUint24 = 2n ** 24n - 1n; - maxUint32 = 2n ** 32n - 1n; - maxUint40 = 2n ** 40n - 1n; - maxUint48 = 2n ** 48n - 1n; - maxUint56 = 2n ** 56n - 1n; - maxUint64 = 2n ** 64n - 1n; - maxUint72 = 2n ** 72n - 1n; - maxUint80 = 2n ** 80n - 1n; - maxUint88 = 2n ** 88n - 1n; - maxUint96 = 2n ** 96n - 1n; - maxUint104 = 2n ** 104n - 1n; - maxUint112 = 2n ** 112n - 1n; - maxUint120 = 2n ** 120n - 1n; - maxUint128 = 2n ** 128n - 1n; - maxUint136 = 2n ** 136n - 1n; - maxUint144 = 2n ** 144n - 1n; - maxUint152 = 2n ** 152n - 1n; - maxUint160 = 2n ** 160n - 1n; - maxUint168 = 2n ** 168n - 1n; - maxUint176 = 2n ** 176n - 1n; - maxUint184 = 2n ** 184n - 1n; - maxUint192 = 2n ** 192n - 1n; - maxUint200 = 2n ** 200n - 1n; - maxUint208 = 2n ** 208n - 1n; - maxUint216 = 2n ** 216n - 1n; - maxUint224 = 2n ** 224n - 1n; - maxUint232 = 2n ** 232n - 1n; - maxUint240 = 2n ** 240n - 1n; - maxUint248 = 2n ** 248n - 1n; - maxUint256 = 2n ** 256n - 1n; +// node_modules/viem/_esm/constants/unit.js +var etherUnits, gweiUnits; +var init_unit = __esm({ + "node_modules/viem/_esm/constants/unit.js"() { + etherUnits = { + gwei: 9, + wei: 18 + }; + gweiUnits = { + ether: -9, + wei: 9 + }; } }); -// node_modules/viem/_esm/utils/transaction/assertRequest.js -function assertRequest(args) { - const { account: account_, gasPrice, maxFeePerGas, maxPriorityFeePerGas, to: to2 } = args; - const account = account_ ? parseAccount(account_) : void 0; - if (account && !isAddress(account.address)) - throw new InvalidAddressError({ address: account.address }); - if (to2 && !isAddress(to2)) - throw new InvalidAddressError({ address: to2 }); - if (typeof gasPrice !== "undefined" && (typeof maxFeePerGas !== "undefined" || typeof maxPriorityFeePerGas !== "undefined")) - throw new FeeConflictError(); - if (maxFeePerGas && maxFeePerGas > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas }); - if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) - throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); +// node_modules/viem/_esm/utils/unit/formatUnits.js +function formatUnits(value, decimals) { + let display = value.toString(); + const negative = display.startsWith("-"); + if (negative) + display = display.slice(1); + display = display.padStart(decimals, "0"); + let [integer, fraction] = [ + display.slice(0, display.length - decimals), + display.slice(display.length - decimals) + ]; + fraction = fraction.replace(/(0+)$/, ""); + return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`; } -var init_assertRequest = __esm({ - "node_modules/viem/_esm/utils/transaction/assertRequest.js"() { - init_parseAccount(); - init_number(); - init_address(); - init_node(); - init_transaction(); - init_isAddress(); +var init_formatUnits = __esm({ + "node_modules/viem/_esm/utils/unit/formatUnits.js"() { } }); -// node_modules/viem/_esm/utils/address/isAddressEqual.js -function isAddressEqual(a, b2) { - if (!isAddress(a, { strict: false })) - throw new InvalidAddressError({ address: a }); - if (!isAddress(b2, { strict: false })) - throw new InvalidAddressError({ address: b2 }); - return a.toLowerCase() === b2.toLowerCase(); +// node_modules/viem/_esm/utils/unit/formatEther.js +function formatEther(wei, unit = "wei") { + return formatUnits(wei, etherUnits[unit]); } -var init_isAddressEqual = __esm({ - "node_modules/viem/_esm/utils/address/isAddressEqual.js"() { - init_address(); - init_isAddress(); +var init_formatEther = __esm({ + "node_modules/viem/_esm/utils/unit/formatEther.js"() { + init_unit(); + init_formatUnits(); } }); -// node_modules/viem/_esm/utils/abi/decodeFunctionResult.js -function decodeFunctionResult(parameters) { - const { abi: abi4, args, functionName, data } = parameters; - let abiItem = abi4[0]; - if (functionName) { - const item = getAbiItem({ abi: abi4, args, name: functionName }); - if (!item) - throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath4 }); - abiItem = item; +// node_modules/viem/_esm/utils/unit/formatGwei.js +function formatGwei(wei, unit = "wei") { + return formatUnits(wei, gweiUnits[unit]); +} +var init_formatGwei = __esm({ + "node_modules/viem/_esm/utils/unit/formatGwei.js"() { + init_unit(); + init_formatUnits(); } - if (abiItem.type !== "function") - throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath4 }); - if (!abiItem.outputs) - throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath4 }); - const values = decodeAbiParameters(abiItem.outputs, data); - if (values && values.length > 1) - return values; - if (values && values.length === 1) - return values[0]; - return void 0; +}); + +// node_modules/viem/_esm/errors/stateOverride.js +function prettyStateMapping(stateMapping) { + return stateMapping.reduce((pretty, { slot, value }) => { + return `${pretty} ${slot}: ${value} +`; + }, ""); } -var docsPath4; -var init_decodeFunctionResult = __esm({ - "node_modules/viem/_esm/utils/abi/decodeFunctionResult.js"() { - init_abi(); - init_decodeAbiParameters(); - init_getAbiItem(); - docsPath4 = "/docs/contract/decodeFunctionResult"; +function prettyStateOverride(stateOverride) { + return stateOverride.reduce((pretty, { address, ...state }) => { + let val = `${pretty} ${address}: +`; + if (state.nonce) + val += ` nonce: ${state.nonce} +`; + if (state.balance) + val += ` balance: ${state.balance} +`; + if (state.code) + val += ` code: ${state.code} +`; + if (state.state) { + val += " state:\n"; + val += prettyStateMapping(state.state); + } + if (state.stateDiff) { + val += " stateDiff:\n"; + val += prettyStateMapping(state.stateDiff); + } + return val; + }, " State Override:\n").slice(0, -1); +} +var AccountStateConflictError, StateAssignmentConflictError; +var init_stateOverride = __esm({ + "node_modules/viem/_esm/errors/stateOverride.js"() { + init_base(); + AccountStateConflictError = class extends BaseError2 { + constructor({ address }) { + super(`State for account "${address}" is set multiple times.`, { + name: "AccountStateConflictError" + }); + } + }; + StateAssignmentConflictError = class extends BaseError2 { + constructor() { + super("state and stateDiff are set on the same account.", { + name: "StateAssignmentConflictError" + }); + } + }; } }); -// node_modules/viem/_esm/constants/abis.js -var multicall3Abi, universalResolverErrors, universalResolverResolveAbi, universalResolverReverseAbi, textResolverAbi, addressResolverAbi, universalSignatureValidatorAbi; -var init_abis = __esm({ - "node_modules/viem/_esm/constants/abis.js"() { - multicall3Abi = [ - { - inputs: [ - { - components: [ - { - name: "target", - type: "address" - }, - { - name: "allowFailure", - type: "bool" - }, - { - name: "callData", - type: "bytes" - } - ], - name: "calls", - type: "tuple[]" - } - ], - name: "aggregate3", - outputs: [ - { - components: [ - { - name: "success", - type: "bool" - }, - { - name: "returnData", - type: "bytes" - } - ], - name: "returnData", - type: "tuple[]" - } - ], - stateMutability: "view", - type: "function" +// node_modules/viem/_esm/errors/transaction.js +function prettyPrint(args) { + const entries = Object.entries(args).map(([key, value]) => { + if (value === void 0 || value === false) + return null; + return [key, value]; + }).filter(Boolean); + const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0); + return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n"); +} +var FeeConflictError, InvalidLegacyVError, InvalidSerializableTransactionError, InvalidStorageKeySizeError, TransactionExecutionError, TransactionNotFoundError, TransactionReceiptNotFoundError, WaitForTransactionReceiptTimeoutError; +var init_transaction = __esm({ + "node_modules/viem/_esm/errors/transaction.js"() { + init_formatEther(); + init_formatGwei(); + init_base(); + FeeConflictError = class extends BaseError2 { + constructor() { + super([ + "Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.", + "Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others." + ].join("\n"), { name: "FeeConflictError" }); } - ]; - universalResolverErrors = [ - { - inputs: [], - name: "ResolverNotFound", - type: "error" - }, - { - inputs: [], - name: "ResolverWildcardNotSupported", - type: "error" - }, - { - inputs: [], - name: "ResolverNotContract", - type: "error" - }, - { - inputs: [ - { - name: "returnData", - type: "bytes" - } - ], - name: "ResolverError", - type: "error" - }, - { - inputs: [ - { - components: [ - { - name: "status", - type: "uint16" - }, - { - name: "message", - type: "string" - } - ], - name: "errors", - type: "tuple[]" - } - ], - name: "HttpError", - type: "error" + }; + InvalidLegacyVError = class extends BaseError2 { + constructor({ v }) { + super(`Invalid \`v\` value "${v}". Expected 27 or 28.`, { + name: "InvalidLegacyVError" + }); } - ]; - universalResolverResolveAbi = [ - ...universalResolverErrors, - { - name: "resolve", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes" }, - { name: "data", type: "bytes" } - ], - outputs: [ - { name: "", type: "bytes" }, - { name: "address", type: "address" } - ] - }, - { - name: "resolve", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes" }, - { name: "data", type: "bytes" }, - { name: "gateways", type: "string[]" } - ], - outputs: [ - { name: "", type: "bytes" }, - { name: "address", type: "address" } - ] + }; + InvalidSerializableTransactionError = class extends BaseError2 { + constructor({ transaction }) { + super("Cannot infer a transaction type from provided transaction.", { + metaMessages: [ + "Provided Transaction:", + "{", + prettyPrint(transaction), + "}", + "", + "To infer the type, either provide:", + "- a `type` to the Transaction, or", + "- an EIP-1559 Transaction with `maxFeePerGas`, or", + "- an EIP-2930 Transaction with `gasPrice` & `accessList`, or", + "- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or", + "- an EIP-7702 Transaction with `authorizationList`, or", + "- a Legacy Transaction with `gasPrice`" + ], + name: "InvalidSerializableTransactionError" + }); } - ]; - universalResolverReverseAbi = [ - ...universalResolverErrors, - { - name: "reverse", - type: "function", - stateMutability: "view", - inputs: [{ type: "bytes", name: "reverseName" }], - outputs: [ - { type: "string", name: "resolvedName" }, - { type: "address", name: "resolvedAddress" }, - { type: "address", name: "reverseResolver" }, - { type: "address", name: "resolver" } - ] - }, - { - name: "reverse", - type: "function", - stateMutability: "view", - inputs: [ - { type: "bytes", name: "reverseName" }, - { type: "string[]", name: "gateways" } - ], - outputs: [ - { type: "string", name: "resolvedName" }, - { type: "address", name: "resolvedAddress" }, - { type: "address", name: "reverseResolver" }, - { type: "address", name: "resolver" } - ] + }; + InvalidStorageKeySizeError = class extends BaseError2 { + constructor({ storageKey }) { + super(`Size for storage key "${storageKey}" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: "InvalidStorageKeySizeError" }); + } + }; + TransactionExecutionError = class extends BaseError2 { + constructor(cause, { account, docsPath: docsPath6, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value }) { + const prettyArgs = prettyPrint({ + chain: chain && `${chain?.name} (id: ${chain?.id})`, + from: account?.address, + to: to2, + value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, + data, + gas, + gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, + maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, + maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, + nonce + }); + super(cause.shortMessage, { + cause, + docsPath: docsPath6, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Request Arguments:", + prettyArgs + ].filter(Boolean), + name: "TransactionExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cause = cause; } - ]; - textResolverAbi = [ - { - name: "text", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes32" }, - { name: "key", type: "string" } - ], - outputs: [{ name: "", type: "string" }] + }; + TransactionNotFoundError = class extends BaseError2 { + constructor({ blockHash, blockNumber, blockTag, hash: hash2, index: index2 }) { + let identifier = "Transaction"; + if (blockTag && index2 !== void 0) + identifier = `Transaction at block time "${blockTag}" at index "${index2}"`; + if (blockHash && index2 !== void 0) + identifier = `Transaction at block hash "${blockHash}" at index "${index2}"`; + if (blockNumber && index2 !== void 0) + identifier = `Transaction at block number "${blockNumber}" at index "${index2}"`; + if (hash2) + identifier = `Transaction with hash "${hash2}"`; + super(`${identifier} could not be found.`, { + name: "TransactionNotFoundError" + }); } - ]; - addressResolverAbi = [ - { - name: "addr", - type: "function", - stateMutability: "view", - inputs: [{ name: "name", type: "bytes32" }], - outputs: [{ name: "", type: "address" }] - }, - { - name: "addr", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes32" }, - { name: "coinType", type: "uint256" } - ], - outputs: [{ name: "", type: "bytes" }] + }; + TransactionReceiptNotFoundError = class extends BaseError2 { + constructor({ hash: hash2 }) { + super(`Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`, { + name: "TransactionReceiptNotFoundError" + }); } - ]; - universalSignatureValidatorAbi = [ - { - inputs: [ - { - name: "_signer", - type: "address" - }, - { - name: "_hash", - type: "bytes32" - }, - { - name: "_signature", - type: "bytes" - } - ], - stateMutability: "nonpayable", - type: "constructor" - }, - { - inputs: [ - { - name: "_signer", - type: "address" - }, - { - name: "_hash", - type: "bytes32" - }, - { - name: "_signature", - type: "bytes" - } - ], - outputs: [ - { - type: "bool" - } - ], - stateMutability: "nonpayable", - type: "function", - name: "isValidSig" + }; + WaitForTransactionReceiptTimeoutError = class extends BaseError2 { + constructor({ hash: hash2 }) { + super(`Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`, { name: "WaitForTransactionReceiptTimeoutError" }); } - ]; + }; } }); -// node_modules/viem/_esm/constants/contract.js -var aggregate3Signature; -var init_contract2 = __esm({ - "node_modules/viem/_esm/constants/contract.js"() { - aggregate3Signature = "0x82ad56cb"; +// node_modules/viem/_esm/errors/utils.js +var getContractAddress, getUrl; +var init_utils3 = __esm({ + "node_modules/viem/_esm/errors/utils.js"() { + getContractAddress = (address) => address; + getUrl = (url2) => url2; } }); -// node_modules/viem/_esm/constants/contracts.js -var deploylessCallViaBytecodeBytecode, deploylessCallViaFactoryBytecode, universalSignatureValidatorByteCode; -var init_contracts = __esm({ - "node_modules/viem/_esm/constants/contracts.js"() { - deploylessCallViaBytecodeBytecode = "0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe"; - deploylessCallViaFactoryBytecode = "0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe"; - universalSignatureValidatorByteCode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572"; +// node_modules/viem/_esm/errors/contract.js +var CallExecutionError, ContractFunctionExecutionError, ContractFunctionRevertedError, ContractFunctionZeroDataError, CounterfactualDeploymentFailedError, RawContractError; +var init_contract = __esm({ + "node_modules/viem/_esm/errors/contract.js"() { + init_parseAccount(); + init_solidity(); + init_decodeErrorResult(); + init_formatAbiItem2(); + init_formatAbiItemWithArgs(); + init_getAbiItem(); + init_formatEther(); + init_formatGwei(); + init_abi(); + init_base(); + init_stateOverride(); + init_transaction(); + init_utils3(); + CallExecutionError = class extends BaseError2 { + constructor(cause, { account: account_, docsPath: docsPath6, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value, stateOverride }) { + const account = account_ ? parseAccount(account_) : void 0; + let prettyArgs = prettyPrint({ + from: account?.address, + to: to2, + value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, + data, + gas, + gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, + maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, + maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, + nonce + }); + if (stateOverride) { + prettyArgs += ` +${prettyStateOverride(stateOverride)}`; + } + super(cause.shortMessage, { + cause, + docsPath: docsPath6, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Raw Call Arguments:", + prettyArgs + ].filter(Boolean), + name: "CallExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cause = cause; + } + }; + ContractFunctionExecutionError = class extends BaseError2 { + constructor(cause, { abi: abi4, args, contractAddress, docsPath: docsPath6, functionName, sender }) { + const abiItem = getAbiItem({ abi: abi4, args, name: functionName }); + const formattedArgs = abiItem ? formatAbiItemWithArgs({ + abiItem, + args, + includeFunctionName: false, + includeName: false + }) : void 0; + const functionWithParams = abiItem ? formatAbiItem2(abiItem, { includeName: true }) : void 0; + const prettyArgs = prettyPrint({ + address: contractAddress && getContractAddress(contractAddress), + function: functionWithParams, + args: formattedArgs && formattedArgs !== "()" && `${[...Array(functionName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`, + sender + }); + super(cause.shortMessage || `An unknown error occurred while executing the contract function "${functionName}".`, { + cause, + docsPath: docsPath6, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + prettyArgs && "Contract Call:", + prettyArgs + ].filter(Boolean), + name: "ContractFunctionExecutionError" + }); + Object.defineProperty(this, "abi", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "args", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "contractAddress", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "formattedArgs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "functionName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sender", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.abi = abi4; + this.args = args; + this.cause = cause; + this.contractAddress = contractAddress; + this.functionName = functionName; + this.sender = sender; + } + }; + ContractFunctionRevertedError = class extends BaseError2 { + constructor({ abi: abi4, data, functionName, message }) { + let cause; + let decodedData = void 0; + let metaMessages; + let reason; + if (data && data !== "0x") { + try { + decodedData = decodeErrorResult({ abi: abi4, data }); + const { abiItem, errorName, args: errorArgs } = decodedData; + if (errorName === "Error") { + reason = errorArgs[0]; + } else if (errorName === "Panic") { + const [firstArg] = errorArgs; + reason = panicReasons[firstArg]; + } else { + const errorWithParams = abiItem ? formatAbiItem2(abiItem, { includeName: true }) : void 0; + const formattedArgs = abiItem && errorArgs ? formatAbiItemWithArgs({ + abiItem, + args: errorArgs, + includeFunctionName: false, + includeName: false + }) : void 0; + metaMessages = [ + errorWithParams ? `Error: ${errorWithParams}` : "", + formattedArgs && formattedArgs !== "()" ? ` ${[...Array(errorName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : "" + ]; + } + } catch (err) { + cause = err; + } + } else if (message) + reason = message; + let signature; + if (cause instanceof AbiErrorSignatureNotFoundError) { + signature = cause.signature; + metaMessages = [ + `Unable to decode signature "${signature}" as it was not found on the provided ABI.`, + "Make sure you are using the correct ABI and that the error exists on it.", + `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.` + ]; + } + super(reason && reason !== "execution reverted" || signature ? [ + `The contract function "${functionName}" reverted with the following ${signature ? "signature" : "reason"}:`, + reason || signature + ].join("\n") : `The contract function "${functionName}" reverted.`, { + cause, + metaMessages, + name: "ContractFunctionRevertedError" + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "raw", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "reason", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "signature", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = decodedData; + this.raw = data; + this.reason = reason; + this.signature = signature; + } + }; + ContractFunctionZeroDataError = class extends BaseError2 { + constructor({ functionName }) { + super(`The contract function "${functionName}" returned no data ("0x").`, { + metaMessages: [ + "This could be due to any of the following:", + ` - The contract does not have the function "${functionName}",`, + " - The parameters passed to the contract function may be invalid, or", + " - The address is not a contract." + ], + name: "ContractFunctionZeroDataError" + }); + } + }; + CounterfactualDeploymentFailedError = class extends BaseError2 { + constructor({ factory }) { + super(`Deployment for counterfactual contract call failed${factory ? ` for factory "${factory}".` : ""}`, { + metaMessages: [ + "Please ensure:", + "- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).", + "- The `factoryData` is a valid encoded function call for contract deployment function on the factory." + ], + name: "CounterfactualDeploymentFailedError" + }); + } + }; + RawContractError = class extends BaseError2 { + constructor({ data, message }) { + super(message || "", { name: "RawContractError" }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 3 + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.data = data; + } + }; } }); -// node_modules/viem/_esm/errors/chain.js -var ChainDoesNotSupportContract, ChainMismatchError, ChainNotFoundError, ClientChainNotConfiguredError, InvalidChainIdError; -var init_chain = __esm({ - "node_modules/viem/_esm/errors/chain.js"() { +// node_modules/viem/_esm/errors/request.js +var HttpRequestError, RpcRequestError, TimeoutError; +var init_request = __esm({ + "node_modules/viem/_esm/errors/request.js"() { + init_stringify(); init_base(); - ChainDoesNotSupportContract = class extends BaseError2 { - constructor({ blockNumber, chain, contract }) { - super(`Chain "${chain.name}" does not support contract "${contract.name}".`, { + init_utils3(); + HttpRequestError = class extends BaseError2 { + constructor({ body, cause, details, headers, status, url: url2 }) { + super("HTTP request failed.", { + cause, + details, metaMessages: [ - "This could be due to any of the following:", - ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [ - `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).` - ] : [ - `- The chain does not have the contract "${contract.name}" configured.` - ] - ], - name: "ChainDoesNotSupportContract" + status && `Status: ${status}`, + `URL: ${getUrl(url2)}`, + body && `Request body: ${stringify(body)}` + ].filter(Boolean), + name: "HttpRequestError" + }); + Object.defineProperty(this, "body", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "url", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.body = body; + this.headers = headers; + this.status = status; + this.url = url2; + } + }; + RpcRequestError = class extends BaseError2 { + constructor({ body, error, url: url2 }) { + super("RPC Request failed.", { + cause: error, + details: error.message, + metaMessages: [`URL: ${getUrl(url2)}`, `Request body: ${stringify(body)}`], + name: "RpcRequestError" + }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.code = error.code; + this.data = error.data; + } + }; + TimeoutError = class extends BaseError2 { + constructor({ body, url: url2 }) { + super("The request took too long to respond.", { + details: "The request timed out.", + metaMessages: [`URL: ${getUrl(url2)}`, `Request body: ${stringify(body)}`], + name: "TimeoutError" + }); + } + }; + } +}); + +// node_modules/viem/_esm/errors/rpc.js +var unknownErrorCode, RpcError, ProviderRpcError, ParseRpcError, InvalidRequestRpcError, MethodNotFoundRpcError, InvalidParamsRpcError, InternalRpcError, InvalidInputRpcError, ResourceNotFoundRpcError, ResourceUnavailableRpcError, TransactionRejectedRpcError, MethodNotSupportedRpcError, LimitExceededRpcError, JsonRpcVersionUnsupportedError, UserRejectedRequestError, UnauthorizedProviderError, UnsupportedProviderMethodError, ProviderDisconnectedError, ChainDisconnectedError, SwitchChainError, UnknownRpcError; +var init_rpc = __esm({ + "node_modules/viem/_esm/errors/rpc.js"() { + init_base(); + init_request(); + unknownErrorCode = -1; + RpcError = class extends BaseError2 { + constructor(cause, { code, docsPath: docsPath6, metaMessages, name, shortMessage }) { + super(shortMessage, { + cause, + docsPath: docsPath6, + metaMessages: metaMessages || cause?.metaMessages, + name: name || "RpcError" }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = name || cause.name; + this.code = cause instanceof RpcRequestError ? cause.code : code ?? unknownErrorCode; } }; - ChainMismatchError = class extends BaseError2 { - constructor({ chain, currentChainId }) { - super(`The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} \u2013 ${chain.name}).`, { - metaMessages: [ - `Current Chain ID: ${currentChainId}`, - `Expected Chain ID: ${chain.id} \u2013 ${chain.name}` - ], - name: "ChainMismatchError" + ProviderRpcError = class extends RpcError { + constructor(cause, options) { + super(cause, options); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); + this.data = options.data; } }; - ChainNotFoundError = class extends BaseError2 { - constructor() { - super([ - "No chain was provided to the request.", - "Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient." - ].join("\n"), { - name: "ChainNotFoundError" + ParseRpcError = class _ParseRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _ParseRpcError.code, + name: "ParseRpcError", + shortMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text." }); } }; - ClientChainNotConfiguredError = class extends BaseError2 { - constructor() { - super("No chain was provided to the Client.", { - name: "ClientChainNotConfiguredError" + Object.defineProperty(ParseRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32700 + }); + InvalidRequestRpcError = class _InvalidRequestRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _InvalidRequestRpcError.code, + name: "InvalidRequestRpcError", + shortMessage: "JSON is not a valid request object." }); } }; - InvalidChainIdError = class extends BaseError2 { - constructor({ chainId }) { - super(typeof chainId === "number" ? `Chain ID "${chainId}" is invalid.` : "Chain ID is invalid.", { name: "InvalidChainIdError" }); + Object.defineProperty(InvalidRequestRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32600 + }); + MethodNotFoundRpcError = class _MethodNotFoundRpcError extends RpcError { + constructor(cause, { method } = {}) { + super(cause, { + code: _MethodNotFoundRpcError.code, + name: "MethodNotFoundRpcError", + shortMessage: `The method${method ? ` "${method}"` : ""} does not exist / is not available.` + }); } }; - } -}); - -// node_modules/viem/_esm/utils/abi/encodeDeployData.js -function encodeDeployData(parameters) { - const { abi: abi4, args, bytecode } = parameters; - if (!args || args.length === 0) - return bytecode; - const description = abi4.find((x2) => "type" in x2 && x2.type === "constructor"); - if (!description) - throw new AbiConstructorNotFoundError({ docsPath: docsPath5 }); - if (!("inputs" in description)) - throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 }); - if (!description.inputs || description.inputs.length === 0) - throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 }); - const data = encodeAbiParameters(description.inputs, args); - return concatHex([bytecode, data]); -} -var docsPath5; -var init_encodeDeployData = __esm({ - "node_modules/viem/_esm/utils/abi/encodeDeployData.js"() { - init_abi(); - init_concat(); - init_encodeAbiParameters(); - docsPath5 = "/docs/contract/encodeDeployData"; - } -}); - -// node_modules/viem/_esm/utils/chain/getChainContractAddress.js -function getChainContractAddress({ blockNumber, chain, contract: name }) { - const contract = chain?.contracts?.[name]; - if (!contract) - throw new ChainDoesNotSupportContract({ - chain, - contract: { name } + Object.defineProperty(MethodNotFoundRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32601 }); - if (blockNumber && contract.blockCreated && contract.blockCreated > blockNumber) - throw new ChainDoesNotSupportContract({ - blockNumber, - chain, - contract: { - name, - blockCreated: contract.blockCreated + InvalidParamsRpcError = class _InvalidParamsRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _InvalidParamsRpcError.code, + name: "InvalidParamsRpcError", + shortMessage: [ + "Invalid parameters were provided to the RPC method.", + "Double check you have provided the correct parameters." + ].join("\n") + }); } + }; + Object.defineProperty(InvalidParamsRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32602 }); - return contract.address; -} -var init_getChainContractAddress = __esm({ - "node_modules/viem/_esm/utils/chain/getChainContractAddress.js"() { - init_chain(); - } -}); - -// node_modules/viem/_esm/utils/errors/getCallError.js -function getCallError(err, { docsPath: docsPath6, ...args }) { - const cause = (() => { - const cause2 = getNodeError(err, args); - if (cause2 instanceof UnknownNodeError) - return err; - return cause2; - })(); - return new CallExecutionError(cause, { - docsPath: docsPath6, - ...args - }); -} -var init_getCallError = __esm({ - "node_modules/viem/_esm/utils/errors/getCallError.js"() { - init_contract(); - init_node(); - init_getNodeError(); - } -}); - -// node_modules/viem/_esm/utils/promise/withResolvers.js -function withResolvers() { - let resolve = () => void 0; - let reject = () => void 0; - const promise = new Promise((resolve_, reject_) => { - resolve = resolve_; - reject = reject_; - }); - return { promise, resolve, reject }; -} -var init_withResolvers = __esm({ - "node_modules/viem/_esm/utils/promise/withResolvers.js"() { - } -}); - -// node_modules/viem/_esm/utils/promise/createBatchScheduler.js -function createBatchScheduler({ fn: fn2, id: id2, shouldSplitBatch, wait: wait2 = 0, sort }) { - const exec = async () => { - const scheduler = getScheduler(); - flush(); - const args = scheduler.map(({ args: args2 }) => args2); - if (args.length === 0) - return; - fn2(args).then((data) => { - if (sort && Array.isArray(data)) - data.sort(sort); - for (let i = 0; i < scheduler.length; i++) { - const { resolve } = scheduler[i]; - resolve?.([data[i], data]); + InternalRpcError = class _InternalRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _InternalRpcError.code, + name: "InternalRpcError", + shortMessage: "An internal error was received." + }); } - }).catch((err) => { - for (let i = 0; i < scheduler.length; i++) { - const { reject } = scheduler[i]; - reject?.(err); + }; + Object.defineProperty(InternalRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32603 + }); + InvalidInputRpcError = class _InvalidInputRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _InvalidInputRpcError.code, + name: "InvalidInputRpcError", + shortMessage: [ + "Missing or invalid parameters.", + "Double check you have provided the correct parameters." + ].join("\n") + }); } + }; + Object.defineProperty(InvalidInputRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32e3 }); - }; - const flush = () => schedulerCache.delete(id2); - const getBatchedArgs = () => getScheduler().map(({ args }) => args); - const getScheduler = () => schedulerCache.get(id2) || []; - const setScheduler = (item) => schedulerCache.set(id2, [...getScheduler(), item]); - return { - flush, - async schedule(args) { - const { promise, resolve, reject } = withResolvers(); - const split3 = shouldSplitBatch?.([...getBatchedArgs(), args]); - if (split3) - exec(); - const hasActiveScheduler = getScheduler().length > 0; - if (hasActiveScheduler) { - setScheduler({ args, resolve, reject }); - return promise; + ResourceNotFoundRpcError = class _ResourceNotFoundRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _ResourceNotFoundRpcError.code, + name: "ResourceNotFoundRpcError", + shortMessage: "Requested resource not found." + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "ResourceNotFoundRpcError" + }); } - setScheduler({ args, resolve, reject }); - setTimeout(exec, wait2); - return promise; - } - }; -} -var schedulerCache; -var init_createBatchScheduler = __esm({ - "node_modules/viem/_esm/utils/promise/createBatchScheduler.js"() { - init_withResolvers(); - schedulerCache = /* @__PURE__ */ new Map(); - } -}); - -// node_modules/viem/_esm/errors/ccip.js -var OffchainLookupError, OffchainLookupResponseMalformedError, OffchainLookupSenderMismatchError; -var init_ccip = __esm({ - "node_modules/viem/_esm/errors/ccip.js"() { - init_stringify(); - init_base(); - init_utils3(); - OffchainLookupError = class extends BaseError2 { - constructor({ callbackSelector, cause, data, extraData, sender, urls }) { - super(cause.shortMessage || "An error occurred while fetching for an offchain result.", { - cause, - metaMessages: [ - ...cause.metaMessages || [], - cause.metaMessages?.length ? "" : [], - "Offchain Gateway Call:", - urls && [ - " Gateway URL(s):", - ...urls.map((url2) => ` ${getUrl(url2)}`) - ], - ` Sender: ${sender}`, - ` Data: ${data}`, - ` Callback selector: ${callbackSelector}`, - ` Extra data: ${extraData}` - ].flat(), - name: "OffchainLookupError" + }; + Object.defineProperty(ResourceNotFoundRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32001 + }); + ResourceUnavailableRpcError = class _ResourceUnavailableRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _ResourceUnavailableRpcError.code, + name: "ResourceUnavailableRpcError", + shortMessage: "Requested resource not available." }); } }; - OffchainLookupResponseMalformedError = class extends BaseError2 { - constructor({ result, url: url2 }) { - super("Offchain gateway response is malformed. Response data must be a hex value.", { - metaMessages: [ - `Gateway URL: ${getUrl(url2)}`, - `Response: ${stringify(result)}` - ], - name: "OffchainLookupResponseMalformedError" + Object.defineProperty(ResourceUnavailableRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32002 + }); + TransactionRejectedRpcError = class _TransactionRejectedRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _TransactionRejectedRpcError.code, + name: "TransactionRejectedRpcError", + shortMessage: "Transaction creation failed." }); } }; - OffchainLookupSenderMismatchError = class extends BaseError2 { - constructor({ sender, to: to2 }) { - super("Reverted sender address does not match target contract address (`to`).", { - metaMessages: [ - `Contract address: ${to2}`, - `OffchainLookup sender address: ${sender}` - ], - name: "OffchainLookupSenderMismatchError" + Object.defineProperty(TransactionRejectedRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32003 + }); + MethodNotSupportedRpcError = class _MethodNotSupportedRpcError extends RpcError { + constructor(cause, { method } = {}) { + super(cause, { + code: _MethodNotSupportedRpcError.code, + name: "MethodNotSupportedRpcError", + shortMessage: `Method${method ? ` "${method}"` : ""} is not supported.` }); } }; - } -}); - -// node_modules/viem/_esm/utils/ccip.js -var ccip_exports = {}; -__export(ccip_exports, { - ccipRequest: () => ccipRequest, - offchainLookup: () => offchainLookup, - offchainLookupAbiItem: () => offchainLookupAbiItem, - offchainLookupSignature: () => offchainLookupSignature -}); -async function offchainLookup(client, { blockNumber, blockTag, data, to: to2 }) { - const { args } = decodeErrorResult({ - data, - abi: [offchainLookupAbiItem] - }); - const [sender, urls, callData, callbackSelector, extraData] = args; - const { ccipRead } = client; - const ccipRequest_ = ccipRead && typeof ccipRead?.request === "function" ? ccipRead.request : ccipRequest; - try { - if (!isAddressEqual(to2, sender)) - throw new OffchainLookupSenderMismatchError({ sender, to: to2 }); - const result = await ccipRequest_({ data: callData, sender, urls }); - const { data: data_ } = await call(client, { - blockNumber, - blockTag, - data: concat([ - callbackSelector, - encodeAbiParameters([{ type: "bytes" }, { type: "bytes" }], [result, extraData]) - ]), - to: to2 + Object.defineProperty(MethodNotSupportedRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32004 }); - return data_; - } catch (err) { - throw new OffchainLookupError({ - callbackSelector, - cause: err, - data, - extraData, - sender, - urls + LimitExceededRpcError = class _LimitExceededRpcError extends RpcError { + constructor(cause) { + super(cause, { + code: _LimitExceededRpcError.code, + name: "LimitExceededRpcError", + shortMessage: "Request exceeds defined limit." + }); + } + }; + Object.defineProperty(LimitExceededRpcError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32005 }); - } -} -async function ccipRequest({ data, sender, urls }) { - let error = new Error("An unknown error occurred."); - for (let i = 0; i < urls.length; i++) { - const url2 = urls[i]; - const method = url2.includes("{data}") ? "GET" : "POST"; - const body = method === "POST" ? { data, sender } : void 0; - const headers = method === "POST" ? { "Content-Type": "application/json" } : {}; - try { - const response = await fetch(url2.replace("{sender}", sender.toLowerCase()).replace("{data}", data), { - body: JSON.stringify(body), - headers, - method - }); - let result; - if (response.headers.get("Content-Type")?.startsWith("application/json")) { - result = (await response.json()).data; - } else { - result = await response.text(); + JsonRpcVersionUnsupportedError = class _JsonRpcVersionUnsupportedError extends RpcError { + constructor(cause) { + super(cause, { + code: _JsonRpcVersionUnsupportedError.code, + name: "JsonRpcVersionUnsupportedError", + shortMessage: "Version of JSON-RPC protocol is not supported." + }); } - if (!response.ok) { - error = new HttpRequestError({ - body, - details: result?.error ? stringify(result.error) : response.statusText, - headers: response.headers, - status: response.status, - url: url2 + }; + Object.defineProperty(JsonRpcVersionUnsupportedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: -32006 + }); + UserRejectedRequestError = class _UserRejectedRequestError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: _UserRejectedRequestError.code, + name: "UserRejectedRequestError", + shortMessage: "User rejected the request." }); - continue; } - if (!isHex(result)) { - error = new OffchainLookupResponseMalformedError({ - result, - url: url2 + }; + Object.defineProperty(UserRejectedRequestError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4001 + }); + UnauthorizedProviderError = class _UnauthorizedProviderError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: _UnauthorizedProviderError.code, + name: "UnauthorizedProviderError", + shortMessage: "The requested method and/or account has not been authorized by the user." }); - continue; } - return result; - } catch (err) { - error = new HttpRequestError({ - body, - details: err.message, - url: url2 - }); - } - } - throw error; -} -var offchainLookupSignature, offchainLookupAbiItem; -var init_ccip2 = __esm({ - "node_modules/viem/_esm/utils/ccip.js"() { - init_call(); - init_ccip(); - init_request(); - init_decodeErrorResult(); - init_encodeAbiParameters(); - init_isAddressEqual(); - init_concat(); - init_isHex(); - init_stringify(); - offchainLookupSignature = "0x556f1830"; - offchainLookupAbiItem = { - name: "OffchainLookup", - type: "error", - inputs: [ - { - name: "sender", - type: "address" - }, - { - name: "urls", - type: "string[]" - }, - { - name: "callData", - type: "bytes" - }, - { - name: "callbackFunction", - type: "bytes4" - }, - { - name: "extraData", - type: "bytes" - } - ] }; - } -}); - -// node_modules/viem/_esm/actions/public/call.js -async function call(client, args) { - const { account: account_ = client.account, batch = Boolean(client.batch?.multicall), blockNumber, blockTag = "latest", accessList, blobs, code, data: data_, factory, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value, stateOverride, ...rest } = args; - const account = account_ ? parseAccount(account_) : void 0; - if (code && (factory || factoryData)) - throw new BaseError2("Cannot provide both `code` & `factory`/`factoryData` as parameters."); - if (code && to2) - throw new BaseError2("Cannot provide both `code` & `to` as parameters."); - const deploylessCallViaBytecode = code && data_; - const deploylessCallViaFactory = factory && factoryData && to2 && data_; - const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory; - const data = (() => { - if (deploylessCallViaBytecode) - return toDeploylessCallViaBytecodeData({ - code, - data: data_ - }); - if (deploylessCallViaFactory) - return toDeploylessCallViaFactoryData({ - data: data_, - factory, - factoryData, - to: to2 - }); - return data_; - })(); - try { - assertRequest(args); - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const block = blockNumberHex || blockTag; - const rpcStateOverride = serializeStateOverride(stateOverride); - const chainFormat = client.chain?.formatters?.transactionRequest?.format; - const format = chainFormat || formatTransactionRequest; - const request = format({ - // Pick out extra data that might exist on the chain's transaction request type. - ...extract(rest, { format: chainFormat }), - from: account?.address, - accessList, - blobs, - data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to: deploylessCall ? void 0 : to2, - value + Object.defineProperty(UnauthorizedProviderError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4100 }); - if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) { - try { - return await scheduleMulticall(client, { - ...request, - blockNumber, - blockTag + UnsupportedProviderMethodError = class _UnsupportedProviderMethodError extends ProviderRpcError { + constructor(cause, { method } = {}) { + super(cause, { + code: _UnsupportedProviderMethodError.code, + name: "UnsupportedProviderMethodError", + shortMessage: `The Provider does not support the requested method${method ? ` " ${method}"` : ""}.` }); - } catch (err) { - if (!(err instanceof ClientChainNotConfiguredError) && !(err instanceof ChainDoesNotSupportContract)) - throw err; } - } - const response = await client.request({ - method: "eth_call", - params: rpcStateOverride ? [ - request, - block, - rpcStateOverride - ] : [request, block] + }; + Object.defineProperty(UnsupportedProviderMethodError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4200 }); - if (response === "0x") - return { data: void 0 }; - return { data: response }; - } catch (err) { - const data2 = getRevertErrorData(err); - const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await Promise.resolve().then(() => (init_ccip2(), ccip_exports)); - if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to2) - return { data: await offchainLookup2(client, { data: data2, to: to2 }) }; - if (deploylessCall && data2?.slice(0, 10) === "0x101bb98d") - throw new CounterfactualDeploymentFailedError({ factory }); - throw getCallError(err, { - ...args, - account, - chain: client.chain + ProviderDisconnectedError = class _ProviderDisconnectedError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: _ProviderDisconnectedError.code, + name: "ProviderDisconnectedError", + shortMessage: "The Provider is disconnected from all chains." + }); + } + }; + Object.defineProperty(ProviderDisconnectedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4900 }); - } -} -function shouldPerformMulticall({ request }) { - const { data, to: to2, ...request_ } = request; - if (!data) - return false; - if (data.startsWith(aggregate3Signature)) - return false; - if (!to2) - return false; - if (Object.values(request_).filter((x2) => typeof x2 !== "undefined").length > 0) - return false; - return true; -} -async function scheduleMulticall(client, args) { - const { batchSize = 1024, wait: wait2 = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; - const { blockNumber, blockTag = "latest", data, multicallAddress: multicallAddress_, to: to2 } = args; - let multicallAddress = multicallAddress_; - if (!multicallAddress) { - if (!client.chain) - throw new ClientChainNotConfiguredError(); - multicallAddress = getChainContractAddress({ - blockNumber, - chain: client.chain, - contract: "multicall3" + ChainDisconnectedError = class _ChainDisconnectedError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: _ChainDisconnectedError.code, + name: "ChainDisconnectedError", + shortMessage: "The Provider is not connected to the requested chain." + }); + } + }; + Object.defineProperty(ChainDisconnectedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4901 + }); + SwitchChainError = class _SwitchChainError extends ProviderRpcError { + constructor(cause) { + super(cause, { + code: _SwitchChainError.code, + name: "SwitchChainError", + shortMessage: "An error occurred when attempting to switch chain." + }); + } + }; + Object.defineProperty(SwitchChainError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 4902 }); + UnknownRpcError = class extends RpcError { + constructor(cause) { + super(cause, { + name: "UnknownRpcError", + shortMessage: "An unknown RPC error occurred." + }); + } + }; } - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const block = blockNumberHex || blockTag; - const { schedule } = createBatchScheduler({ - id: `${client.uid}.${block}`, - wait: wait2, - shouldSplitBatch(args2) { - const size5 = args2.reduce((size6, { data: data2 }) => size6 + (data2.length - 2), 0); - return size5 > batchSize * 2; - }, - fn: async (requests) => { - const calls = requests.map((request) => ({ - allowFailure: true, - callData: request.data, - target: request.to - })); - const calldata = encodeFunctionData({ - abi: multicall3Abi, - args: [calls], - functionName: "aggregate3" - }); - const data2 = await client.request({ - method: "eth_call", - params: [ - { - data: calldata, - to: multicallAddress - }, - block - ] - }); - return decodeFunctionResult({ - abi: multicall3Abi, - args: [calls], - functionName: "aggregate3", - data: data2 || "0x" - }); - } - }); - const [{ returnData, success }] = await schedule({ data, to: to2 }); - if (!success) - throw new RawContractError({ data: returnData }); - if (returnData === "0x") - return { data: void 0 }; - return { data: returnData }; -} -function toDeploylessCallViaBytecodeData(parameters) { - const { code, data } = parameters; - return encodeDeployData({ - abi: parseAbi(["constructor(bytes, bytes)"]), - bytecode: deploylessCallViaBytecodeBytecode, - args: [code, data] - }); +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/_md.js +function setBigUint64(view, byteOffset, value, isLE3) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE3); + const _32n3 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n3 & _u32_max); + const wl2 = Number(value & _u32_max); + const h = isLE3 ? 4 : 0; + const l = isLE3 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE3); + view.setUint32(byteOffset + l, wl2, isLE3); } -function toDeploylessCallViaFactoryData(parameters) { - const { data, factory, factoryData, to: to2 } = parameters; - return encodeDeployData({ - abi: parseAbi(["constructor(address, bytes, address, bytes)"]), - bytecode: deploylessCallViaFactoryBytecode, - args: [to2, data, factory, factoryData] - }); +function Chi(a, b2, c) { + return a & b2 ^ ~a & c; } -function getRevertErrorData(err) { - if (!(err instanceof BaseError2)) - return void 0; - const error = err.walk(); - return typeof error?.data === "object" ? error.data?.data : error.data; +function Maj(a, b2, c) { + return a & b2 ^ a & c ^ b2 & c; } -var init_call = __esm({ - "node_modules/viem/_esm/actions/public/call.js"() { - init_exports(); - init_parseAccount(); - init_abis(); - init_contract2(); - init_contracts(); - init_base(); - init_chain(); - init_contract(); - init_decodeFunctionResult(); - init_encodeDeployData(); - init_encodeFunctionData(); - init_getChainContractAddress(); - init_toHex(); - init_getCallError(); - init_extract(); - init_transactionRequest(); - init_createBatchScheduler(); - init_stateOverride2(); - init_assertRequest(); +var HashMD; +var init_md = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/_md.js"() { + init_assert(); + init_utils2(); + HashMD = class extends Hash { + constructor(blockLen, outputLen, padOffset, isLE3) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE3; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + const { view, buffer: buffer2, blockLen } = this; + data = toBytes2(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer2.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE3 } = this; + let { pos } = this; + buffer2[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer2[i] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE3); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to2) { + to2 || (to2 = new this.constructor()); + to2.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to2.length = length; + to2.pos = pos; + to2.finished = finished; + to2.destroyed = destroyed; + if (length % blockLen) + to2.buffer.set(buffer2); + return to2; + } + }; } }); -// node_modules/axios/dist/node/axios.cjs -var require_axios = __commonJS({ - "node_modules/axios/dist/node/axios.cjs"(exports2, module2) { - "use strict"; - var FormData$1 = require_form_data(); - var crypto4 = __require("crypto"); - var url2 = __require("url"); - var proxyFromEnv2 = require_proxy_from_env(); - var http3 = __require("http"); - var https2 = __require("https"); - var util3 = __require("util"); - var followRedirects2 = require_follow_redirects(); - var zlib2 = __require("zlib"); - var stream4 = __require("stream"); - var events = __require("events"); - function _interopDefaultLegacy(e) { - return e && typeof e === "object" && "default" in e ? e : { "default": e }; - } - var FormData__default = /* @__PURE__ */ _interopDefaultLegacy(FormData$1); - var crypto__default = /* @__PURE__ */ _interopDefaultLegacy(crypto4); - var url__default = /* @__PURE__ */ _interopDefaultLegacy(url2); - var proxyFromEnv__default = /* @__PURE__ */ _interopDefaultLegacy(proxyFromEnv2); - var http__default = /* @__PURE__ */ _interopDefaultLegacy(http3); - var https__default = /* @__PURE__ */ _interopDefaultLegacy(https2); - var util__default = /* @__PURE__ */ _interopDefaultLegacy(util3); - var followRedirects__default = /* @__PURE__ */ _interopDefaultLegacy(followRedirects2); - var zlib__default = /* @__PURE__ */ _interopDefaultLegacy(zlib2); - var stream__default = /* @__PURE__ */ _interopDefaultLegacy(stream4); - function bind2(fn2, thisArg) { - return function wrap() { - return fn2.apply(thisArg, arguments); - }; - } - var { toString: toString3 } = Object.prototype; - var { getPrototypeOf: getPrototypeOf2 } = Object; - var { iterator: iterator2, toStringTag: toStringTag2 } = Symbol; - var kindOf2 = /* @__PURE__ */ ((cache) => (thing) => { - const str = toString3.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); - })(/* @__PURE__ */ Object.create(null)); - var kindOfTest2 = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf2(thing) === type; - }; - var typeOfTest2 = (type) => (thing) => typeof thing === type; - var { isArray: isArray2 } = Array; - var isUndefined2 = typeOfTest2("undefined"); - function isBuffer2(val) { - return val !== null && !isUndefined2(val) && val.constructor !== null && !isUndefined2(val.constructor) && isFunction2(val.constructor.isBuffer) && val.constructor.isBuffer(val); - } - var isArrayBuffer2 = kindOfTest2("ArrayBuffer"); - function isArrayBufferView2(val) { - let result; - if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { - result = ArrayBuffer.isView(val); - } else { - result = val && val.buffer && isArrayBuffer2(val.buffer); - } - return result; - } - var isString2 = typeOfTest2("string"); - var isFunction2 = typeOfTest2("function"); - var isNumber2 = typeOfTest2("number"); - var isObject2 = (thing) => thing !== null && typeof thing === "object"; - var isBoolean2 = (thing) => thing === true || thing === false; - var isPlainObject2 = (val) => { - if (kindOf2(val) !== "object") { - return false; +// node_modules/viem/node_modules/@noble/hashes/esm/sha256.js +var SHA256_K, SHA256_IV, SHA256_W, SHA256, sha256; +var init_sha256 = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/sha256.js"() { + init_md(); + init_utils2(); + SHA256_K = /* @__PURE__ */ new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]); + SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 + ]); + SHA256_W = /* @__PURE__ */ new Uint32Array(64); + SHA256 = class extends HashMD { + constructor() { + super(64, 32, 8, false); + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; } - const prototype4 = getPrototypeOf2(val); - return (prototype4 === null || prototype4 === Object.prototype || Object.getPrototypeOf(prototype4) === null) && !(toStringTag2 in val) && !(iterator2 in val); - }; - var isDate2 = kindOfTest2("Date"); - var isFile2 = kindOfTest2("File"); - var isBlob2 = kindOfTest2("Blob"); - var isFileList2 = kindOfTest2("FileList"); - var isStream2 = (val) => isObject2(val) && isFunction2(val.pipe); - var isFormData2 = (thing) => { - let kind; - return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction2(thing.append) && ((kind = kindOf2(thing)) === "formdata" || // detect form-data instance - kind === "object" && isFunction2(thing.toString) && thing.toString() === "[object FormData]")); - }; - var isURLSearchParams2 = kindOfTest2("URLSearchParams"); - var [isReadableStream2, isRequest2, isResponse2, isHeaders2] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest2); - var trim5 = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); - function forEach2(obj, fn2, { allOwnKeys = false } = {}) { - if (obj === null || typeof obj === "undefined") { - return; + get() { + const { A: A2, B: B2, C, D, E, F: F2, G: G2, H: H2 } = this; + return [A2, B2, C, D, E, F2, G2, H2]; } - let i; - let l; - if (typeof obj !== "object") { - obj = [obj]; + // prettier-ignore + set(A2, B2, C, D, E, F2, G2, H2) { + this.A = A2 | 0; + this.B = B2 | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F2 | 0; + this.G = G2 | 0; + this.H = H2 | 0; } - if (isArray2(obj)) { - for (i = 0, l = obj.length; i < l; i++) { - fn2.call(null, obj[i], i, obj); + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; } - } else { - const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys.length; - let key; - for (i = 0; i < len; i++) { - key = keys[i]; - fn2.call(null, obj[key], key, obj); + let { A: A2, B: B2, C, D, E, F: F2, G: G2, H: H2 } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H2 + sigma1 + Chi(E, F2, G2) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A2, 2) ^ rotr(A2, 13) ^ rotr(A2, 22); + const T2 = sigma0 + Maj(A2, B2, C) | 0; + H2 = G2; + G2 = F2; + F2 = E; + E = D + T1 | 0; + D = C; + C = B2; + B2 = A2; + A2 = T1 + T2 | 0; } + A2 = A2 + this.A | 0; + B2 = B2 + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F2 = F2 + this.F | 0; + G2 = G2 + this.G | 0; + H2 = H2 + this.H | 0; + this.set(A2, B2, C, D, E, F2, G2, H2); } - } - function findKey2(obj, key) { - key = key.toLowerCase(); - const keys = Object.keys(obj); - let i = keys.length; - let _key; - while (i-- > 0) { - _key = keys[i]; - if (key === _key.toLowerCase()) { - return _key; - } + roundClean() { + SHA256_W.fill(0); } - return null; - } - var _global2 = (() => { - if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; - })(); - var isContextDefined2 = (context) => !isUndefined2(context) && context !== _global2; - function merge2() { - const { caseless } = isContextDefined2(this) && this || {}; - const result = {}; - const assignValue = (val, key) => { - const targetKey = caseless && findKey2(result, key) || key; - if (isPlainObject2(result[targetKey]) && isPlainObject2(val)) { - result[targetKey] = merge2(result[targetKey], val); - } else if (isPlainObject2(val)) { - result[targetKey] = merge2({}, val); - } else if (isArray2(val)) { - result[targetKey] = val.slice(); - } else { - result[targetKey] = val; - } - }; - for (let i = 0, l = arguments.length; i < l; i++) { - arguments[i] && forEach2(arguments[i], assignValue); + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); } - return result; - } - var extend2 = (a, b2, thisArg, { allOwnKeys } = {}) => { - forEach2(b2, (val, key) => { - if (thisArg && isFunction2(val)) { - a[key] = bind2(val, thisArg); - } else { - a[key] = val; - } - }, { allOwnKeys }); - return a; }; - var stripBOM2 = (content) => { - if (content.charCodeAt(0) === 65279) { - content = content.slice(1); + sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); + } +}); + +// node_modules/viem/node_modules/@noble/hashes/esm/hmac.js +var HMAC, hmac; +var init_hmac = __esm({ + "node_modules/viem/node_modules/@noble/hashes/esm/hmac.js"() { + init_assert(); + init_utils2(); + HMAC = class extends Hash { + constructor(hash2, _key) { + super(); + this.finished = false; + this.destroyed = false; + ahash(hash2); + const key = toBytes2(_key); + this.iHash = hash2.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad4 = new Uint8Array(blockLen); + pad4.set(key.length > blockLen ? hash2.create().update(key).digest() : key); + for (let i = 0; i < pad4.length; i++) + pad4[i] ^= 54; + this.iHash.update(pad4); + this.oHash = hash2.create(); + for (let i = 0; i < pad4.length; i++) + pad4[i] ^= 54 ^ 92; + this.oHash.update(pad4); + pad4.fill(0); } - return content; - }; - var inherits2 = (constructor, superConstructor, props, descriptors3) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors3); - constructor.prototype.constructor = constructor; - Object.defineProperty(constructor, "super", { - value: superConstructor.prototype - }); - props && Object.assign(constructor.prototype, props); - }; - var toFlatObject2 = (sourceObj, destObj, filter2, propFilter) => { - let props; - let i; - let prop; - const merged = {}; - destObj = destObj || {}; - if (sourceObj == null) return destObj; - do { - props = Object.getOwnPropertyNames(sourceObj); - i = props.length; - while (i-- > 0) { - prop = props[i]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } - } - sourceObj = filter2 !== false && getPrototypeOf2(sourceObj); - } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype); - return destObj; - }; - var endsWith2 = (str, searchString, position) => { - str = String(str); - if (position === void 0 || position > str.length) { - position = str.length; + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; } - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; + digestInto(out) { + aexists(this); + abytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to2) { + to2 || (to2 = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to2 = to2; + to2.finished = finished; + to2.destroyed = destroyed; + to2.blockLen = blockLen; + to2.outputLen = outputLen; + to2.oHash = oHash._cloneInto(to2.oHash); + to2.iHash = iHash._cloneInto(to2.iHash); + return to2; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } + }; + hmac = (hash2, key, message) => new HMAC(hash2, key).update(message).digest(); + hmac.create = (hash2, key) => new HMAC(hash2, key); + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/abstract/utils.js +var utils_exports = {}; +__export(utils_exports, { + aInRange: () => aInRange, + abool: () => abool, + abytes: () => abytes2, + bitGet: () => bitGet, + bitLen: () => bitLen, + bitMask: () => bitMask, + bitSet: () => bitSet, + bytesToHex: () => bytesToHex2, + bytesToNumberBE: () => bytesToNumberBE, + bytesToNumberLE: () => bytesToNumberLE, + concatBytes: () => concatBytes3, + createHmacDrbg: () => createHmacDrbg, + ensureBytes: () => ensureBytes, + equalBytes: () => equalBytes, + hexToBytes: () => hexToBytes2, + hexToNumber: () => hexToNumber2, + inRange: () => inRange, + isBytes: () => isBytes2, + memoized: () => memoized, + notImplemented: () => notImplemented, + numberToBytesBE: () => numberToBytesBE, + numberToBytesLE: () => numberToBytesLE, + numberToHexUnpadded: () => numberToHexUnpadded, + numberToVarBytesBE: () => numberToVarBytesBE, + utf8ToBytes: () => utf8ToBytes2, + validateObject: () => validateObject +}); +function isBytes2(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; +} +function abytes2(item) { + if (!isBytes2(item)) + throw new Error("Uint8Array expected"); +} +function abool(title, value) { + if (typeof value !== "boolean") + throw new Error(title + " boolean expected, got " + value); +} +function bytesToHex2(bytes) { + abytes2(bytes); + let hex = ""; + for (let i = 0; i < bytes.length; i++) { + hex += hexes2[bytes[i]]; + } + return hex; +} +function numberToHexUnpadded(num2) { + const hex = num2.toString(16); + return hex.length & 1 ? "0" + hex : hex; +} +function hexToNumber2(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + return hex === "" ? _0n2 : BigInt("0x" + hex); +} +function asciiToBase16(ch) { + if (ch >= asciis._0 && ch <= asciis._9) + return ch - asciis._0; + if (ch >= asciis.A && ch <= asciis.F) + return ch - (asciis.A - 10); + if (ch >= asciis.a && ch <= asciis.f) + return ch - (asciis.a - 10); + return; +} +function hexToBytes2(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + const hl2 = hex.length; + const al2 = hl2 / 2; + if (hl2 % 2) + throw new Error("hex string expected, got unpadded hex of length " + hl2); + const array = new Uint8Array(al2); + for (let ai2 = 0, hi2 = 0; ai2 < al2; ai2++, hi2 += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi2)); + const n2 = asciiToBase16(hex.charCodeAt(hi2 + 1)); + if (n1 === void 0 || n2 === void 0) { + const char = hex[hi2] + hex[hi2 + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi2); + } + array[ai2] = n1 * 16 + n2; + } + return array; +} +function bytesToNumberBE(bytes) { + return hexToNumber2(bytesToHex2(bytes)); +} +function bytesToNumberLE(bytes) { + abytes2(bytes); + return hexToNumber2(bytesToHex2(Uint8Array.from(bytes).reverse())); +} +function numberToBytesBE(n, len) { + return hexToBytes2(n.toString(16).padStart(len * 2, "0")); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +function numberToVarBytesBE(n) { + return hexToBytes2(numberToHexUnpadded(n)); +} +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === "string") { + try { + res = hexToBytes2(hex); + } catch (e) { + throw new Error(title + " must be hex string or Uint8Array, cause: " + e); + } + } else if (isBytes2(hex)) { + res = Uint8Array.from(hex); + } else { + throw new Error(title + " must be hex string or Uint8Array"); + } + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) + throw new Error(title + " of length " + expectedLength + " expected, got " + len); + return res; +} +function concatBytes3(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes2(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad4 = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad4); + pad4 += a.length; + } + return res; +} +function equalBytes(a, b2) { + if (a.length !== b2.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b2[i]; + return diff === 0; +} +function utf8ToBytes2(str) { + if (typeof str !== "string") + throw new Error("string expected"); + return new Uint8Array(new TextEncoder().encode(str)); +} +function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +function aInRange(title, n, min, max) { + if (!inRange(n, min, max)) + throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); +} +function bitLen(n) { + let len; + for (len = 0; n > _0n2; n >>= _1n2, len += 1) + ; + return len; +} +function bitGet(n, pos) { + return n >> BigInt(pos) & _1n2; +} +function bitSet(n, pos, value) { + return n | (value ? _1n2 : _0n2) << BigInt(pos); +} +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) + throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) + throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") + throw new Error("hmacFn must be a function"); + let v = u8n(hashLen); + let k2 = u8n(hashLen); + let i = 0; + const reset = () => { + v.fill(1); + k2.fill(0); + i = 0; + }; + const h = (...b2) => hmacFn(k2, v, ...b2); + const reseed = (seed = u8n()) => { + k2 = h(u8fr([0]), seed); + v = h(); + if (seed.length === 0) + return; + k2 = h(u8fr([1]), seed); + v = h(); + }; + const gen3 = () => { + if (i++ >= 1e3) + throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl2 = v.slice(); + out.push(sl2); + len += v.length; + } + return concatBytes3(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = void 0; + while (!(res = pred(gen3()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +function validateObject(object, validators3, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== "function") + throw new Error("invalid validator function"); + const val = object[fieldName]; + if (isOptional && val === void 0) + return; + if (!checkVal(val, object)) { + throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val); + } + }; + for (const [fieldName, type] of Object.entries(validators3)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +function memoized(fn2) { + const map = /* @__PURE__ */ new WeakMap(); + return (arg, ...args) => { + const val = map.get(arg); + if (val !== void 0) + return val; + const computed = fn2(arg, ...args); + map.set(arg, computed); + return computed; + }; +} +var _0n2, _1n2, _2n2, hexes2, asciis, isPosBig, bitMask, u8n, u8fr, validatorFns, notImplemented; +var init_utils4 = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/abstract/utils.js"() { + _0n2 = /* @__PURE__ */ BigInt(0); + _1n2 = /* @__PURE__ */ BigInt(1); + _2n2 = /* @__PURE__ */ BigInt(2); + hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); + asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; + isPosBig = (n) => typeof n === "bigint" && _0n2 <= n; + bitMask = (n) => (_2n2 << BigInt(n - 1)) - _1n2; + u8n = (data) => new Uint8Array(data); + u8fr = (arr) => Uint8Array.from(arr); + validatorFns = { + bigint: (val) => typeof val === "bigint", + function: (val) => typeof val === "function", + boolean: (val) => typeof val === "boolean", + string: (val) => typeof val === "string", + stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val), + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) }; - var toArray2 = (thing) => { - if (!thing) return null; - if (isArray2(thing)) return thing; - let i = thing.length; - if (!isNumber2(i)) return null; - const arr = new Array(i); - while (i-- > 0) { - arr[i] = thing[i]; - } - return arr; + notImplemented = () => { + throw new Error("not implemented"); }; - var isTypedArray2 = /* @__PURE__ */ ((TypedArray) => { - return (thing) => { - return TypedArray && thing instanceof TypedArray; - }; - })(typeof Uint8Array !== "undefined" && getPrototypeOf2(Uint8Array)); - var forEachEntry2 = (obj, fn2) => { - const generator = obj && obj[iterator2]; - const _iterator = generator.call(obj); - let result; - while ((result = _iterator.next()) && !result.done) { - const pair = result.value; - fn2.call(obj, pair[0], pair[1]); - } + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/abstract/modular.js +function mod(a, b2) { + const result = a % b2; + return result >= _0n3 ? result : b2 + result; +} +function pow(num2, power, modulo) { + if (power < _0n3) + throw new Error("invalid exponent, negatives unsupported"); + if (modulo <= _0n3) + throw new Error("invalid modulus"); + if (modulo === _1n3) + return _0n3; + let res = _1n3; + while (power > _0n3) { + if (power & _1n3) + res = res * num2 % modulo; + num2 = num2 * num2 % modulo; + power >>= _1n3; + } + return res; +} +function pow2(x2, power, modulo) { + let res = x2; + while (power-- > _0n3) { + res *= res; + res %= modulo; + } + return res; +} +function invert(number, modulo) { + if (number === _0n3) + throw new Error("invert: expected non-zero number"); + if (modulo <= _0n3) + throw new Error("invert: expected positive modulus, got " + modulo); + let a = mod(number, modulo); + let b2 = modulo; + let x2 = _0n3, y2 = _1n3, u = _1n3, v = _0n3; + while (a !== _0n3) { + const q2 = b2 / a; + const r = b2 % a; + const m2 = x2 - u * q2; + const n = y2 - v * q2; + b2 = a, a = r, x2 = u, y2 = v, u = m2, v = n; + } + const gcd = b2; + if (gcd !== _1n3) + throw new Error("invert: does not exist"); + return mod(x2, modulo); +} +function tonelliShanks(P2) { + const legendreC = (P2 - _1n3) / _2n3; + let Q, S, Z2; + for (Q = P2 - _1n3, S = 0; Q % _2n3 === _0n3; Q /= _2n3, S++) + ; + for (Z2 = _2n3; Z2 < P2 && pow(Z2, legendreC, P2) !== P2 - _1n3; Z2++) { + if (Z2 > 1e3) + throw new Error("Cannot find square root: likely non-prime P"); + } + if (S === 1) { + const p1div4 = (P2 + _1n3) / _4n; + return function tonelliFast(Fp2, n) { + const root = Fp2.pow(n, p1div4); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; }; - var matchAll2 = (regExp, str) => { - let matches; - const arr = []; - while ((matches = regExp.exec(str)) !== null) { - arr.push(matches); + } + const Q1div2 = (Q + _1n3) / _2n3; + return function tonelliSlow(Fp2, n) { + if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) + throw new Error("Cannot find square root"); + let r = S; + let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z2), Q); + let x2 = Fp2.pow(n, Q1div2); + let b2 = Fp2.pow(n, Q); + while (!Fp2.eql(b2, Fp2.ONE)) { + if (Fp2.eql(b2, Fp2.ZERO)) + return Fp2.ZERO; + let m2 = 1; + for (let t2 = Fp2.sqr(b2); m2 < r; m2++) { + if (Fp2.eql(t2, Fp2.ONE)) + break; + t2 = Fp2.sqr(t2); } - return arr; - }; - var isHTMLForm2 = kindOfTest2("HTMLFormElement"); - var toCamelCase2 = (str) => { - return str.toLowerCase().replace( - /[-_\s]([a-z\d])(\w*)/g, - function replacer(m2, p1, p2) { - return p1.toUpperCase() + p2; - } - ); - }; - var hasOwnProperty2 = (({ hasOwnProperty: hasOwnProperty3 }) => (obj, prop) => hasOwnProperty3.call(obj, prop))(Object.prototype); - var isRegExp2 = kindOfTest2("RegExp"); - var reduceDescriptors2 = (obj, reducer) => { - const descriptors3 = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; - forEach2(descriptors3, (descriptor, name) => { - let ret; - if ((ret = reducer(descriptor, name, obj)) !== false) { - reducedDescriptors[name] = ret || descriptor; - } - }); - Object.defineProperties(obj, reducedDescriptors); - }; - var freezeMethods2 = (obj) => { - reduceDescriptors2(obj, (descriptor, name) => { - if (isFunction2(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) { - return false; - } - const value = obj[name]; - if (!isFunction2(value)) return; - descriptor.enumerable = false; - if ("writable" in descriptor) { - descriptor.writable = false; - return; - } - if (!descriptor.set) { - descriptor.set = () => { - throw Error("Can not rewrite read-only method '" + name + "'"); - }; - } - }); - }; - var toObjectSet2 = (arrayOrString, delimiter) => { - const obj = {}; - const define2 = (arr) => { - arr.forEach((value) => { - obj[value] = true; - }); - }; - isArray2(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); - return obj; - }; - var noop2 = () => { - }; - var toFiniteNumber2 = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; - }; - function isSpecCompliantForm2(thing) { - return !!(thing && isFunction2(thing.append) && thing[toStringTag2] === "FormData" && thing[iterator2]); + const ge2 = Fp2.pow(g, _1n3 << BigInt(r - m2 - 1)); + g = Fp2.sqr(ge2); + x2 = Fp2.mul(x2, ge2); + b2 = Fp2.mul(b2, g); + r = m2; } - var toJSONObject2 = (obj) => { - const stack = new Array(10); - const visit = (source, i) => { - if (isObject2(source)) { - if (stack.indexOf(source) >= 0) { - return; - } - if (!("toJSON" in source)) { - stack[i] = source; - const target = isArray2(source) ? [] : {}; - forEach2(source, (value, key) => { - const reducedValue = visit(value, i + 1); - !isUndefined2(reducedValue) && (target[key] = reducedValue); - }); - stack[i] = void 0; - return target; - } - } - return source; - }; - return visit(obj, 0); - }; - var isAsyncFn2 = kindOfTest2("AsyncFunction"); - var isThenable2 = (thing) => thing && (isObject2(thing) || isFunction2(thing)) && isFunction2(thing.then) && isFunction2(thing.catch); - var _setImmediate2 = ((setImmediateSupported, postMessageSupported) => { - if (setImmediateSupported) { - return setImmediate; - } - return postMessageSupported ? ((token, callbacks) => { - _global2.addEventListener("message", ({ source, data }) => { - if (source === _global2 && data === token) { - callbacks.length && callbacks.shift()(); - } - }, false); - return (cb) => { - callbacks.push(cb); - _global2.postMessage(token, "*"); - }; - })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); - })( - typeof setImmediate === "function", - isFunction2(_global2.postMessage) - ); - var asap2 = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global2) : typeof process !== "undefined" && process.nextTick || _setImmediate2; - var isIterable2 = (thing) => thing != null && isFunction2(thing[iterator2]); - var utils$1 = { - isArray: isArray2, - isArrayBuffer: isArrayBuffer2, - isBuffer: isBuffer2, - isFormData: isFormData2, - isArrayBufferView: isArrayBufferView2, - isString: isString2, - isNumber: isNumber2, - isBoolean: isBoolean2, - isObject: isObject2, - isPlainObject: isPlainObject2, - isReadableStream: isReadableStream2, - isRequest: isRequest2, - isResponse: isResponse2, - isHeaders: isHeaders2, - isUndefined: isUndefined2, - isDate: isDate2, - isFile: isFile2, - isBlob: isBlob2, - isRegExp: isRegExp2, - isFunction: isFunction2, - isStream: isStream2, - isURLSearchParams: isURLSearchParams2, - isTypedArray: isTypedArray2, - isFileList: isFileList2, - forEach: forEach2, - merge: merge2, - extend: extend2, - trim: trim5, - stripBOM: stripBOM2, - inherits: inherits2, - toFlatObject: toFlatObject2, - kindOf: kindOf2, - kindOfTest: kindOfTest2, - endsWith: endsWith2, - toArray: toArray2, - forEachEntry: forEachEntry2, - matchAll: matchAll2, - isHTMLForm: isHTMLForm2, - hasOwnProperty: hasOwnProperty2, - hasOwnProp: hasOwnProperty2, - // an alias to avoid ESLint no-prototype-builtins detection - reduceDescriptors: reduceDescriptors2, - freezeMethods: freezeMethods2, - toObjectSet: toObjectSet2, - toCamelCase: toCamelCase2, - noop: noop2, - toFiniteNumber: toFiniteNumber2, - findKey: findKey2, - global: _global2, - isContextDefined: isContextDefined2, - isSpecCompliantForm: isSpecCompliantForm2, - toJSONObject: toJSONObject2, - isAsyncFn: isAsyncFn2, - isThenable: isThenable2, - setImmediate: _setImmediate2, - asap: asap2, - isIterable: isIterable2 + return x2; + }; +} +function FpSqrt(P2) { + if (P2 % _4n === _3n) { + const p1div4 = (P2 + _1n3) / _4n; + return function sqrt3mod4(Fp2, n) { + const root = Fp2.pow(n, p1div4); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; }; - function AxiosError3(message, code, config3, request, response) { - Error.call(this); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = new Error().stack; - } - this.message = message; - this.name = "AxiosError"; - code && (this.code = code); - config3 && (this.config = config3); - request && (this.request = request); - if (response) { - this.response = response; - this.status = response.status ? response.status : null; - } - } - utils$1.inherits(AxiosError3, Error, { - toJSON: function toJSON2() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: utils$1.toJSONObject(this.config), - code: this.code, - status: this.status - }; - } - }); - var prototype$1 = AxiosError3.prototype; - var descriptors2 = {}; - [ - "ERR_BAD_OPTION_VALUE", - "ERR_BAD_OPTION", - "ECONNABORTED", - "ETIMEDOUT", - "ERR_NETWORK", - "ERR_FR_TOO_MANY_REDIRECTS", - "ERR_DEPRECATED", - "ERR_BAD_RESPONSE", - "ERR_BAD_REQUEST", - "ERR_CANCELED", - "ERR_NOT_SUPPORT", - "ERR_INVALID_URL" - // eslint-disable-next-line func-names - ].forEach((code) => { - descriptors2[code] = { value: code }; - }); - Object.defineProperties(AxiosError3, descriptors2); - Object.defineProperty(prototype$1, "isAxiosError", { value: true }); - AxiosError3.from = (error, code, config3, request, response, customProps) => { - const axiosError = Object.create(prototype$1); - utils$1.toFlatObject(error, axiosError, function filter2(obj) { - return obj !== Error.prototype; - }, (prop) => { - return prop !== "isAxiosError"; - }); - AxiosError3.call(axiosError, error.message, code, config3, request, response); - axiosError.cause = error; - axiosError.name = error.name; - customProps && Object.assign(axiosError, customProps); - return axiosError; + } + if (P2 % _8n === _5n) { + const c1 = (P2 - _5n) / _8n; + return function sqrt5mod8(Fp2, n) { + const n2 = Fp2.mul(n, _2n3); + const v = Fp2.pow(n2, c1); + const nv = Fp2.mul(n, v); + const i = Fp2.mul(Fp2.mul(nv, _2n3), v); + const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; }; - function isVisitable2(thing) { - return utils$1.isPlainObject(thing) || utils$1.isArray(thing); - } - function removeBrackets2(key) { - return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key; - } - function renderKey2(path, key, dots) { - if (!path) return key; - return path.concat(key).map(function each(token, i) { - token = removeBrackets2(token); - return !dots && i ? "[" + token + "]" : token; - }).join(dots ? "." : ""); - } - function isFlatArray2(arr) { - return utils$1.isArray(arr) && !arr.some(isVisitable2); + } + if (P2 % _16n === _9n) { + } + return tonelliShanks(P2); +} +function validateField(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "isSafeInteger", + BITS: "isSafeInteger" + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + return validateObject(field, opts); +} +function FpPow(f, num2, power) { + if (power < _0n3) + throw new Error("invalid exponent, negatives unsupported"); + if (power === _0n3) + return f.ONE; + if (power === _1n3) + return num2; + let p = f.ONE; + let d = num2; + while (power > _0n3) { + if (power & _1n3) + p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n3; + } + return p; +} +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num2, i) => { + if (f.is0(num2)) + return acc; + tmp[i] = acc; + return f.mul(acc, num2); + }, f.ONE); + const inverted = f.inv(lastMultiplied); + nums.reduceRight((acc, num2, i) => { + if (f.is0(num2)) + return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num2); + }, inverted); + return tmp; +} +function nLength(n, nBitLength) { + const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +function Field(ORDER, bitLen2, isLE3 = false, redef = {}) { + if (ORDER <= _0n3) + throw new Error("invalid field: expected ORDER > 0, got " + ORDER); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); + if (BYTES > 2048) + throw new Error("invalid field: expected ORDER of <= 2048 bytes"); + let sqrtP; + const f = Object.freeze({ + ORDER, + isLE: isLE3, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n3, + ONE: _1n3, + create: (num2) => mod(num2, ORDER), + isValid: (num2) => { + if (typeof num2 !== "bigint") + throw new Error("invalid field element: expected bigint, got " + typeof num2); + return _0n3 <= num2 && num2 < ORDER; + }, + is0: (num2) => num2 === _0n3, + isOdd: (num2) => (num2 & _1n3) === _1n3, + neg: (num2) => mod(-num2, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num2) => mod(num2 * num2, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num2, power) => FpPow(f, num2, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num2) => num2 * num2, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num2) => invert(num2, ORDER), + sqrt: redef.sqrt || ((n) => { + if (!sqrtP) + sqrtP = FpSqrt(ORDER); + return sqrtP(f, n); + }), + invertBatch: (lst) => FpInvertBatch(f, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b2, c) => c ? b2 : a, + toBytes: (num2) => isLE3 ? numberToBytesLE(num2, BYTES) : numberToBytesBE(num2, BYTES), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); + return isLE3 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); } - var predicates2 = utils$1.toFlatObject(utils$1, {}, null, function filter2(prop) { - return /^is[A-Z]/.test(prop); - }); - function toFormData3(obj, formData, options) { - if (!utils$1.isObject(obj)) { - throw new TypeError("target must be an object"); - } - formData = formData || new (FormData__default["default"] || FormData)(); - options = utils$1.toFlatObject(options, { - metaTokens: true, - dots: false, - indexes: false - }, false, function defined(option, source) { - return !utils$1.isUndefined(source[option]); - }); - const metaTokens = options.metaTokens; - const visitor = options.visitor || defaultVisitor; - const dots = options.dots; - const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; - const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); - if (!utils$1.isFunction(visitor)) { - throw new TypeError("visitor must be a function"); + }); + return Object.freeze(f); +} +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== "bigint") + throw new Error("field order must be bigint"); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +function mapHashToField(key, fieldOrder, isLE3 = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + if (len < 16 || len < minLen || len > 1024) + throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); + const num2 = isLE3 ? bytesToNumberLE(key) : bytesToNumberBE(key); + const reduced = mod(num2, fieldOrder - _1n3) + _1n3; + return isLE3 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} +var _0n3, _1n3, _2n3, _3n, _4n, _5n, _8n, _9n, _16n, FIELD_FIELDS; +var init_modular = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/abstract/modular.js"() { + init_utils4(); + _0n3 = BigInt(0); + _1n3 = BigInt(1); + _2n3 = /* @__PURE__ */ BigInt(2); + _3n = /* @__PURE__ */ BigInt(3); + _4n = /* @__PURE__ */ BigInt(4); + _5n = /* @__PURE__ */ BigInt(5); + _8n = /* @__PURE__ */ BigInt(8); + _9n = /* @__PURE__ */ BigInt(9); + _16n = /* @__PURE__ */ BigInt(16); + FIELD_FIELDS = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" + ]; + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/abstract/curve.js +function constTimeNegate(condition, item) { + const neg = item.negate(); + return condition ? neg : item; +} +function validateW(W2, bits) { + if (!Number.isSafeInteger(W2) || W2 <= 0 || W2 > bits) + throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W2); +} +function calcWOpts(W2, bits) { + validateW(W2, bits); + const windows = Math.ceil(bits / W2) + 1; + const windowSize = 2 ** (W2 - 1); + return { windows, windowSize }; +} +function validateMSMPoints(points, c) { + if (!Array.isArray(points)) + throw new Error("array expected"); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error("invalid point at index " + i); + }); +} +function validateMSMScalars(scalars, field) { + if (!Array.isArray(scalars)) + throw new Error("array of scalars expected"); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error("invalid scalar at index " + i); + }); +} +function getW(P2) { + return pointWindowSizes.get(P2) || 1; +} +function wNAF(c, bits) { + return { + constTimeNegate, + hasPrecomputes(elm) { + return getW(elm) !== 1; + }, + // non-const time multiplication ladder + unsafeLadder(elm, n, p = c.ZERO) { + let d = elm; + while (n > _0n4) { + if (n & _1n4) + p = p.add(d); + d = d.double(); + n >>= _1n4; } - function convertValue(value) { - if (value === null) return ""; - if (utils$1.isDate(value)) { - return value.toISOString(); - } - if (!useBlob && utils$1.isBlob(value)) { - throw new AxiosError3("Blob is not supported. Use a Buffer instead."); - } - if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { - return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @param elm Point instance + * @param W window size + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W2) { + const { windows, windowSize } = calcWOpts(W2, bits); + const points = []; + let p = elm; + let base = p; + for (let window2 = 0; window2 < windows; window2++) { + base = p; + points.push(base); + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); } - return value; + p = base.double(); } - function defaultVisitor(value, key, path) { - let arr = value; - if (value && !path && typeof value === "object") { - if (utils$1.endsWith(key, "{}")) { - key = metaTokens ? key : key.slice(0, -2); - value = JSON.stringify(value); - } else if (utils$1.isArray(value) && isFlatArray2(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) { - key = removeBrackets2(key); - arr.forEach(function each(el2, index2) { - !(utils$1.isUndefined(el2) || el2 === null) && formData.append( - // eslint-disable-next-line no-nested-ternary - indexes === true ? renderKey2([key], index2, dots) : indexes === null ? key : key + "[]", - convertValue(el2) - ); - }); - return false; - } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W2, precomputes, n) { + const { windows, windowSize } = calcWOpts(W2, bits); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W2 - 1); + const maxNumber = 2 ** W2; + const shiftBy = BigInt(W2); + for (let window2 = 0; window2 < windows; window2++) { + const offset = window2 * windowSize; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n4; } - if (isVisitable2(value)) { - return true; + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; + const cond1 = window2 % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); } - formData.append(renderKey2(path, key, dots), convertValue(value)); - return false; } - const stack = []; - const exposedHelpers = Object.assign(predicates2, { - defaultVisitor, - convertValue, - isVisitable: isVisitable2 - }); - function build(value, path) { - if (utils$1.isUndefined(value)) return; - if (stack.indexOf(value) !== -1) { - throw Error("Circular reference detected in " + path.join(".")); + return { p, f }; + }, + /** + * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @param acc accumulator point to add result of multiplication + * @returns point + */ + wNAFUnsafe(W2, precomputes, n, acc = c.ZERO) { + const { windows, windowSize } = calcWOpts(W2, bits); + const mask = BigInt(2 ** W2 - 1); + const maxNumber = 2 ** W2; + const shiftBy = BigInt(W2); + for (let window2 = 0; window2 < windows; window2++) { + const offset = window2 * windowSize; + if (n === _0n4) + break; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n4; } - stack.push(value); - utils$1.forEach(value, function each(el2, key) { - const result = !(utils$1.isUndefined(el2) || el2 === null) && visitor.call( - formData, - el2, - utils$1.isString(key) ? key.trim() : key, - path, - exposedHelpers - ); - if (result === true) { - build(el2, path ? path.concat(key) : [key]); - } - }); - stack.pop(); + if (wbits === 0) + continue; + let curr = precomputes[offset + Math.abs(wbits) - 1]; + if (wbits < 0) + curr = curr.negate(); + acc = acc.add(curr); } - if (!utils$1.isObject(obj)) { - throw new TypeError("data must be an object"); + return acc; + }, + getPrecomputes(W2, P2, transform) { + let comp = pointPrecomputes.get(P2); + if (!comp) { + comp = this.precomputeWindow(P2, W2); + if (W2 !== 1) + pointPrecomputes.set(P2, transform(comp)); } - build(obj); - return formData; + return comp; + }, + wNAFCached(P2, n, transform) { + const W2 = getW(P2); + return this.wNAF(W2, this.getPrecomputes(W2, P2, transform), n); + }, + wNAFCachedUnsafe(P2, n, transform, prev) { + const W2 = getW(P2); + if (W2 === 1) + return this.unsafeLadder(P2, n, prev); + return this.wNAFUnsafe(W2, this.getPrecomputes(W2, P2, transform), n, prev); + }, + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + setWindowSize(P2, W2) { + validateW(W2, bits); + pointWindowSizes.set(P2, W2); + pointPrecomputes.delete(P2); + } + }; +} +function pippenger(c, fieldN, points, scalars) { + validateMSMPoints(points, c); + validateMSMScalars(scalars, fieldN); + if (points.length !== scalars.length) + throw new Error("arrays of points and scalars must have equal length"); + const zero = c.ZERO; + const wbits = bitLen(BigInt(points.length)); + const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; + const MASK = (1 << windowSize) - 1; + const buckets = new Array(MASK + 1).fill(zero); + const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; + let sum = zero; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(zero); + for (let j2 = 0; j2 < scalars.length; j2++) { + const scalar = scalars[j2]; + const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK)); + buckets[wbits2] = buckets[wbits2].add(points[j2]); + } + let resI = zero; + for (let j2 = buckets.length - 1, sumI = zero; j2 > 0; j2--) { + sumI = sumI.add(buckets[j2]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) + for (let j2 = 0; j2 < windowSize; j2++) + sum = sum.double(); + } + return sum; +} +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: "bigint", + h: "bigint", + Gx: "field", + Gy: "field" + }, { + nBitLength: "isSafeInteger", + nByteLength: "isSafeInteger" + }); + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER } + }); +} +var _0n4, _1n4, pointPrecomputes, pointWindowSizes; +var init_curve = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/abstract/curve.js"() { + init_modular(); + init_utils4(); + _0n4 = BigInt(0); + _1n4 = BigInt(1); + pointPrecomputes = /* @__PURE__ */ new WeakMap(); + pointWindowSizes = /* @__PURE__ */ new WeakMap(); + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/abstract/weierstrass.js +function validateSigVerOpts(opts) { + if (opts.lowS !== void 0) + abool("lowS", opts.lowS); + if (opts.prehash !== void 0) + abool("prehash", opts.prehash); +} +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: "field", + b: "field" + }, { + allowedPrivateKeyLengths: "array", + wrapPrivateKey: "boolean", + isTorsionFree: "function", + clearCofactor: "function", + allowInfinityPoint: "boolean", + fromBytes: "function", + toBytes: "function" + }); + const { endo, Fp: Fp2, a } = opts; + if (endo) { + if (!Fp2.eql(a, Fp2.ZERO)) { + throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0"); + } + if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { + throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function"); + } + } + return Object.freeze({ ...opts }); +} +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp: Fp2 } = CURVE; + const Fn2 = Field(CURVE.n, CURVE.nBitLength); + const toBytes4 = CURVE.toBytes || ((_c2, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes3(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); + }); + const fromBytes2 = CURVE.fromBytes || ((bytes) => { + const tail = bytes.subarray(1); + const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x: x2, y: y2 }; + }); + function weierstrassEquation(x2) { + const { a, b: b2 } = CURVE; + const x22 = Fp2.sqr(x2); + const x3 = Fp2.mul(x22, x2); + return Fp2.add(Fp2.add(x3, Fp2.mul(x2, a)), b2); + } + if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) + throw new Error("bad generator point: equation left != right"); + function isWithinCurveOrder(num2) { + return inRange(num2, _1n5, CURVE.n); + } + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N2 } = CURVE; + if (lengths && typeof key !== "bigint") { + if (isBytes2(key)) + key = bytesToHex2(key); + if (typeof key !== "string" || !lengths.includes(key.length)) + throw new Error("invalid private key"); + key = key.padStart(nByteLength * 2, "0"); + } + let num2; + try { + num2 = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); + } catch (error) { + throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key); + } + if (wrapPrivateKey) + num2 = mod(num2, N2); + aInRange("private key", num2, _1n5, N2); + return num2; + } + function assertPrjPoint(other) { + if (!(other instanceof Point2)) + throw new Error("ProjectivePoint expected"); + } + const toAffineMemo = memoized((p, iz) => { + const { px: x2, py: y2, pz: z } = p; + if (Fp2.eql(z, Fp2.ONE)) + return { x: x2, y: y2 }; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? Fp2.ONE : Fp2.inv(z); + const ax = Fp2.mul(x2, iz); + const ay = Fp2.mul(y2, iz); + const zz = Fp2.mul(z, iz); + if (is0) + return { x: Fp2.ZERO, y: Fp2.ZERO }; + if (!Fp2.eql(zz, Fp2.ONE)) + throw new Error("invZ was invalid"); + return { x: ax, y: ay }; + }); + const assertValidMemo = memoized((p) => { + if (p.is0()) { + if (CURVE.allowInfinityPoint && !Fp2.is0(p.py)) + return; + throw new Error("bad point: ZERO"); + } + const { x: x2, y: y2 } = p.toAffine(); + if (!Fp2.isValid(x2) || !Fp2.isValid(y2)) + throw new Error("bad point: x or y not FE"); + const left = Fp2.sqr(y2); + const right = weierstrassEquation(x2); + if (!Fp2.eql(left, right)) + throw new Error("bad point: equation left != right"); + if (!p.isTorsionFree()) + throw new Error("bad point: not in prime-order subgroup"); + return true; + }); + class Point2 { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp2.isValid(px)) + throw new Error("x required"); + if (py == null || !Fp2.isValid(py)) + throw new Error("y required"); + if (pz == null || !Fp2.isValid(pz)) + throw new Error("z required"); + Object.freeze(this); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x: x2, y: y2 } = p || {}; + if (!p || !Fp2.isValid(x2) || !Fp2.isValid(y2)) + throw new Error("invalid affine point"); + if (p instanceof Point2) + throw new Error("projective point not allowed"); + const is0 = (i) => Fp2.eql(i, Fp2.ZERO); + if (is0(x2) && is0(y2)) + return Point2.ZERO; + return new Point2(x2, y2, Fp2.ONE); + } + get x() { + return this.toAffine().x; } - function encode$1(str) { - const charMap = { - "!": "%21", - "'": "%27", - "(": "%28", - ")": "%29", - "~": "%7E", - "%20": "+", - "%00": "\0" - }; - return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { - return charMap[match]; - }); + get y() { + return this.toAffine().y; } - function AxiosURLSearchParams2(params, options) { - this._pairs = []; - params && toFormData3(params, this, options); + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp2.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); } - var prototype3 = AxiosURLSearchParams2.prototype; - prototype3.append = function append2(name, value) { - this._pairs.push([name, value]); - }; - prototype3.toString = function toString4(encoder5) { - const _encode = encoder5 ? function(value) { - return encoder5.call(this, value, encode$1); - } : encode$1; - return this._pairs.map(function each(pair) { - return _encode(pair[0]) + "=" + _encode(pair[1]); - }, "").join("&"); - }; - function encode6(val) { - return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P2 = Point2.fromAffine(fromBytes2(ensureBytes("pointHex", hex))); + P2.assertValidity(); + return P2; } - function buildURL2(url3, params, options) { - if (!params) { - return url3; - } - const _encode = options && options.encode || encode6; - if (utils$1.isFunction(options)) { - options = { - serialize: options - }; - } - const serializeFn = options && options.serialize; - let serializedParams; - if (serializeFn) { - serializedParams = serializeFn(params, options); - } else { - serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams2(params, options).toString(_encode); - } - if (serializedParams) { - const hashmarkIndex = url3.indexOf("#"); - if (hashmarkIndex !== -1) { - url3 = url3.slice(0, hashmarkIndex); - } - url3 += (url3.indexOf("?") === -1 ? "?" : "&") + serializedParams; - } - return url3; + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); } - var InterceptorManager2 = class { - constructor() { - this.handlers = []; - } - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled, - rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - } - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - * - * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise - */ - eject(id2) { - if (this.handlers[id2]) { - this.handlers[id2] = null; - } - } - /** - * Clear all interceptors from the stack - * - * @returns {void} - */ - clear() { - if (this.handlers) { - this.handlers = []; - } - } - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - * - * @returns {void} - */ - forEach(fn2) { - utils$1.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn2(h); - } - }); - } - }; - var InterceptorManager$1 = InterceptorManager2; - var transitionalDefaults = { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false - }; - var URLSearchParams = url__default["default"].URLSearchParams; - var ALPHA2 = "abcdefghijklmnopqrstuvwxyz"; - var DIGIT2 = "0123456789"; - var ALPHABET2 = { - DIGIT: DIGIT2, - ALPHA: ALPHA2, - ALPHA_DIGIT: ALPHA2 + ALPHA2.toUpperCase() + DIGIT2 - }; - var generateString2 = (size5 = 16, alphabet = ALPHABET2.ALPHA_DIGIT) => { - let str = ""; - const { length } = alphabet; - const randomValues = new Uint32Array(size5); - crypto__default["default"].randomFillSync(randomValues); - for (let i = 0; i < size5; i++) { - str += alphabet[randomValues[i] % length]; - } - return str; - }; - var platform$1 = { - isNode: true, - classes: { - URLSearchParams, - FormData: FormData__default["default"], - Blob: typeof Blob !== "undefined" && Blob || null - }, - ALPHABET: ALPHABET2, - generateString: generateString2, - protocols: ["http", "https", "file", "data"] - }; - var hasBrowserEnv2 = typeof window !== "undefined" && typeof document !== "undefined"; - var _navigator2 = typeof navigator === "object" && navigator || void 0; - var hasStandardBrowserEnv2 = hasBrowserEnv2 && (!_navigator2 || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator2.product) < 0); - var hasStandardBrowserWebWorkerEnv2 = (() => { - return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef - self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; - })(); - var origin2 = hasBrowserEnv2 && window.location.href || "http://localhost"; - var utils = /* @__PURE__ */ Object.freeze({ - __proto__: null, - hasBrowserEnv: hasBrowserEnv2, - hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv2, - hasStandardBrowserEnv: hasStandardBrowserEnv2, - navigator: _navigator2, - origin: origin2 - }); - var platform = { - ...utils, - ...platform$1 - }; - function toURLEncodedForm2(data, options) { - return toFormData3(data, new platform.classes.URLSearchParams(), Object.assign({ - visitor: function(value, key, path, helpers) { - if (platform.isNode && utils$1.isBuffer(value)) { - this.append(key, value.toString("base64")); - return false; - } - return helpers.defaultVisitor.apply(this, arguments); - } - }, options)); + // Multiscalar Multiplication + static msm(points, scalars) { + return pippenger(Point2, Fn2, points, scalars); } - function parsePropPath2(name) { - return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => { - return match[0] === "[]" ? "" : match[1] || match[0]; - }); + // "Private method", don't use it directly + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); } - function arrayToObject2(arr) { - const obj = {}; - const keys = Object.keys(arr); - let i; - const len = keys.length; - let key; - for (i = 0; i < len; i++) { - key = keys[i]; - obj[key] = arr[key]; - } - return obj; + // A point on curve is valid if it conforms to equation. + assertValidity() { + assertValidMemo(this); } - function formDataToJSON2(formData) { - function buildPath(path, value, target, index2) { - let name = path[index2++]; - if (name === "__proto__") return true; - const isNumericKey = Number.isFinite(+name); - const isLast = index2 >= path.length; - name = !name && utils$1.isArray(target) ? target.length : name; - if (isLast) { - if (utils$1.hasOwnProp(target, name)) { - target[name] = [target[name], value]; - } else { - target[name] = value; - } - return !isNumericKey; - } - if (!target[name] || !utils$1.isObject(target[name])) { - target[name] = []; - } - const result = buildPath(path, value, target[name], index2); - if (result && utils$1.isArray(target[name])) { - target[name] = arrayToObject2(target[name]); - } - return !isNumericKey; - } - if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { - const obj = {}; - utils$1.forEachEntry(formData, (name, value) => { - buildPath(parsePropPath2(name), value, obj, 0); - }); - return obj; - } - return null; + hasEvenY() { + const { y: y2 } = this.toAffine(); + if (Fp2.isOdd) + return !Fp2.isOdd(y2); + throw new Error("Field doesn't support isOdd"); } - function stringifySafely2(rawValue, parser, encoder5) { - if (utils$1.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$1.trim(rawValue); - } catch (e) { - if (e.name !== "SyntaxError") { - throw e; - } - } - } - return (encoder5 || JSON.stringify)(rawValue); + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); + const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); + return U1 && U2; } - var defaults2 = { - transitional: transitionalDefaults, - adapter: ["xhr", "http", "fetch"], - transformRequest: [function transformRequest2(data, headers) { - const contentType = headers.getContentType() || ""; - const hasJSONContentType = contentType.indexOf("application/json") > -1; - const isObjectPayload = utils$1.isObject(data); - if (isObjectPayload && utils$1.isHTMLForm(data)) { - data = new FormData(data); - } - const isFormData3 = utils$1.isFormData(data); - if (isFormData3) { - return hasJSONContentType ? JSON.stringify(formDataToJSON2(data)) : data; - } - if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) { - return data; - } - if (utils$1.isArrayBufferView(data)) { - return data.buffer; - } - if (utils$1.isURLSearchParams(data)) { - headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); - return data.toString(); - } - let isFileList3; - if (isObjectPayload) { - if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { - return toURLEncodedForm2(data, this.formSerializer).toString(); - } - if ((isFileList3 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { - const _FormData = this.env && this.env.FormData; - return toFormData3( - isFileList3 ? { "files[]": data } : data, - _FormData && new _FormData(), - this.formSerializer - ); - } - } - if (isObjectPayload || hasJSONContentType) { - headers.setContentType("application/json", false); - return stringifySafely2(data); - } - return data; - }], - transformResponse: [function transformResponse2(data) { - const transitional2 = this.transitional || defaults2.transitional; - const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing; - const JSONRequested = this.responseType === "json"; - if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) { - return data; - } - if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { - const silentJSONParsing = transitional2 && transitional2.silentJSONParsing; - const strictJSONParsing = !silentJSONParsing && JSONRequested; - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === "SyntaxError") { - throw AxiosError3.from(e, AxiosError3.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e; - } - } - } - return data; - }], - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - xsrfCookieName: "XSRF-TOKEN", - xsrfHeaderName: "X-XSRF-TOKEN", - maxContentLength: -1, - maxBodyLength: -1, - env: { - FormData: platform.classes.FormData, - Blob: platform.classes.Blob - }, - validateStatus: function validateStatus2(status) { - return status >= 200 && status < 300; - }, - headers: { - common: { - "Accept": "application/json, text/plain, */*", - "Content-Type": void 0 - } - } - }; - utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { - defaults2.headers[method] = {}; - }); - var defaults$1 = defaults2; - var ignoreDuplicateOf2 = utils$1.toObjectSet([ - "age", - "authorization", - "content-length", - "content-type", - "etag", - "expires", - "from", - "host", - "if-modified-since", - "if-unmodified-since", - "last-modified", - "location", - "max-forwards", - "proxy-authorization", - "referer", - "retry-after", - "user-agent" - ]); - var parseHeaders = (rawHeaders) => { - const parsed = {}; - let key; - let val; - let i; - rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { - i = line.indexOf(":"); - key = line.substring(0, i).trim().toLowerCase(); - val = line.substring(i + 1).trim(); - if (!key || parsed[key] && ignoreDuplicateOf2[key]) { - return; - } - if (key === "set-cookie") { - if (parsed[key]) { - parsed[key].push(val); - } else { - parsed[key] = [val]; - } - } else { - parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; - } - }); - return parsed; - }; - var $internals2 = Symbol("internals"); - function normalizeHeader2(header) { - return header && String(header).trim().toLowerCase(); + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point2(this.px, Fp2.neg(this.py), this.pz); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b: b2 } = CURVE; + const b3 = Fp2.mul(b2, _3n2); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + let t0 = Fp2.mul(X1, X1); + let t1 = Fp2.mul(Y1, Y1); + let t2 = Fp2.mul(Z1, Z1); + let t3 = Fp2.mul(X1, Y1); + t3 = Fp2.add(t3, t3); + Z3 = Fp2.mul(X1, Z1); + Z3 = Fp2.add(Z3, Z3); + X3 = Fp2.mul(a, Z3); + Y3 = Fp2.mul(b3, t2); + Y3 = Fp2.add(X3, Y3); + X3 = Fp2.sub(t1, Y3); + Y3 = Fp2.add(t1, Y3); + Y3 = Fp2.mul(X3, Y3); + X3 = Fp2.mul(t3, X3); + Z3 = Fp2.mul(b3, Z3); + t2 = Fp2.mul(a, t2); + t3 = Fp2.sub(t0, t2); + t3 = Fp2.mul(a, t3); + t3 = Fp2.add(t3, Z3); + Z3 = Fp2.add(t0, t0); + t0 = Fp2.add(Z3, t0); + t0 = Fp2.add(t0, t2); + t0 = Fp2.mul(t0, t3); + Y3 = Fp2.add(Y3, t0); + t2 = Fp2.mul(Y1, Z1); + t2 = Fp2.add(t2, t2); + t0 = Fp2.mul(t2, t3); + X3 = Fp2.sub(X3, t0); + Z3 = Fp2.mul(t2, t1); + Z3 = Fp2.add(Z3, Z3); + Z3 = Fp2.add(Z3, Z3); + return new Point2(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + const a = CURVE.a; + const b3 = Fp2.mul(CURVE.b, _3n2); + let t0 = Fp2.mul(X1, X2); + let t1 = Fp2.mul(Y1, Y2); + let t2 = Fp2.mul(Z1, Z2); + let t3 = Fp2.add(X1, Y1); + let t4 = Fp2.add(X2, Y2); + t3 = Fp2.mul(t3, t4); + t4 = Fp2.add(t0, t1); + t3 = Fp2.sub(t3, t4); + t4 = Fp2.add(X1, Z1); + let t5 = Fp2.add(X2, Z2); + t4 = Fp2.mul(t4, t5); + t5 = Fp2.add(t0, t2); + t4 = Fp2.sub(t4, t5); + t5 = Fp2.add(Y1, Z1); + X3 = Fp2.add(Y2, Z2); + t5 = Fp2.mul(t5, X3); + X3 = Fp2.add(t1, t2); + t5 = Fp2.sub(t5, X3); + Z3 = Fp2.mul(a, t4); + X3 = Fp2.mul(b3, t2); + Z3 = Fp2.add(X3, Z3); + X3 = Fp2.sub(t1, Z3); + Z3 = Fp2.add(t1, Z3); + Y3 = Fp2.mul(X3, Z3); + t1 = Fp2.add(t0, t0); + t1 = Fp2.add(t1, t0); + t2 = Fp2.mul(a, t2); + t4 = Fp2.mul(b3, t4); + t1 = Fp2.add(t1, t2); + t2 = Fp2.sub(t0, t2); + t2 = Fp2.mul(a, t2); + t4 = Fp2.add(t4, t2); + t0 = Fp2.mul(t1, t4); + Y3 = Fp2.add(Y3, t0); + t0 = Fp2.mul(t5, t4); + X3 = Fp2.mul(t3, X3); + X3 = Fp2.sub(X3, t0); + t0 = Fp2.mul(t3, t1); + Z3 = Fp2.mul(t5, Z3); + Z3 = Fp2.add(Z3, t0); + return new Point2(X3, Y3, Z3); } - function normalizeValue2(value) { - if (value === false || value == null) { - return value; - } - return utils$1.isArray(value) ? value.map(normalizeValue2) : String(value); + subtract(other) { + return this.add(other.negate()); } - function parseTokens2(str) { - const tokens = /* @__PURE__ */ Object.create(null); - const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; - let match; - while (match = tokensRE.exec(str)) { - tokens[match[1]] = match[2]; - } - return tokens; + is0() { + return this.equals(Point2.ZERO); } - var isValidHeaderName2 = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); - function matchHeaderValue2(context, value, header, filter2, isHeaderNameFilter) { - if (utils$1.isFunction(filter2)) { - return filter2.call(this, value, header); - } - if (isHeaderNameFilter) { - value = header; - } - if (!utils$1.isString(value)) return; - if (utils$1.isString(filter2)) { - return value.indexOf(filter2) !== -1; + wNAF(n) { + return wnaf.wNAFCached(this, n, Point2.normalizeZ); + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(sc2) { + const { endo, n: N2 } = CURVE; + aInRange("scalar", sc2, _0n5, N2); + const I2 = Point2.ZERO; + if (sc2 === _0n5) + return I2; + if (this.is0() || sc2 === _1n5) + return this; + if (!endo || wnaf.hasPrecomputes(this)) + return wnaf.wNAFCachedUnsafe(this, sc2, Point2.normalizeZ); + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc2); + let k1p = I2; + let k2p = I2; + let d = this; + while (k1 > _0n5 || k2 > _0n5) { + if (k1 & _1n5) + k1p = k1p.add(d); + if (k2 & _1n5) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n5; + k2 >>= _1n5; } - if (utils$1.isRegExp(filter2)) { - return filter2.test(value); + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + const { endo, n: N2 } = CURVE; + aInRange("scalar", scalar, _1n5, N2); + let point, fake; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; } + return Point2.normalizeZ([point, fake])[0]; } - function formatHeader2(header) { - return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str) => { - return char.toUpperCase() + str; - }); + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b2) { + const G2 = Point2.BASE; + const mul = (P2, a2) => a2 === _0n5 || a2 === _1n5 || !P2.equals(G2) ? P2.multiplyUnsafe(a2) : P2.multiply(a2); + const sum = mul(this, a).add(mul(Q, b2)); + return sum.is0() ? void 0 : sum; } - function buildAccessors2(obj, header) { - const accessorName = utils$1.toCamelCase(" " + header); - ["get", "set", "has"].forEach((methodName) => { - Object.defineProperty(obj, methodName + accessorName, { - value: function(arg1, arg2, arg3) { - return this[methodName].call(this, header, arg1, arg2, arg3); - }, - configurable: true - }); - }); + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + return toAffineMemo(this, iz); } - var AxiosHeaders3 = class { - constructor(headers) { - headers && this.set(headers); - } - set(header, valueOrRewrite, rewrite) { - const self2 = this; - function setHeader(_value, _header, _rewrite) { - const lHeader = normalizeHeader2(_header); - if (!lHeader) { - throw new Error("header name must be a non-empty string"); - } - const key = utils$1.findKey(self2, lHeader); - if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { - self2[key || _header] = normalizeValue2(_value); - } - } - const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); - if (utils$1.isPlainObject(header) || header instanceof this.constructor) { - setHeaders(header, valueOrRewrite); - } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName2(header)) { - setHeaders(parseHeaders(header), valueOrRewrite); - } else if (utils$1.isObject(header) && utils$1.isIterable(header)) { - let obj = {}, dest, key; - for (const entry of header) { - if (!utils$1.isArray(entry)) { - throw TypeError("Object iterator must return a key-value pair"); - } - obj[key = entry[0]] = (dest = obj[key]) ? utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1]; - } - setHeaders(obj, valueOrRewrite); - } else { - header != null && setHeader(valueOrRewrite, header, rewrite); - } - return this; - } - get(header, parser) { - header = normalizeHeader2(header); - if (header) { - const key = utils$1.findKey(this, header); - if (key) { - const value = this[key]; - if (!parser) { - return value; - } - if (parser === true) { - return parseTokens2(value); - } - if (utils$1.isFunction(parser)) { - return parser.call(this, value, key); - } - if (utils$1.isRegExp(parser)) { - return parser.exec(value); - } - throw new TypeError("parser must be boolean|regexp|function"); - } - } - } - has(header, matcher) { - header = normalizeHeader2(header); - if (header) { - const key = utils$1.findKey(this, header); - return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue2(this, this[key], key, matcher))); - } - return false; - } - delete(header, matcher) { - const self2 = this; - let deleted = false; - function deleteHeader(_header) { - _header = normalizeHeader2(_header); - if (_header) { - const key = utils$1.findKey(self2, _header); - if (key && (!matcher || matchHeaderValue2(self2, self2[key], key, matcher))) { - delete self2[key]; - deleted = true; - } - } - } - if (utils$1.isArray(header)) { - header.forEach(deleteHeader); - } else { - deleteHeader(header); - } - return deleted; - } - clear(matcher) { - const keys = Object.keys(this); - let i = keys.length; - let deleted = false; - while (i--) { - const key = keys[i]; - if (!matcher || matchHeaderValue2(this, this[key], key, matcher, true)) { - delete this[key]; - deleted = true; - } - } - return deleted; - } - normalize(format) { - const self2 = this; - const headers = {}; - utils$1.forEach(this, (value, header) => { - const key = utils$1.findKey(headers, header); - if (key) { - self2[key] = normalizeValue2(value); - delete self2[header]; - return; - } - const normalized = format ? formatHeader2(header) : String(header).trim(); - if (normalized !== header) { - delete self2[header]; - } - self2[normalized] = normalizeValue2(value); - headers[normalized] = true; - }); + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n5) + return true; + if (isTorsionFree) + return isTorsionFree(Point2, this); + throw new Error("isTorsionFree() has not been declared for the elliptic curve"); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n5) return this; + if (clearCofactor) + return clearCofactor(Point2, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + abool("isCompressed", isCompressed); + this.assertValidity(); + return toBytes4(Point2, this, isCompressed); + } + toHex(isCompressed = true) { + abool("isCompressed", isCompressed); + return bytesToHex2(this.toRawBytes(isCompressed)); + } + } + Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE); + Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + return { + CURVE, + ProjectivePoint: Point2, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder + }; +} +function validateOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: "hash", + hmac: "function", + randomBytes: "function" + }, { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean" + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp: Fp2, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp2.BYTES + 1; + const uncompressedLen = 2 * Fp2.BYTES + 1; + function modN2(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ + ...CURVE, + toBytes(_c2, point, isCompressed) { + const a = point.toAffine(); + const x2 = Fp2.toBytes(a.x); + const cat = concatBytes3; + abool("isCompressed", isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x2); + } else { + return cat(Uint8Array.from([4]), x2, Fp2.toBytes(a.y)); } - concat(...targets) { - return this.constructor.concat(this, ...targets); - } - toJSON(asStrings) { - const obj = /* @__PURE__ */ Object.create(null); - utils$1.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value); - }); - return obj; - } - [Symbol.iterator]() { - return Object.entries(this.toJSON())[Symbol.iterator](); - } - toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); - } - getSetCookie() { - return this.get("set-cookie") || []; - } - get [Symbol.toStringTag]() { - return "AxiosHeaders"; - } - static from(thing) { - return thing instanceof this ? thing : new this(thing); - } - static concat(first, ...targets) { - const computed = new this(first); - targets.forEach((target) => computed.set(target)); - return computed; - } - static accessor(header) { - const internals = this[$internals2] = this[$internals2] = { - accessors: {} - }; - const accessors = internals.accessors; - const prototype4 = this.prototype; - function defineAccessor(_header) { - const lHeader = normalizeHeader2(_header); - if (!accessors[lHeader]) { - buildAccessors2(prototype4, _header); - accessors[lHeader] = true; - } + }, + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + if (len === compressedLen && (head === 2 || head === 3)) { + const x2 = bytesToNumberBE(tail); + if (!inRange(x2, _1n5, Fp2.ORDER)) + throw new Error("Point is not on curve"); + const y2 = weierstrassEquation(x2); + let y3; + try { + y3 = Fp2.sqrt(y2); + } catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : ""; + throw new Error("Point is not on curve" + suffix); } - utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); - return this; + const isYOdd = (y3 & _1n5) === _1n5; + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y3 = Fp2.neg(y3); + return { x: x2, y: y3 }; + } else if (len === uncompressedLen && head === 4) { + const x2 = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y2 = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x: x2, y: y2 }; + } else { + const cl2 = compressedLen; + const ul2 = uncompressedLen; + throw new Error("invalid Point, expected length of " + cl2 + ", or uncompressed " + ul2 + ", got " + len); } - }; - AxiosHeaders3.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); - utils$1.reduceDescriptors(AxiosHeaders3.prototype, ({ value }, key) => { - let mapped = key[0].toUpperCase() + key.slice(1); - return { - get: () => value, - set(headerValue) { - this[mapped] = headerValue; - } - }; - }); - utils$1.freezeMethods(AxiosHeaders3); - var AxiosHeaders$1 = AxiosHeaders3; - function transformData2(fns, response) { - const config3 = this || defaults$1; - const context = response || config3; - const headers = AxiosHeaders$1.from(context.headers); - let data = context.data; - utils$1.forEach(fns, function transform(fn2) { - data = fn2.call(config3, data, headers.normalize(), response ? response.status : void 0); - }); - headers.normalize(); - return data; } - function isCancel3(value) { - return !!(value && value.__CANCEL__); + }); + const numToNByteStr = (num2) => bytesToHex2(numberToBytesBE(num2, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n5; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN2(-s) : s; + } + const slcNum = (b2, from5, to2) => bytesToNumberBE(b2.slice(from5, to2)); + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); } - function CanceledError3(message, config3, request) { - AxiosError3.call(this, message == null ? "canceled" : message, AxiosError3.ERR_CANCELED, config3, request); - this.name = "CanceledError"; + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes("compactSignature", hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); } - utils$1.inherits(CanceledError3, AxiosError3, { - __CANCEL__: true - }); - function settle2(resolve, reject, response) { - const validateStatus2 = response.config.validateStatus; - if (!response.status || !validateStatus2 || validateStatus2(response.status)) { - resolve(response); - } else { - reject(new AxiosError3( - "Request failed with status code " + response.status, - [AxiosError3.ERR_BAD_REQUEST, AxiosError3.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); - } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes("DER", hex)); + return new Signature(r, s); } - function isAbsoluteURL2(url3) { - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url3); + assertValidity() { + aInRange("r", this.r, _1n5, CURVE_ORDER); + aInRange("s", this.s, _1n5, CURVE_ORDER); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes("msgHash", msgHash)); + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error("recovery id invalid"); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp2.ORDER) + throw new Error("recovery id 2 or 3 invalid"); + const prefix = (rec & 1) === 0 ? "02" : "03"; + const R2 = Point2.fromHex(prefix + numToNByteStr(radj)); + const ir2 = invN(radj); + const u1 = modN2(-h * ir2); + const u2 = modN2(s * ir2); + const Q = Point2.BASE.multiplyAndAddUnsafe(R2, u1, u2); + if (!Q) + throw new Error("point at infinify"); + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return hexToBytes2(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes2(this.toCompactHex()); } - function combineURLs2(baseURL, relativeURL) { - return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); } - function buildFullPath2(baseURL, requestedURL, allowAbsoluteUrls) { - let isRelativeUrl = !isAbsoluteURL2(requestedURL); - if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) { - return combineURLs2(baseURL, requestedURL); + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; } - return requestedURL; + }, + normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point2.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; } - var VERSION3 = "1.9.0"; - function parseProtocol2(url3) { - const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url3); - return match && match[1] || ""; + }; + function getPublicKey(privateKey, isCompressed = true) { + return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + function isProbPub(item) { + const arr = isBytes2(item); + const str = typeof item === "string"; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point2) + return true; + return false; + } + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error("first arg must be private key"); + if (!isProbPub(publicB)) + throw new Error("second arg must be public key"); + const b2 = Point2.fromHex(publicB); + return b2.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + const bits2int = CURVE.bits2int || function(bytes) { + if (bytes.length > 8192) + throw new Error("input is too large"); + const num2 = bytesToNumberBE(bytes); + const delta = bytes.length * 8 - CURVE.nBitLength; + return delta > 0 ? num2 >> BigInt(delta) : num2; + }; + const bits2int_modN = CURVE.bits2int_modN || function(bytes) { + return modN2(bits2int(bytes)); + }; + const ORDER_MASK = bitMask(CURVE.nBitLength); + function int2octets(num2) { + aInRange("num < 2^" + CURVE.nBitLength, num2, _0n5, ORDER_MASK); + return numberToBytesBE(num2, CURVE.nByteLength); + } + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (["recovered", "canonical"].some((k2) => k2 in opts)) + throw new Error("sign() legacy options not supported"); + const { hash: hash2, randomBytes: randomBytes2 } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; + if (lowS == null) + lowS = true; + msgHash = ensureBytes("msgHash", msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); + const seedArgs = [int2octets(d), int2octets(h1int)]; + if (ent != null && ent !== false) { + const e = ent === true ? randomBytes2(Fp2.BYTES) : ent; + seedArgs.push(ensureBytes("extraEntropy", e)); } - var DATA_URL_PATTERN2 = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; - function fromDataURI2(uri, asBlob, options) { - const _Blob = options && options.Blob || platform.classes.Blob; - const protocol = parseProtocol2(uri); - if (asBlob === void 0 && _Blob) { - asBlob = true; - } - if (protocol === "data") { - uri = protocol.length ? uri.slice(protocol.length + 1) : uri; - const match = DATA_URL_PATTERN2.exec(uri); - if (!match) { - throw new AxiosError3("Invalid URL", AxiosError3.ERR_INVALID_URL); - } - const mime = match[1]; - const isBase64 = match[2]; - const body = match[3]; - const buffer2 = Buffer.from(decodeURIComponent(body), isBase64 ? "base64" : "utf8"); - if (asBlob) { - if (!_Blob) { - throw new AxiosError3("Blob is not supported", AxiosError3.ERR_NOT_SUPPORT); - } - return new _Blob([buffer2], { type: mime }); - } - return buffer2; + const seed = concatBytes3(...seedArgs); + const m2 = h1int; + function k2sig(kBytes) { + const k2 = bits2int(kBytes); + if (!isWithinCurveOrder(k2)) + return; + const ik = invN(k2); + const q2 = Point2.BASE.multiply(k2).toAffine(); + const r = modN2(q2.x); + if (r === _0n5) + return; + const s = modN2(ik * modN2(m2 + r * d)); + if (s === _0n5) + return; + let recovery = (q2.x === r ? 0 : 2) | Number(q2.y & _1n5); + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); + recovery ^= 1; } - throw new AxiosError3("Unsupported protocol " + protocol, AxiosError3.ERR_NOT_SUPPORT); + return new Signature(r, normS, recovery); } - var kInternals2 = Symbol("internals"); - var AxiosTransformStream2 = class extends stream__default["default"].Transform { - constructor(options) { - options = utils$1.toFlatObject(options, { - maxRate: 0, - chunkSize: 64 * 1024, - minChunkSize: 100, - timeWindow: 500, - ticksRate: 2, - samplesCount: 15 - }, null, (prop, source) => { - return !utils$1.isUndefined(source[prop]); - }); - super({ - readableHighWaterMark: options.chunkSize - }); - const internals = this[kInternals2] = { - timeWindow: options.timeWindow, - chunkSize: options.chunkSize, - maxRate: options.maxRate, - minChunkSize: options.minChunkSize, - bytesSeen: 0, - isCaptured: false, - notifiedBytesLoaded: 0, - ts: Date.now(), - bytes: 0, - onReadCallback: null - }; - this.on("newListener", (event) => { - if (event === "progress") { - if (!internals.isCaptured) { - internals.isCaptured = true; - } - } - }); - } - _read(size5) { - const internals = this[kInternals2]; - if (internals.onReadCallback) { - internals.onReadCallback(); + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + function sign2(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); + } + Point2.BASE._setWindowSize(8); + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes("msgHash", msgHash); + publicKey = ensureBytes("publicKey", publicKey); + const { lowS, prehash, format } = opts; + validateSigVerOpts(opts); + if ("strict" in opts) + throw new Error("options.strict was renamed to lowS"); + if (format !== void 0 && format !== "compact" && format !== "der") + throw new Error("format must be compact or der"); + const isHex2 = typeof sg === "string" || isBytes2(sg); + const isObj = !isHex2 && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint"; + if (!isHex2 && !isObj) + throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance"); + let _sig = void 0; + let P2; + try { + if (isObj) + _sig = new Signature(sg.r, sg.s); + if (isHex2) { + try { + if (format !== "compact") + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; } - return super._read(size5); - } - _transform(chunk, encoding, callback) { - const internals = this[kInternals2]; - const maxRate = internals.maxRate; - const readableHighWaterMark = this.readableHighWaterMark; - const timeWindow = internals.timeWindow; - const divider = 1e3 / timeWindow; - const bytesThreshold = maxRate / divider; - const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; - const pushChunk = (_chunk, _callback) => { - const bytes = Buffer.byteLength(_chunk); - internals.bytesSeen += bytes; - internals.bytes += bytes; - internals.isCaptured && this.emit("progress", internals.bytesSeen); - if (this.push(_chunk)) { - process.nextTick(_callback); - } else { - internals.onReadCallback = () => { - internals.onReadCallback = null; - process.nextTick(_callback); - }; - } - }; - const transformChunk = (_chunk, _callback) => { - const chunkSize = Buffer.byteLength(_chunk); - let chunkRemainder = null; - let maxChunkSize = readableHighWaterMark; - let bytesLeft; - let passed = 0; - if (maxRate) { - const now = Date.now(); - if (!internals.ts || (passed = now - internals.ts) >= timeWindow) { - internals.ts = now; - bytesLeft = bytesThreshold - internals.bytes; - internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; - passed = 0; - } - bytesLeft = bytesThreshold - internals.bytes; - } - if (maxRate) { - if (bytesLeft <= 0) { - return setTimeout(() => { - _callback(null, _chunk); - }, timeWindow - passed); - } - if (bytesLeft < maxChunkSize) { - maxChunkSize = bytesLeft; - } - } - if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) { - chunkRemainder = _chunk.subarray(maxChunkSize); - _chunk = _chunk.subarray(0, maxChunkSize); - } - pushChunk(_chunk, chunkRemainder ? () => { - process.nextTick(_callback, null, chunkRemainder); - } : _callback); - }; - transformChunk(chunk, function transformNextChunk(err, _chunk) { - if (err) { - return callback(err); - } - if (_chunk) { - transformChunk(_chunk, transformNextChunk); - } else { - callback(null); - } - }); + if (!_sig && format !== "der") + _sig = Signature.fromCompact(sg); } + P2 = Point2.fromHex(publicKey); + } catch (error) { + return false; + } + if (!_sig) + return false; + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); + const is2 = invN(s); + const u1 = modN2(h * is2); + const u2 = modN2(r * is2); + const R2 = Point2.BASE.multiplyAndAddUnsafe(P2, u1, u2)?.toAffine(); + if (!R2) + return false; + const v = modN2(R2.x); + return v === r; + } + return { + CURVE, + getPublicKey, + getSharedSecret, + sign: sign2, + verify, + ProjectivePoint: Point2, + Signature, + utils + }; +} +function SWUFpSqrtRatio(Fp2, Z2) { + const q2 = Fp2.ORDER; + let l = _0n5; + for (let o = q2 - _1n5; o % _2n4 === _0n5; o /= _2n4) + l += _1n5; + const c1 = l; + const _2n_pow_c1_1 = _2n4 << c1 - _1n5 - _1n5; + const _2n_pow_c1 = _2n_pow_c1_1 * _2n4; + const c2 = (q2 - _1n5) / _2n_pow_c1; + const c3 = (c2 - _1n5) / _2n4; + const c4 = _2n_pow_c1 - _1n5; + const c5 = _2n_pow_c1_1; + const c6 = Fp2.pow(Z2, c2); + const c7 = Fp2.pow(Z2, (c2 + _1n5) / _2n4); + let sqrtRatio = (u, v) => { + let tv1 = c6; + let tv2 = Fp2.pow(v, c4); + let tv3 = Fp2.sqr(tv2); + tv3 = Fp2.mul(tv3, v); + let tv5 = Fp2.mul(u, tv3); + tv5 = Fp2.pow(tv5, c3); + tv5 = Fp2.mul(tv5, tv2); + tv2 = Fp2.mul(tv5, v); + tv3 = Fp2.mul(tv5, u); + let tv4 = Fp2.mul(tv3, tv2); + tv5 = Fp2.pow(tv4, c5); + let isQR = Fp2.eql(tv5, Fp2.ONE); + tv2 = Fp2.mul(tv3, c7); + tv5 = Fp2.mul(tv4, tv1); + tv3 = Fp2.cmov(tv2, tv3, isQR); + tv4 = Fp2.cmov(tv5, tv4, isQR); + for (let i = c1; i > _1n5; i--) { + let tv52 = i - _2n4; + tv52 = _2n4 << tv52 - _1n5; + let tvv5 = Fp2.pow(tv4, tv52); + const e1 = Fp2.eql(tvv5, Fp2.ONE); + tv2 = Fp2.mul(tv3, tv1); + tv1 = Fp2.mul(tv1, tv1); + tvv5 = Fp2.mul(tv4, tv1); + tv3 = Fp2.cmov(tv2, tv3, e1); + tv4 = Fp2.cmov(tvv5, tv4, e1); + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp2.ORDER % _4n2 === _3n2) { + const c12 = (Fp2.ORDER - _3n2) / _4n2; + const c22 = Fp2.sqrt(Fp2.neg(Z2)); + sqrtRatio = (u, v) => { + let tv1 = Fp2.sqr(v); + const tv2 = Fp2.mul(u, v); + tv1 = Fp2.mul(tv1, tv2); + let y1 = Fp2.pow(tv1, c12); + y1 = Fp2.mul(y1, tv2); + const y2 = Fp2.mul(y1, c22); + const tv3 = Fp2.mul(Fp2.sqr(y1), v); + const isQR = Fp2.eql(tv3, u); + let y3 = Fp2.cmov(y2, y1, isQR); + return { isValid: isQR, value: y3 }; }; - var AxiosTransformStream$1 = AxiosTransformStream2; - var { asyncIterator: asyncIterator2 } = Symbol; - var readBlob2 = async function* (blob) { - if (blob.stream) { - yield* blob.stream(); - } else if (blob.arrayBuffer) { - yield await blob.arrayBuffer(); - } else if (blob[asyncIterator2]) { - yield* blob[asyncIterator2](); - } else { - yield blob; + } + return sqrtRatio; +} +function mapToCurveSimpleSWU(Fp2, opts) { + validateField(Fp2); + if (!Fp2.isValid(opts.A) || !Fp2.isValid(opts.B) || !Fp2.isValid(opts.Z)) + throw new Error("mapToCurveSimpleSWU: invalid opts"); + const sqrtRatio = SWUFpSqrtRatio(Fp2, opts.Z); + if (!Fp2.isOdd) + throw new Error("Fp.isOdd is not implemented!"); + return (u) => { + let tv1, tv2, tv3, tv4, tv5, tv6, x2, y2; + tv1 = Fp2.sqr(u); + tv1 = Fp2.mul(tv1, opts.Z); + tv2 = Fp2.sqr(tv1); + tv2 = Fp2.add(tv2, tv1); + tv3 = Fp2.add(tv2, Fp2.ONE); + tv3 = Fp2.mul(tv3, opts.B); + tv4 = Fp2.cmov(opts.Z, Fp2.neg(tv2), !Fp2.eql(tv2, Fp2.ZERO)); + tv4 = Fp2.mul(tv4, opts.A); + tv2 = Fp2.sqr(tv3); + tv6 = Fp2.sqr(tv4); + tv5 = Fp2.mul(tv6, opts.A); + tv2 = Fp2.add(tv2, tv5); + tv2 = Fp2.mul(tv2, tv3); + tv6 = Fp2.mul(tv6, tv4); + tv5 = Fp2.mul(tv6, opts.B); + tv2 = Fp2.add(tv2, tv5); + x2 = Fp2.mul(tv1, tv3); + const { isValid, value } = sqrtRatio(tv2, tv6); + y2 = Fp2.mul(tv1, u); + y2 = Fp2.mul(y2, value); + x2 = Fp2.cmov(x2, tv3, isValid); + y2 = Fp2.cmov(y2, value, isValid); + const e1 = Fp2.isOdd(u) === Fp2.isOdd(y2); + y2 = Fp2.cmov(Fp2.neg(y2), y2, e1); + x2 = Fp2.div(x2, tv4); + return { x: x2, y: y2 }; + }; +} +var b2n, h2b, DERErr, DER, _0n5, _1n5, _2n4, _3n2, _4n2; +var init_weierstrass = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/abstract/weierstrass.js"() { + init_curve(); + init_modular(); + init_utils4(); + init_utils4(); + ({ bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports); + DERErr = class extends Error { + constructor(m2 = "") { + super(m2); } }; - var readBlob$1 = readBlob2; - var BOUNDARY_ALPHABET2 = platform.ALPHABET.ALPHA_DIGIT + "-_"; - var textEncoder2 = typeof TextEncoder === "function" ? new TextEncoder() : new util__default["default"].TextEncoder(); - var CRLF2 = "\r\n"; - var CRLF_BYTES2 = textEncoder2.encode(CRLF2); - var CRLF_BYTES_COUNT2 = 2; - var FormDataPart2 = class { - constructor(name, value) { - const { escapeName } = this.constructor; - const isStringValue = utils$1.isString(value); - let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF2}`; - if (isStringValue) { - value = textEncoder2.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF2)); - } else { - headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF2}`; + DER = { + // asn.1 DER encoding utils + Err: DERErr, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + if (tag < 0 || tag > 256) + throw new E("tlv.encode: wrong tag"); + if (data.length & 1) + throw new E("tlv.encode: unpadded data"); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if (len.length / 2 & 128) + throw new E("tlv.encode: long form length too big"); + const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; + const t = numberToHexUnpadded(tag); + return t + lenLen + len + data; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER; + let pos = 0; + if (tag < 0 || tag > 256) + throw new E("tlv.encode: wrong tag"); + if (data.length < 2 || data[pos++] !== tag) + throw new E("tlv.decode: wrong tlv"); + const first = data[pos++]; + const isLong = !!(first & 128); + let length = 0; + if (!isLong) + length = first; + else { + const lenLen = first & 127; + if (!lenLen) + throw new E("tlv.decode(long): indefinite length not supported"); + if (lenLen > 4) + throw new E("tlv.decode(long): byte length is too big"); + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E("tlv.decode: length bytes not complete"); + if (lengthBytes[0] === 0) + throw new E("tlv.decode(long): zero leftmost byte"); + for (const b2 of lengthBytes) + length = length << 8 | b2; + pos += lenLen; + if (length < 128) + throw new E("tlv.decode(long): not minimal encoding"); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E("tlv.decode: wrong value length"); + return { v, l: data.subarray(pos + length) }; } - this.headers = textEncoder2.encode(headers + CRLF2); - this.contentLength = isStringValue ? value.byteLength : value.size; - this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT2; - this.name = name; - this.value = value; - } - async *encode() { - yield this.headers; - const { value } = this; - if (utils$1.isTypedArray(value)) { - yield value; - } else { - yield* readBlob$1(value); + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num2) { + const { Err: E } = DER; + if (num2 < _0n5) + throw new E("integer: negative integers are not allowed"); + let hex = numberToHexUnpadded(num2); + if (Number.parseInt(hex[0], 16) & 8) + hex = "00" + hex; + if (hex.length & 1) + throw new E("unexpected DER parsing assertion: unpadded hex"); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data[0] & 128) + throw new E("invalid signature integer: negative"); + if (data[0] === 0 && !(data[1] & 128)) + throw new E("invalid signature integer: unnecessary leading zero"); + return b2n(data); } - yield CRLF_BYTES2; - } - static escapeName(name) { - return String(name).replace(/[\r\n"]/g, (match) => ({ - "\r": "%0D", - "\n": "%0A", - '"': "%22" - })[match]); + }, + toSig(hex) { + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = typeof hex === "string" ? h2b(hex) : hex; + abytes2(data); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); + if (seqLeftBytes.length) + throw new E("invalid signature: left bytes after parsing"); + const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); + if (sLeftBytes.length) + throw new E("invalid signature: left bytes after parsing"); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const rs2 = tlv.encode(2, int.encode(sig.r)); + const ss = tlv.encode(2, int.encode(sig.s)); + const seq = rs2 + ss; + return tlv.encode(48, seq); } }; - var formDataToStream2 = (form, headersHandler, options) => { - const { - tag = "form-data-boundary", - size: size5 = 25, - boundary = tag + "-" + platform.generateString(size5, BOUNDARY_ALPHABET2) - } = options || {}; - if (!utils$1.isFormData(form)) { - throw TypeError("FormData instance required"); + _0n5 = BigInt(0); + _1n5 = BigInt(1); + _2n4 = BigInt(2); + _3n2 = BigInt(3); + _4n2 = BigInt(4); + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/_shortw_utils.js +function getHash(hash2) { + return { + hash: hash2, + hmac: (key, ...msgs) => hmac(hash2, key, concatBytes(...msgs)), + randomBytes + }; +} +function createCurve(curveDef, defHash) { + const create = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) }); + return { ...create(defHash), create }; +} +var init_shortw_utils = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/_shortw_utils.js"() { + init_hmac(); + init_utils2(); + init_weierstrass(); + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/abstract/hash-to-curve.js +function i2osp(value, length) { + anum(value); + anum(length); + if (value < 0 || value >= 1 << 8 * length) + throw new Error("invalid I2OSP input: " + value); + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 255; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b2) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b2[i]; + } + return arr; +} +function anum(item) { + if (!Number.isSafeInteger(item)) + throw new Error("number expected"); +} +function expand_message_xmd(msg, DST, lenInBytes, H2) { + abytes2(msg); + abytes2(DST); + anum(lenInBytes); + if (DST.length > 255) + DST = H2(concatBytes3(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H2; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (lenInBytes > 65535 || ell > 255) + throw new Error("expand_message_xmd: invalid lenInBytes"); + const DST_prime = concatBytes3(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); + const b2 = new Array(ell); + const b_0 = H2(concatBytes3(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b2[0] = H2(concatBytes3(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b2[i - 1]), i2osp(i + 1, 1), DST_prime]; + b2[i] = H2(concatBytes3(...args)); + } + const pseudo_random_bytes = concatBytes3(...b2); + return pseudo_random_bytes.slice(0, lenInBytes); +} +function expand_message_xof(msg, DST, lenInBytes, k2, H2) { + abytes2(msg); + abytes2(DST); + anum(lenInBytes); + if (DST.length > 255) { + const dkLen = Math.ceil(2 * k2 / 8); + DST = H2.create({ dkLen }).update(utf8ToBytes2("H2C-OVERSIZE-DST-")).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error("expand_message_xof: invalid lenInBytes"); + return H2.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); +} +function hash_to_field(msg, count, options) { + validateObject(options, { + DST: "stringOrUint8Array", + p: "bigint", + m: "isSafeInteger", + k: "isSafeInteger", + hash: "hash" + }); + const { p, k: k2, m: m2, hash: hash2, expand, DST: _DST } = options; + abytes2(msg); + anum(count); + const DST = typeof _DST === "string" ? utf8ToBytes2(_DST) : _DST; + const log2p = p.toString(2).length; + const L2 = Math.ceil((log2p + k2) / 8); + const len_in_bytes = count * m2 * L2; + let prb; + if (expand === "xmd") { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash2); + } else if (expand === "xof") { + prb = expand_message_xof(msg, DST, len_in_bytes, k2, hash2); + } else if (expand === "_internal_pass") { + prb = msg; + } else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m2); + for (let j2 = 0; j2 < m2; j2++) { + const elm_offset = L2 * (j2 + i * m2); + const tv = prb.subarray(elm_offset, elm_offset + L2); + e[j2] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +function isogenyMap(field, map) { + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x2, y2) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x2), i))); + x2 = field.div(xNum, xDen); + y2 = field.mul(y2, field.div(yNum, yDen)); + return { x: x2, y: y2 }; + }; +} +function createHasher(Point2, mapToCurve, def) { + if (typeof mapToCurve !== "function") + throw new Error("mapToCurve() must be defined"); + return { + // Encodes byte string to elliptic curve. + // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point2.fromAffine(mapToCurve(u[0])); + const u1 = Point2.fromAffine(mapToCurve(u[1])); + const P2 = u0.add(u1).clearCofactor(); + P2.assertValidity(); + return P2; + }, + // Encodes byte string to elliptic curve. + // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P2 = Point2.fromAffine(mapToCurve(u[0])).clearCofactor(); + P2.assertValidity(); + return P2; + }, + // Same as encodeToCurve, but without hash + mapToCurve(scalars) { + if (!Array.isArray(scalars)) + throw new Error("mapToCurve: expected array of bigints"); + for (const i of scalars) + if (typeof i !== "bigint") + throw new Error("mapToCurve: expected array of bigints"); + const P2 = Point2.fromAffine(mapToCurve(scalars)).clearCofactor(); + P2.assertValidity(); + return P2; + } + }; +} +var os2ip; +var init_hash_to_curve = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/abstract/hash-to-curve.js"() { + init_modular(); + init_utils4(); + os2ip = bytesToNumberBE; + } +}); + +// node_modules/viem/node_modules/@noble/curves/esm/secp256k1.js +var secp256k1_exports = {}; +__export(secp256k1_exports, { + encodeToCurve: () => encodeToCurve, + hashToCurve: () => hashToCurve, + schnorr: () => schnorr, + secp256k1: () => secp256k1 +}); +function sqrtMod(y2) { + const P2 = secp256k1P; + const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = y2 * y2 * y2 % P2; + const b3 = b2 * b2 * y2 % P2; + const b6 = pow2(b3, _3n3, P2) * b3 % P2; + const b9 = pow2(b6, _3n3, P2) * b3 % P2; + const b11 = pow2(b9, _2n5, P2) * b2 % P2; + const b22 = pow2(b11, _11n, P2) * b11 % P2; + const b44 = pow2(b22, _22n, P2) * b22 % P2; + const b88 = pow2(b44, _44n, P2) * b44 % P2; + const b176 = pow2(b88, _88n, P2) * b88 % P2; + const b220 = pow2(b176, _44n, P2) * b44 % P2; + const b223 = pow2(b220, _3n3, P2) * b3 % P2; + const t1 = pow2(b223, _23n, P2) * b22 % P2; + const t2 = pow2(t1, _6n, P2) * b2 % P2; + const root = pow2(t2, _2n5, P2); + if (!Fpk1.eql(Fpk1.sqr(root), y2)) + throw new Error("Cannot find square root"); + return root; +} +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === void 0) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes3(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes3(tagP, ...messages)); +} +function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); + let p = Point.fromPrivateKey(d_); + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar, bytes: pointToBytes(p) }; +} +function lift_x(x2) { + aInRange("x", x2, _1n6, secp256k1P); + const xx = modP(x2 * x2); + const c = modP(xx * x2 + BigInt(7)); + let y2 = sqrtMod(c); + if (y2 % _2n5 !== _0n6) + y2 = modP(-y2); + const p = new Point(x2, y2, _1n6); + p.assertValidity(); + return p; +} +function challenge(...args) { + return modN(num(taggedHash("BIP0340/challenge", ...args))); +} +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; +} +function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m2 = ensureBytes("message", message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); + const a = ensureBytes("auxRand", auxRand, 32); + const t = numTo32b(d ^ num(taggedHash("BIP0340/aux", a))); + const rand = taggedHash("BIP0340/nonce", t, px, m2); + const k_ = modN(num(rand)); + if (k_ === _0n6) + throw new Error("sign failed: k is zero"); + const { bytes: rx, scalar: k2 } = schnorrGetExtPubKey(k_); + const e = challenge(rx, px, m2); + const sig = new Uint8Array(64); + sig.set(rx, 0); + sig.set(numTo32b(modN(k2 + e * d)), 32); + if (!schnorrVerify(sig, m2, px)) + throw new Error("sign: Invalid signature produced"); + return sig; +} +function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes("signature", signature, 64); + const m2 = ensureBytes("message", message); + const pub = ensureBytes("publicKey", publicKey, 32); + try { + const P2 = lift_x(num(pub)); + const r = num(sig.subarray(0, 32)); + if (!inRange(r, _1n6, secp256k1P)) + return false; + const s = num(sig.subarray(32, 64)); + if (!inRange(s, _1n6, secp256k1N)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P2), m2); + const R2 = GmulAdd(P2, s, modN(-e)); + if (!R2 || !R2.hasEvenY() || R2.toAffine().x !== r) + return false; + return true; + } catch (error) { + return false; + } +} +var secp256k1P, secp256k1N, _1n6, _2n5, divNearest, Fpk1, secp256k1, _0n6, TAGGED_HASH_PREFIXES, pointToBytes, numTo32b, modP, modN, Point, GmulAdd, num, schnorr, isoMap, mapSWU, htf, hashToCurve, encodeToCurve; +var init_secp256k1 = __esm({ + "node_modules/viem/node_modules/@noble/curves/esm/secp256k1.js"() { + init_sha256(); + init_utils2(); + init_shortw_utils(); + init_hash_to_curve(); + init_modular(); + init_utils4(); + init_weierstrass(); + secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); + secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); + _1n6 = BigInt(1); + _2n5 = BigInt(2); + divNearest = (a, b2) => (a + b2 / _2n5) / b2; + Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); + secp256k1 = createCurve({ + a: BigInt(0), + // equation params: a, b + b: BigInt(7), + Fp: Fpk1, + // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n + n: secp256k1N, + // Curve order, total count of valid points in the field + // Base point (x, y) aka generator point + Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), + Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), + h: BigInt(1), + // Cofactor + lowS: true, + // Allow only low-S signatures by default in sign() and verify() + endo: { + // Endomorphism, see above + beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), + splitScalar: (k2) => { + const n = secp256k1N; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n6 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest(b2 * k2, n); + const c2 = divNearest(-b1 * k2, n); + let k1 = mod(k2 - c1 * a1 - c2 * a2, n); + let k22 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k22 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k22 = n - k22; + if (k1 > POW_2_128 || k22 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k2); + } + return { k1neg, k1, k2neg, k2: k22 }; + } } - if (boundary.length < 1 || boundary.length > 70) { - throw Error("boundary must be 10-70 characters long"); + }, sha256); + _0n6 = BigInt(0); + TAGGED_HASH_PREFIXES = {}; + pointToBytes = (point) => point.toRawBytes(true).slice(1); + numTo32b = (n) => numberToBytesBE(n, 32); + modP = (x2) => mod(x2, secp256k1P); + modN = (x2) => mod(x2, secp256k1N); + Point = secp256k1.ProjectivePoint; + GmulAdd = (Q, a, b2) => Point.BASE.multiplyAndAddUnsafe(Q, a, b2); + num = bytesToNumberBE; + schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod } - const boundaryBytes = textEncoder2.encode("--" + boundary + CRLF2); - const footerBytes = textEncoder2.encode("--" + boundary + "--" + CRLF2); - let contentLength = footerBytes.byteLength; - const parts = Array.from(form.entries()).map(([name, value]) => { - const part = new FormDataPart2(name, value); - contentLength += part.size; - return part; - }); - contentLength += boundaryBytes.byteLength * parts.length; - contentLength = utils$1.toFiniteNumber(contentLength); - const computedHeaders = { - "Content-Type": `multipart/form-data; boundary=${boundary}` - }; - if (Number.isFinite(contentLength)) { - computedHeaders["Content-Length"] = contentLength; + }))(); + isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [ + // xNum + [ + "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", + "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", + "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", + "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" + ], + // xDen + [ + "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", + "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", + "0x0000000000000000000000000000000000000000000000000000000000000001" + // LAST 1 + ], + // yNum + [ + "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", + "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", + "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", + "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" + ], + // yDen + [ + "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", + "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", + "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", + "0x0000000000000000000000000000000000000000000000000000000000000001" + // LAST 1 + ] + ].map((i) => i.map((j2) => BigInt(j2)))))(); + mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, { + A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), + B: BigInt("1771"), + Z: Fpk1.create(BigInt("-11")) + }))(); + htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { + const { x: x2, y: y2 } = mapSWU(Fpk1.create(scalars[0])); + return isoMap(x2, y2); + }, { + DST: "secp256k1_XMD:SHA-256_SSWU_RO_", + encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", + p: Fpk1.ORDER, + m: 1, + k: 128, + expand: "xmd", + hash: sha256 + }))(); + hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)(); + encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)(); + } +}); + +// node_modules/viem/_esm/errors/node.js +var ExecutionRevertedError, FeeCapTooHighError, FeeCapTooLowError, NonceTooHighError, NonceTooLowError, NonceMaxValueError, InsufficientFundsError, IntrinsicGasTooHighError, IntrinsicGasTooLowError, TransactionTypeNotSupportedError, TipAboveFeeCapError, UnknownNodeError; +var init_node = __esm({ + "node_modules/viem/_esm/errors/node.js"() { + init_formatGwei(); + init_base(); + ExecutionRevertedError = class extends BaseError2 { + constructor({ cause, message } = {}) { + const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", ""); + super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, { + cause, + name: "ExecutionRevertedError" + }); } - headersHandler && headersHandler(computedHeaders); - return stream4.Readable.from(async function* () { - for (const part of parts) { - yield boundaryBytes; - yield* part.encode(); - } - yield footerBytes; - }()); }; - var formDataToStream$1 = formDataToStream2; - var ZlibHeaderTransformStream2 = class extends stream__default["default"].Transform { - __transform(chunk, encoding, callback) { - this.push(chunk); - callback(); - } - _transform(chunk, encoding, callback) { - if (chunk.length !== 0) { - this._transform = this.__transform; - if (chunk[0] !== 120) { - const header = Buffer.alloc(2); - header[0] = 120; - header[1] = 156; - this.push(header, encoding); - } - } - this.__transform(chunk, encoding, callback); + Object.defineProperty(ExecutionRevertedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 3 + }); + Object.defineProperty(ExecutionRevertedError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /execution reverted/ + }); + FeeCapTooHighError = class extends BaseError2 { + constructor({ cause, maxFeePerGas } = {}) { + super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, { + cause, + name: "FeeCapTooHighError" + }); } }; - var ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream2; - var callbackify2 = (fn2, reducer) => { - return utils$1.isAsyncFn(fn2) ? function(...args) { - const cb = args.pop(); - fn2.apply(this, args).then((value) => { - try { - reducer ? cb(null, ...reducer(value)) : cb(null, value); - } catch (err) { - cb(err); - } - }, cb); - } : fn2; + Object.defineProperty(FeeCapTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/ + }); + FeeCapTooLowError = class extends BaseError2 { + constructor({ cause, maxFeePerGas } = {}) { + super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, { + cause, + name: "FeeCapTooLowError" + }); + } }; - var callbackify$1 = callbackify2; - function speedometer2(samplesCount, min) { - samplesCount = samplesCount || 10; - const bytes = new Array(samplesCount); - const timestamps = new Array(samplesCount); - let head = 0; - let tail = 0; - let firstSampleTS; - min = min !== void 0 ? min : 1e3; - return function push(chunkLength) { - const now = Date.now(); - const startedAt = timestamps[tail]; - if (!firstSampleTS) { - firstSampleTS = now; - } - bytes[head] = chunkLength; - timestamps[head] = now; - let i = tail; - let bytesCount = 0; - while (i !== head) { - bytesCount += bytes[i++]; - i = i % samplesCount; - } - head = (head + 1) % samplesCount; - if (head === tail) { - tail = (tail + 1) % samplesCount; - } - if (now - firstSampleTS < min) { - return; - } - const passed = startedAt && now - startedAt; - return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; - }; - } - function throttle2(fn2, freq) { - let timestamp = 0; - let threshold = 1e3 / freq; - let lastArgs; - let timer; - const invoke = (args, now = Date.now()) => { - timestamp = now; - lastArgs = null; - if (timer) { - clearTimeout(timer); - timer = null; - } - fn2.apply(null, args); - }; - const throttled = (...args) => { - const now = Date.now(); - const passed = now - timestamp; - if (passed >= threshold) { - invoke(args, now); - } else { - lastArgs = args; - if (!timer) { - timer = setTimeout(() => { - timer = null; - invoke(lastArgs); - }, threshold - passed); - } - } - }; - const flush = () => lastArgs && invoke(lastArgs); - return [throttled, flush]; - } - var progressEventReducer2 = (listener, isDownloadStream, freq = 3) => { - let bytesNotified = 0; - const _speedometer = speedometer2(50, 250); - return throttle2((e) => { - const loaded = e.loaded; - const total = e.lengthComputable ? e.total : void 0; - const progressBytes = loaded - bytesNotified; - const rate = _speedometer(progressBytes); - const inRange2 = loaded <= total; - bytesNotified = loaded; - const data = { - loaded, - total, - progress: total ? loaded / total : void 0, - bytes: progressBytes, - rate: rate ? rate : void 0, - estimated: rate && total && inRange2 ? (total - loaded) / rate : void 0, - event: e, - lengthComputable: total != null, - [isDownloadStream ? "download" : "upload"]: true - }; - listener(data); - }, freq); + Object.defineProperty(FeeCapTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/ + }); + NonceTooHighError = class extends BaseError2 { + constructor({ cause, nonce } = {}) { + super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" }); + } }; - var progressEventDecorator2 = (total, throttled) => { - const lengthComputable = total != null; - return [(loaded) => throttled[0]({ - lengthComputable, - total, - loaded - }), throttled[1]]; + Object.defineProperty(NonceTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce too high/ + }); + NonceTooLowError = class extends BaseError2 { + constructor({ cause, nonce } = {}) { + super([ + `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`, + "Try increasing the nonce or find the latest nonce with `getTransactionCount`." + ].join("\n"), { cause, name: "NonceTooLowError" }); + } }; - var asyncDecorator2 = (fn2) => (...args) => utils$1.asap(() => fn2(...args)); - var zlibOptions2 = { - flush: zlib__default["default"].constants.Z_SYNC_FLUSH, - finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH + Object.defineProperty(NonceTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce too low|transaction already imported|already known/ + }); + NonceMaxValueError = class extends BaseError2 { + constructor({ cause, nonce } = {}) { + super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" }); + } }; - var brotliOptions2 = { - flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH, - finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH + Object.defineProperty(NonceMaxValueError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce has max value/ + }); + InsufficientFundsError = class extends BaseError2 { + constructor({ cause } = {}) { + super([ + "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account." + ].join("\n"), { + cause, + metaMessages: [ + "This error could arise when the account does not have enough funds to:", + " - pay for the total gas fee,", + " - pay for the value to send.", + " ", + "The cost of the transaction is calculated as `gas * gas fee + value`, where:", + " - `gas` is the amount of gas needed for transaction to execute,", + " - `gas fee` is the gas fee,", + " - `value` is the amount of ether to send to the recipient." + ], + name: "InsufficientFundsError" + }); + } }; - var isBrotliSupported2 = utils$1.isFunction(zlib__default["default"].createBrotliDecompress); - var { http: httpFollow2, https: httpsFollow2 } = followRedirects__default["default"]; - var isHttps2 = /https:?/; - var supportedProtocols2 = platform.protocols.map((protocol) => { - return protocol + ":"; + Object.defineProperty(InsufficientFundsError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /insufficient funds|exceeds transaction sender account balance/ }); - var flushOnFinish2 = (stream5, [throttled, flush]) => { - stream5.on("end", flush).on("error", flush); - return throttled; + IntrinsicGasTooHighError = class extends BaseError2 { + constructor({ cause, gas } = {}) { + super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, { + cause, + name: "IntrinsicGasTooHighError" + }); + } }; - function dispatchBeforeRedirect2(options, responseDetails) { - if (options.beforeRedirects.proxy) { - options.beforeRedirects.proxy(options); + Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /intrinsic gas too high|gas limit reached/ + }); + IntrinsicGasTooLowError = class extends BaseError2 { + constructor({ cause, gas } = {}) { + super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, { + cause, + name: "IntrinsicGasTooLowError" + }); } - if (options.beforeRedirects.config) { - options.beforeRedirects.config(options, responseDetails); + }; + Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /intrinsic gas too low/ + }); + TransactionTypeNotSupportedError = class extends BaseError2 { + constructor({ cause }) { + super("The transaction type is not supported for this chain.", { + cause, + name: "TransactionTypeNotSupportedError" + }); } - } - function setProxy2(options, configProxy, location) { - let proxy = configProxy; - if (!proxy && proxy !== false) { - const proxyUrl = proxyFromEnv__default["default"].getProxyForUrl(location); - if (proxyUrl) { - proxy = new URL(proxyUrl); - } + }; + Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /transaction type not valid/ + }); + TipAboveFeeCapError = class extends BaseError2 { + constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) { + super([ + `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).` + ].join("\n"), { + cause, + name: "TipAboveFeeCapError" + }); } - if (proxy) { - if (proxy.username) { - proxy.auth = (proxy.username || "") + ":" + (proxy.password || ""); - } - if (proxy.auth) { - if (proxy.auth.username || proxy.auth.password) { - proxy.auth = (proxy.auth.username || "") + ":" + (proxy.auth.password || ""); - } - const base64 = Buffer.from(proxy.auth, "utf8").toString("base64"); - options.headers["Proxy-Authorization"] = "Basic " + base64; - } - options.headers.host = options.hostname + (options.port ? ":" + options.port : ""); - const proxyHost = proxy.hostname || proxy.host; - options.hostname = proxyHost; - options.host = proxyHost; - options.port = proxy.port; - options.path = location; - if (proxy.protocol) { - options.protocol = proxy.protocol.includes(":") ? proxy.protocol : `${proxy.protocol}:`; - } + }; + Object.defineProperty(TipAboveFeeCapError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/ + }); + UnknownNodeError = class extends BaseError2 { + constructor({ cause }) { + super(`An error occurred while executing: ${cause?.shortMessage}`, { + cause, + name: "UnknownNodeError" + }); } - options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { - setProxy2(redirectOptions, configProxy, redirectOptions.href); - }; + }; + } +}); + +// node_modules/viem/_esm/utils/errors/getNodeError.js +function getNodeError(err, args) { + const message = (err.details || "").toLowerCase(); + const executionRevertedError = err instanceof BaseError2 ? err.walk((e) => e?.code === ExecutionRevertedError.code) : err; + if (executionRevertedError instanceof BaseError2) + return new ExecutionRevertedError({ + cause: err, + message: executionRevertedError.details + }); + if (ExecutionRevertedError.nodeMessage.test(message)) + return new ExecutionRevertedError({ + cause: err, + message: err.details + }); + if (FeeCapTooHighError.nodeMessage.test(message)) + return new FeeCapTooHighError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas + }); + if (FeeCapTooLowError.nodeMessage.test(message)) + return new FeeCapTooLowError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas + }); + if (NonceTooHighError.nodeMessage.test(message)) + return new NonceTooHighError({ cause: err, nonce: args?.nonce }); + if (NonceTooLowError.nodeMessage.test(message)) + return new NonceTooLowError({ cause: err, nonce: args?.nonce }); + if (NonceMaxValueError.nodeMessage.test(message)) + return new NonceMaxValueError({ cause: err, nonce: args?.nonce }); + if (InsufficientFundsError.nodeMessage.test(message)) + return new InsufficientFundsError({ cause: err }); + if (IntrinsicGasTooHighError.nodeMessage.test(message)) + return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas }); + if (IntrinsicGasTooLowError.nodeMessage.test(message)) + return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas }); + if (TransactionTypeNotSupportedError.nodeMessage.test(message)) + return new TransactionTypeNotSupportedError({ cause: err }); + if (TipAboveFeeCapError.nodeMessage.test(message)) + return new TipAboveFeeCapError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas, + maxPriorityFeePerGas: args?.maxPriorityFeePerGas + }); + return new UnknownNodeError({ + cause: err + }); +} +var init_getNodeError = __esm({ + "node_modules/viem/_esm/utils/errors/getNodeError.js"() { + init_base(); + init_node(); + } +}); + +// node_modules/viem/_esm/utils/formatters/extract.js +function extract(value_, { format }) { + if (!format) + return {}; + const value = {}; + function extract_(formatted2) { + const keys = Object.keys(formatted2); + for (const key of keys) { + if (key in value_) + value[key] = value_[key]; + if (formatted2[key] && typeof formatted2[key] === "object" && !Array.isArray(formatted2[key])) + extract_(formatted2[key]); } - var isHttpAdapterSupported2 = typeof process !== "undefined" && utils$1.kindOf(process) === "process"; - var wrapAsync2 = (asyncExecutor) => { - return new Promise((resolve, reject) => { - let onDone; - let isDone; - const done = (value, isRejected) => { - if (isDone) return; - isDone = true; - onDone && onDone(value, isRejected); - }; - const _resolve = (value) => { - done(value); - resolve(value); - }; - const _reject = (reason) => { - done(reason, true); - reject(reason); - }; - asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject); + } + const formatted = format(value_ || {}); + extract_(formatted); + return value; +} +var init_extract = __esm({ + "node_modules/viem/_esm/utils/formatters/extract.js"() { + } +}); + +// node_modules/viem/_esm/utils/formatters/transactionRequest.js +function formatTransactionRequest(request) { + const rpcRequest = {}; + if (typeof request.authorizationList !== "undefined") + rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList); + if (typeof request.accessList !== "undefined") + rpcRequest.accessList = request.accessList; + if (typeof request.blobVersionedHashes !== "undefined") + rpcRequest.blobVersionedHashes = request.blobVersionedHashes; + if (typeof request.blobs !== "undefined") { + if (typeof request.blobs[0] !== "string") + rpcRequest.blobs = request.blobs.map((x2) => bytesToHex(x2)); + else + rpcRequest.blobs = request.blobs; + } + if (typeof request.data !== "undefined") + rpcRequest.data = request.data; + if (typeof request.from !== "undefined") + rpcRequest.from = request.from; + if (typeof request.gas !== "undefined") + rpcRequest.gas = numberToHex(request.gas); + if (typeof request.gasPrice !== "undefined") + rpcRequest.gasPrice = numberToHex(request.gasPrice); + if (typeof request.maxFeePerBlobGas !== "undefined") + rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas); + if (typeof request.maxFeePerGas !== "undefined") + rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas); + if (typeof request.maxPriorityFeePerGas !== "undefined") + rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas); + if (typeof request.nonce !== "undefined") + rpcRequest.nonce = numberToHex(request.nonce); + if (typeof request.to !== "undefined") + rpcRequest.to = request.to; + if (typeof request.type !== "undefined") + rpcRequest.type = rpcTransactionType[request.type]; + if (typeof request.value !== "undefined") + rpcRequest.value = numberToHex(request.value); + return rpcRequest; +} +function formatAuthorizationList(authorizationList) { + return authorizationList.map((authorization) => ({ + address: authorization.address, + r: authorization.r ? numberToHex(BigInt(authorization.r)) : authorization.r, + s: authorization.s ? numberToHex(BigInt(authorization.s)) : authorization.s, + chainId: numberToHex(authorization.chainId), + nonce: numberToHex(authorization.nonce), + ...typeof authorization.yParity !== "undefined" ? { yParity: numberToHex(authorization.yParity) } : {}, + ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: numberToHex(authorization.v) } : {} + })); +} +var rpcTransactionType; +var init_transactionRequest = __esm({ + "node_modules/viem/_esm/utils/formatters/transactionRequest.js"() { + init_toHex(); + rpcTransactionType = { + legacy: "0x0", + eip2930: "0x1", + eip1559: "0x2", + eip4844: "0x3", + eip7702: "0x4" + }; + } +}); + +// node_modules/viem/_esm/utils/stateOverride.js +function serializeStateMapping(stateMapping) { + if (!stateMapping || stateMapping.length === 0) + return void 0; + return stateMapping.reduce((acc, { slot, value }) => { + if (slot.length !== 66) + throw new InvalidBytesLengthError({ + size: slot.length, + targetSize: 66, + type: "hex" }); - }; - var resolveFamily2 = ({ address, family }) => { - if (!utils$1.isString(address)) { - throw TypeError("address must be a string"); - } - return { - address, - family: family || (address.indexOf(".") < 0 ? 6 : 4) - }; - }; - var buildAddressEntry2 = (address, family) => resolveFamily2(utils$1.isObject(address) ? address : { address, family }); - var httpAdapter2 = isHttpAdapterSupported2 && function httpAdapter3(config3) { - return wrapAsync2(async function dispatchHttpRequest(resolve, reject, onDone) { - let { data, lookup, family } = config3; - const { responseType, responseEncoding } = config3; - const method = config3.method.toUpperCase(); - let isDone; - let rejected = false; - let req; - if (lookup) { - const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]); - lookup = (hostname, opt, cb) => { - _lookup(hostname, opt, (err, arg0, arg1) => { - if (err) { - return cb(err); + if (value.length !== 66) + throw new InvalidBytesLengthError({ + size: value.length, + targetSize: 66, + type: "hex" + }); + acc[slot] = value; + return acc; + }, {}); +} +function serializeAccountStateOverride(parameters) { + const { balance, nonce, state, stateDiff, code } = parameters; + const rpcAccountStateOverride = {}; + if (code !== void 0) + rpcAccountStateOverride.code = code; + if (balance !== void 0) + rpcAccountStateOverride.balance = numberToHex(balance); + if (nonce !== void 0) + rpcAccountStateOverride.nonce = numberToHex(nonce); + if (state !== void 0) + rpcAccountStateOverride.state = serializeStateMapping(state); + if (stateDiff !== void 0) { + if (rpcAccountStateOverride.state) + throw new StateAssignmentConflictError(); + rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff); + } + return rpcAccountStateOverride; +} +function serializeStateOverride(parameters) { + if (!parameters) + return void 0; + const rpcStateOverride = {}; + for (const { address, ...accountState } of parameters) { + if (!isAddress(address, { strict: false })) + throw new InvalidAddressError({ address }); + if (rpcStateOverride[address]) + throw new AccountStateConflictError({ address }); + rpcStateOverride[address] = serializeAccountStateOverride(accountState); + } + return rpcStateOverride; +} +var init_stateOverride2 = __esm({ + "node_modules/viem/_esm/utils/stateOverride.js"() { + init_address(); + init_data(); + init_stateOverride(); + init_isAddress(); + init_toHex(); + } +}); + +// node_modules/viem/_esm/constants/number.js +var maxInt8, maxInt16, maxInt24, maxInt32, maxInt40, maxInt48, maxInt56, maxInt64, maxInt72, maxInt80, maxInt88, maxInt96, maxInt104, maxInt112, maxInt120, maxInt128, maxInt136, maxInt144, maxInt152, maxInt160, maxInt168, maxInt176, maxInt184, maxInt192, maxInt200, maxInt208, maxInt216, maxInt224, maxInt232, maxInt240, maxInt248, maxInt256, minInt8, minInt16, minInt24, minInt32, minInt40, minInt48, minInt56, minInt64, minInt72, minInt80, minInt88, minInt96, minInt104, minInt112, minInt120, minInt128, minInt136, minInt144, minInt152, minInt160, minInt168, minInt176, minInt184, minInt192, minInt200, minInt208, minInt216, minInt224, minInt232, minInt240, minInt248, minInt256, maxUint8, maxUint16, maxUint24, maxUint32, maxUint40, maxUint48, maxUint56, maxUint64, maxUint72, maxUint80, maxUint88, maxUint96, maxUint104, maxUint112, maxUint120, maxUint128, maxUint136, maxUint144, maxUint152, maxUint160, maxUint168, maxUint176, maxUint184, maxUint192, maxUint200, maxUint208, maxUint216, maxUint224, maxUint232, maxUint240, maxUint248, maxUint256; +var init_number = __esm({ + "node_modules/viem/_esm/constants/number.js"() { + maxInt8 = 2n ** (8n - 1n) - 1n; + maxInt16 = 2n ** (16n - 1n) - 1n; + maxInt24 = 2n ** (24n - 1n) - 1n; + maxInt32 = 2n ** (32n - 1n) - 1n; + maxInt40 = 2n ** (40n - 1n) - 1n; + maxInt48 = 2n ** (48n - 1n) - 1n; + maxInt56 = 2n ** (56n - 1n) - 1n; + maxInt64 = 2n ** (64n - 1n) - 1n; + maxInt72 = 2n ** (72n - 1n) - 1n; + maxInt80 = 2n ** (80n - 1n) - 1n; + maxInt88 = 2n ** (88n - 1n) - 1n; + maxInt96 = 2n ** (96n - 1n) - 1n; + maxInt104 = 2n ** (104n - 1n) - 1n; + maxInt112 = 2n ** (112n - 1n) - 1n; + maxInt120 = 2n ** (120n - 1n) - 1n; + maxInt128 = 2n ** (128n - 1n) - 1n; + maxInt136 = 2n ** (136n - 1n) - 1n; + maxInt144 = 2n ** (144n - 1n) - 1n; + maxInt152 = 2n ** (152n - 1n) - 1n; + maxInt160 = 2n ** (160n - 1n) - 1n; + maxInt168 = 2n ** (168n - 1n) - 1n; + maxInt176 = 2n ** (176n - 1n) - 1n; + maxInt184 = 2n ** (184n - 1n) - 1n; + maxInt192 = 2n ** (192n - 1n) - 1n; + maxInt200 = 2n ** (200n - 1n) - 1n; + maxInt208 = 2n ** (208n - 1n) - 1n; + maxInt216 = 2n ** (216n - 1n) - 1n; + maxInt224 = 2n ** (224n - 1n) - 1n; + maxInt232 = 2n ** (232n - 1n) - 1n; + maxInt240 = 2n ** (240n - 1n) - 1n; + maxInt248 = 2n ** (248n - 1n) - 1n; + maxInt256 = 2n ** (256n - 1n) - 1n; + minInt8 = -(2n ** (8n - 1n)); + minInt16 = -(2n ** (16n - 1n)); + minInt24 = -(2n ** (24n - 1n)); + minInt32 = -(2n ** (32n - 1n)); + minInt40 = -(2n ** (40n - 1n)); + minInt48 = -(2n ** (48n - 1n)); + minInt56 = -(2n ** (56n - 1n)); + minInt64 = -(2n ** (64n - 1n)); + minInt72 = -(2n ** (72n - 1n)); + minInt80 = -(2n ** (80n - 1n)); + minInt88 = -(2n ** (88n - 1n)); + minInt96 = -(2n ** (96n - 1n)); + minInt104 = -(2n ** (104n - 1n)); + minInt112 = -(2n ** (112n - 1n)); + minInt120 = -(2n ** (120n - 1n)); + minInt128 = -(2n ** (128n - 1n)); + minInt136 = -(2n ** (136n - 1n)); + minInt144 = -(2n ** (144n - 1n)); + minInt152 = -(2n ** (152n - 1n)); + minInt160 = -(2n ** (160n - 1n)); + minInt168 = -(2n ** (168n - 1n)); + minInt176 = -(2n ** (176n - 1n)); + minInt184 = -(2n ** (184n - 1n)); + minInt192 = -(2n ** (192n - 1n)); + minInt200 = -(2n ** (200n - 1n)); + minInt208 = -(2n ** (208n - 1n)); + minInt216 = -(2n ** (216n - 1n)); + minInt224 = -(2n ** (224n - 1n)); + minInt232 = -(2n ** (232n - 1n)); + minInt240 = -(2n ** (240n - 1n)); + minInt248 = -(2n ** (248n - 1n)); + minInt256 = -(2n ** (256n - 1n)); + maxUint8 = 2n ** 8n - 1n; + maxUint16 = 2n ** 16n - 1n; + maxUint24 = 2n ** 24n - 1n; + maxUint32 = 2n ** 32n - 1n; + maxUint40 = 2n ** 40n - 1n; + maxUint48 = 2n ** 48n - 1n; + maxUint56 = 2n ** 56n - 1n; + maxUint64 = 2n ** 64n - 1n; + maxUint72 = 2n ** 72n - 1n; + maxUint80 = 2n ** 80n - 1n; + maxUint88 = 2n ** 88n - 1n; + maxUint96 = 2n ** 96n - 1n; + maxUint104 = 2n ** 104n - 1n; + maxUint112 = 2n ** 112n - 1n; + maxUint120 = 2n ** 120n - 1n; + maxUint128 = 2n ** 128n - 1n; + maxUint136 = 2n ** 136n - 1n; + maxUint144 = 2n ** 144n - 1n; + maxUint152 = 2n ** 152n - 1n; + maxUint160 = 2n ** 160n - 1n; + maxUint168 = 2n ** 168n - 1n; + maxUint176 = 2n ** 176n - 1n; + maxUint184 = 2n ** 184n - 1n; + maxUint192 = 2n ** 192n - 1n; + maxUint200 = 2n ** 200n - 1n; + maxUint208 = 2n ** 208n - 1n; + maxUint216 = 2n ** 216n - 1n; + maxUint224 = 2n ** 224n - 1n; + maxUint232 = 2n ** 232n - 1n; + maxUint240 = 2n ** 240n - 1n; + maxUint248 = 2n ** 248n - 1n; + maxUint256 = 2n ** 256n - 1n; + } +}); + +// node_modules/viem/_esm/utils/transaction/assertRequest.js +function assertRequest(args) { + const { account: account_, gasPrice, maxFeePerGas, maxPriorityFeePerGas, to: to2 } = args; + const account = account_ ? parseAccount(account_) : void 0; + if (account && !isAddress(account.address)) + throw new InvalidAddressError({ address: account.address }); + if (to2 && !isAddress(to2)) + throw new InvalidAddressError({ address: to2 }); + if (typeof gasPrice !== "undefined" && (typeof maxFeePerGas !== "undefined" || typeof maxPriorityFeePerGas !== "undefined")) + throw new FeeConflictError(); + if (maxFeePerGas && maxFeePerGas > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas }); + if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) + throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); +} +var init_assertRequest = __esm({ + "node_modules/viem/_esm/utils/transaction/assertRequest.js"() { + init_parseAccount(); + init_number(); + init_address(); + init_node(); + init_transaction(); + init_isAddress(); + } +}); + +// node_modules/viem/_esm/utils/address/isAddressEqual.js +function isAddressEqual(a, b2) { + if (!isAddress(a, { strict: false })) + throw new InvalidAddressError({ address: a }); + if (!isAddress(b2, { strict: false })) + throw new InvalidAddressError({ address: b2 }); + return a.toLowerCase() === b2.toLowerCase(); +} +var init_isAddressEqual = __esm({ + "node_modules/viem/_esm/utils/address/isAddressEqual.js"() { + init_address(); + init_isAddress(); + } +}); + +// node_modules/viem/_esm/utils/abi/decodeFunctionResult.js +function decodeFunctionResult(parameters) { + const { abi: abi4, args, functionName, data } = parameters; + let abiItem = abi4[0]; + if (functionName) { + const item = getAbiItem({ abi: abi4, args, name: functionName }); + if (!item) + throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath4 }); + abiItem = item; + } + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath4 }); + if (!abiItem.outputs) + throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath4 }); + const values = decodeAbiParameters(abiItem.outputs, data); + if (values && values.length > 1) + return values; + if (values && values.length === 1) + return values[0]; + return void 0; +} +var docsPath4; +var init_decodeFunctionResult = __esm({ + "node_modules/viem/_esm/utils/abi/decodeFunctionResult.js"() { + init_abi(); + init_decodeAbiParameters(); + init_getAbiItem(); + docsPath4 = "/docs/contract/decodeFunctionResult"; + } +}); + +// node_modules/viem/_esm/constants/abis.js +var multicall3Abi, universalResolverErrors, universalResolverResolveAbi, universalResolverReverseAbi, textResolverAbi, addressResolverAbi, universalSignatureValidatorAbi; +var init_abis = __esm({ + "node_modules/viem/_esm/constants/abis.js"() { + multicall3Abi = [ + { + inputs: [ + { + components: [ + { + name: "target", + type: "address" + }, + { + name: "allowFailure", + type: "bool" + }, + { + name: "callData", + type: "bytes" } - const addresses = utils$1.isArray(arg0) ? arg0.map((addr) => buildAddressEntry2(addr)) : [buildAddressEntry2(arg0, arg1)]; - opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); - }); - }; - } - const emitter = new events.EventEmitter(); - const onFinished = () => { - if (config3.cancelToken) { - config3.cancelToken.unsubscribe(abort); - } - if (config3.signal) { - config3.signal.removeEventListener("abort", abort); - } - emitter.removeAllListeners(); - }; - onDone((value, isRejected) => { - isDone = true; - if (isRejected) { - rejected = true; - onFinished(); - } - }); - function abort(reason) { - emitter.emit("abort", !reason || reason.type ? new CanceledError3(null, config3, req) : reason); - } - emitter.once("abort", reject); - if (config3.cancelToken || config3.signal) { - config3.cancelToken && config3.cancelToken.subscribe(abort); - if (config3.signal) { - config3.signal.aborted ? abort() : config3.signal.addEventListener("abort", abort); - } - } - const fullPath = buildFullPath2(config3.baseURL, config3.url, config3.allowAbsoluteUrls); - const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : void 0); - const protocol = parsed.protocol || supportedProtocols2[0]; - if (protocol === "data:") { - let convertedData; - if (method !== "GET") { - return settle2(resolve, reject, { - status: 405, - statusText: "method not allowed", - headers: {}, - config: config3 - }); - } - try { - convertedData = fromDataURI2(config3.url, responseType === "blob", { - Blob: config3.env && config3.env.Blob - }); - } catch (err) { - throw AxiosError3.from(err, AxiosError3.ERR_BAD_REQUEST, config3); - } - if (responseType === "text") { - convertedData = convertedData.toString(responseEncoding); - if (!responseEncoding || responseEncoding === "utf8") { - convertedData = utils$1.stripBOM(convertedData); - } - } else if (responseType === "stream") { - convertedData = stream__default["default"].Readable.from(convertedData); - } - return settle2(resolve, reject, { - data: convertedData, - status: 200, - statusText: "OK", - headers: new AxiosHeaders$1(), - config: config3 - }); - } - if (supportedProtocols2.indexOf(protocol) === -1) { - return reject(new AxiosError3( - "Unsupported protocol " + protocol, - AxiosError3.ERR_BAD_REQUEST, - config3 - )); - } - const headers = AxiosHeaders$1.from(config3.headers).normalize(); - headers.set("User-Agent", "axios/" + VERSION3, false); - const { onUploadProgress, onDownloadProgress } = config3; - const maxRate = config3.maxRate; - let maxUploadRate = void 0; - let maxDownloadRate = void 0; - if (utils$1.isSpecCompliantForm(data)) { - const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); - data = formDataToStream$1(data, (formHeaders) => { - headers.set(formHeaders); - }, { - tag: `axios-${VERSION3}-boundary`, - boundary: userBoundary && userBoundary[1] || void 0 - }); - } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) { - headers.set(data.getHeaders()); - if (!headers.hasContentLength()) { - try { - const knownLength = await util__default["default"].promisify(data.getLength).call(data); - Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); - } catch (e) { - } - } - } else if (utils$1.isBlob(data) || utils$1.isFile(data)) { - data.size && headers.setContentType(data.type || "application/octet-stream"); - headers.setContentLength(data.size || 0); - data = stream__default["default"].Readable.from(readBlob$1(data)); - } else if (data && !utils$1.isStream(data)) { - if (Buffer.isBuffer(data)) ; - else if (utils$1.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils$1.isString(data)) { - data = Buffer.from(data, "utf-8"); - } else { - return reject(new AxiosError3( - "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream", - AxiosError3.ERR_BAD_REQUEST, - config3 - )); - } - headers.setContentLength(data.length, false); - if (config3.maxBodyLength > -1 && data.length > config3.maxBodyLength) { - return reject(new AxiosError3( - "Request body larger than maxBodyLength limit", - AxiosError3.ERR_BAD_REQUEST, - config3 - )); + ], + name: "calls", + type: "tuple[]" } - } - const contentLength = utils$1.toFiniteNumber(headers.getContentLength()); - if (utils$1.isArray(maxRate)) { - maxUploadRate = maxRate[0]; - maxDownloadRate = maxRate[1]; - } else { - maxUploadRate = maxDownloadRate = maxRate; - } - if (data && (onUploadProgress || maxUploadRate)) { - if (!utils$1.isStream(data)) { - data = stream__default["default"].Readable.from(data, { objectMode: false }); + ], + name: "aggregate3", + outputs: [ + { + components: [ + { + name: "success", + type: "bool" + }, + { + name: "returnData", + type: "bytes" + } + ], + name: "returnData", + type: "tuple[]" } - data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ - maxRate: utils$1.toFiniteNumber(maxUploadRate) - })], utils$1.noop); - onUploadProgress && data.on("progress", flushOnFinish2( - data, - progressEventDecorator2( - contentLength, - progressEventReducer2(asyncDecorator2(onUploadProgress), false, 3) - ) - )); - } - let auth = void 0; - if (config3.auth) { - const username = config3.auth.username || ""; - const password = config3.auth.password || ""; - auth = username + ":" + password; - } - if (!auth && parsed.username) { - const urlUsername = parsed.username; - const urlPassword = parsed.password; - auth = urlUsername + ":" + urlPassword; - } - auth && headers.delete("authorization"); - let path; - try { - path = buildURL2( - parsed.pathname + parsed.search, - config3.params, - config3.paramsSerializer - ).replace(/^\?/, ""); - } catch (err) { - const customErr = new Error(err.message); - customErr.config = config3; - customErr.url = config3.url; - customErr.exists = true; - return reject(customErr); - } - headers.set( - "Accept-Encoding", - "gzip, compress, deflate" + (isBrotliSupported2 ? ", br" : ""), - false - ); - const options = { - path, - method, - headers: headers.toJSON(), - agents: { http: config3.httpAgent, https: config3.httpsAgent }, - auth, - protocol, - family, - beforeRedirect: dispatchBeforeRedirect2, - beforeRedirects: {} - }; - !utils$1.isUndefined(lookup) && (options.lookup = lookup); - if (config3.socketPath) { - options.socketPath = config3.socketPath; - } else { - options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; - options.port = parsed.port; - setProxy2(options, config3.proxy, protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options.path); - } - let transport; - const isHttpsRequest = isHttps2.test(options.protocol); - options.agent = isHttpsRequest ? config3.httpsAgent : config3.httpAgent; - if (config3.transport) { - transport = config3.transport; - } else if (config3.maxRedirects === 0) { - transport = isHttpsRequest ? https__default["default"] : http__default["default"]; - } else { - if (config3.maxRedirects) { - options.maxRedirects = config3.maxRedirects; + ], + stateMutability: "view", + type: "function" + } + ]; + universalResolverErrors = [ + { + inputs: [], + name: "ResolverNotFound", + type: "error" + }, + { + inputs: [], + name: "ResolverWildcardNotSupported", + type: "error" + }, + { + inputs: [], + name: "ResolverNotContract", + type: "error" + }, + { + inputs: [ + { + name: "returnData", + type: "bytes" } - if (config3.beforeRedirect) { - options.beforeRedirects.config = config3.beforeRedirect; + ], + name: "ResolverError", + type: "error" + }, + { + inputs: [ + { + components: [ + { + name: "status", + type: "uint16" + }, + { + name: "message", + type: "string" + } + ], + name: "errors", + type: "tuple[]" } - transport = isHttpsRequest ? httpsFollow2 : httpFollow2; - } - if (config3.maxBodyLength > -1) { - options.maxBodyLength = config3.maxBodyLength; - } else { - options.maxBodyLength = Infinity; - } - if (config3.insecureHTTPParser) { - options.insecureHTTPParser = config3.insecureHTTPParser; - } - req = transport.request(options, function handleResponse(res) { - if (req.destroyed) return; - const streams = [res]; - const responseLength = +res.headers["content-length"]; - if (onDownloadProgress || maxDownloadRate) { - const transformStream = new AxiosTransformStream$1({ - maxRate: utils$1.toFiniteNumber(maxDownloadRate) - }); - onDownloadProgress && transformStream.on("progress", flushOnFinish2( - transformStream, - progressEventDecorator2( - responseLength, - progressEventReducer2(asyncDecorator2(onDownloadProgress), true, 3) - ) - )); - streams.push(transformStream); + ], + name: "HttpError", + type: "error" + } + ]; + universalResolverResolveAbi = [ + ...universalResolverErrors, + { + name: "resolve", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes" }, + { name: "data", type: "bytes" } + ], + outputs: [ + { name: "", type: "bytes" }, + { name: "address", type: "address" } + ] + }, + { + name: "resolve", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes" }, + { name: "data", type: "bytes" }, + { name: "gateways", type: "string[]" } + ], + outputs: [ + { name: "", type: "bytes" }, + { name: "address", type: "address" } + ] + } + ]; + universalResolverReverseAbi = [ + ...universalResolverErrors, + { + name: "reverse", + type: "function", + stateMutability: "view", + inputs: [{ type: "bytes", name: "reverseName" }], + outputs: [ + { type: "string", name: "resolvedName" }, + { type: "address", name: "resolvedAddress" }, + { type: "address", name: "reverseResolver" }, + { type: "address", name: "resolver" } + ] + }, + { + name: "reverse", + type: "function", + stateMutability: "view", + inputs: [ + { type: "bytes", name: "reverseName" }, + { type: "string[]", name: "gateways" } + ], + outputs: [ + { type: "string", name: "resolvedName" }, + { type: "address", name: "resolvedAddress" }, + { type: "address", name: "reverseResolver" }, + { type: "address", name: "resolver" } + ] + } + ]; + textResolverAbi = [ + { + name: "text", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes32" }, + { name: "key", type: "string" } + ], + outputs: [{ name: "", type: "string" }] + } + ]; + addressResolverAbi = [ + { + name: "addr", + type: "function", + stateMutability: "view", + inputs: [{ name: "name", type: "bytes32" }], + outputs: [{ name: "", type: "address" }] + }, + { + name: "addr", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes32" }, + { name: "coinType", type: "uint256" } + ], + outputs: [{ name: "", type: "bytes" }] + } + ]; + universalSignatureValidatorAbi = [ + { + inputs: [ + { + name: "_signer", + type: "address" + }, + { + name: "_hash", + type: "bytes32" + }, + { + name: "_signature", + type: "bytes" } - let responseStream = res; - const lastRequest = res.req || req; - if (config3.decompress !== false && res.headers["content-encoding"]) { - if (method === "HEAD" || res.statusCode === 204) { - delete res.headers["content-encoding"]; - } - switch ((res.headers["content-encoding"] || "").toLowerCase()) { - /*eslint default-case:0*/ - case "gzip": - case "x-gzip": - case "compress": - case "x-compress": - streams.push(zlib__default["default"].createUnzip(zlibOptions2)); - delete res.headers["content-encoding"]; - break; - case "deflate": - streams.push(new ZlibHeaderTransformStream$1()); - streams.push(zlib__default["default"].createUnzip(zlibOptions2)); - delete res.headers["content-encoding"]; - break; - case "br": - if (isBrotliSupported2) { - streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions2)); - delete res.headers["content-encoding"]; - } - } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [ + { + name: "_signer", + type: "address" + }, + { + name: "_hash", + type: "bytes32" + }, + { + name: "_signature", + type: "bytes" } - responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0]; - const offListeners = stream__default["default"].finished(responseStream, () => { - offListeners(); - onFinished(); - }); - const response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: new AxiosHeaders$1(res.headers), - config: config3, - request: lastRequest - }; - if (responseType === "stream") { - response.data = responseStream; - settle2(resolve, reject, response); - } else { - const responseBuffer = []; - let totalResponseBytes = 0; - responseStream.on("data", function handleStreamData(chunk) { - responseBuffer.push(chunk); - totalResponseBytes += chunk.length; - if (config3.maxContentLength > -1 && totalResponseBytes > config3.maxContentLength) { - rejected = true; - responseStream.destroy(); - reject(new AxiosError3( - "maxContentLength size of " + config3.maxContentLength + " exceeded", - AxiosError3.ERR_BAD_RESPONSE, - config3, - lastRequest - )); - } - }); - responseStream.on("aborted", function handlerStreamAborted() { - if (rejected) { - return; - } - const err = new AxiosError3( - "stream has been aborted", - AxiosError3.ERR_BAD_RESPONSE, - config3, - lastRequest - ); - responseStream.destroy(err); - reject(err); - }); - responseStream.on("error", function handleStreamError(err) { - if (req.destroyed) return; - reject(AxiosError3.from(err, null, config3, lastRequest)); - }); - responseStream.on("end", function handleStreamEnd() { - try { - let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); - if (responseType !== "arraybuffer") { - responseData = responseData.toString(responseEncoding); - if (!responseEncoding || responseEncoding === "utf8") { - responseData = utils$1.stripBOM(responseData); - } - } - response.data = responseData; - } catch (err) { - return reject(AxiosError3.from(err, null, config3, response.request, response)); - } - settle2(resolve, reject, response); - }); + ], + outputs: [ + { + type: "bool" } - emitter.once("abort", (err) => { - if (!responseStream.destroyed) { - responseStream.emit("error", err); - responseStream.destroy(); - } - }); + ], + stateMutability: "nonpayable", + type: "function", + name: "isValidSig" + } + ]; + } +}); + +// node_modules/viem/_esm/constants/contract.js +var aggregate3Signature; +var init_contract2 = __esm({ + "node_modules/viem/_esm/constants/contract.js"() { + aggregate3Signature = "0x82ad56cb"; + } +}); + +// node_modules/viem/_esm/constants/contracts.js +var deploylessCallViaBytecodeBytecode, deploylessCallViaFactoryBytecode, universalSignatureValidatorByteCode; +var init_contracts = __esm({ + "node_modules/viem/_esm/constants/contracts.js"() { + deploylessCallViaBytecodeBytecode = "0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe"; + deploylessCallViaFactoryBytecode = "0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe"; + universalSignatureValidatorByteCode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572"; + } +}); + +// node_modules/viem/_esm/errors/chain.js +var ChainDoesNotSupportContract, ChainMismatchError, ChainNotFoundError, ClientChainNotConfiguredError, InvalidChainIdError; +var init_chain = __esm({ + "node_modules/viem/_esm/errors/chain.js"() { + init_base(); + ChainDoesNotSupportContract = class extends BaseError2 { + constructor({ blockNumber, chain, contract }) { + super(`Chain "${chain.name}" does not support contract "${contract.name}".`, { + metaMessages: [ + "This could be due to any of the following:", + ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [ + `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).` + ] : [ + `- The chain does not have the contract "${contract.name}" configured.` + ] + ], + name: "ChainDoesNotSupportContract" + }); + } + }; + ChainMismatchError = class extends BaseError2 { + constructor({ chain, currentChainId }) { + super(`The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} \u2013 ${chain.name}).`, { + metaMessages: [ + `Current Chain ID: ${currentChainId}`, + `Expected Chain ID: ${chain.id} \u2013 ${chain.name}` + ], + name: "ChainMismatchError" + }); + } + }; + ChainNotFoundError = class extends BaseError2 { + constructor() { + super([ + "No chain was provided to the request.", + "Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient." + ].join("\n"), { + name: "ChainNotFoundError" + }); + } + }; + ClientChainNotConfiguredError = class extends BaseError2 { + constructor() { + super("No chain was provided to the Client.", { + name: "ClientChainNotConfiguredError" + }); + } + }; + InvalidChainIdError = class extends BaseError2 { + constructor({ chainId }) { + super(typeof chainId === "number" ? `Chain ID "${chainId}" is invalid.` : "Chain ID is invalid.", { name: "InvalidChainIdError" }); + } + }; + } +}); + +// node_modules/viem/_esm/utils/abi/encodeDeployData.js +function encodeDeployData(parameters) { + const { abi: abi4, args, bytecode } = parameters; + if (!args || args.length === 0) + return bytecode; + const description = abi4.find((x2) => "type" in x2 && x2.type === "constructor"); + if (!description) + throw new AbiConstructorNotFoundError({ docsPath: docsPath5 }); + if (!("inputs" in description)) + throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 }); + if (!description.inputs || description.inputs.length === 0) + throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 }); + const data = encodeAbiParameters(description.inputs, args); + return concatHex([bytecode, data]); +} +var docsPath5; +var init_encodeDeployData = __esm({ + "node_modules/viem/_esm/utils/abi/encodeDeployData.js"() { + init_abi(); + init_concat(); + init_encodeAbiParameters(); + docsPath5 = "/docs/contract/encodeDeployData"; + } +}); + +// node_modules/viem/_esm/utils/chain/getChainContractAddress.js +function getChainContractAddress({ blockNumber, chain, contract: name }) { + const contract = chain?.contracts?.[name]; + if (!contract) + throw new ChainDoesNotSupportContract({ + chain, + contract: { name } + }); + if (blockNumber && contract.blockCreated && contract.blockCreated > blockNumber) + throw new ChainDoesNotSupportContract({ + blockNumber, + chain, + contract: { + name, + blockCreated: contract.blockCreated + } + }); + return contract.address; +} +var init_getChainContractAddress = __esm({ + "node_modules/viem/_esm/utils/chain/getChainContractAddress.js"() { + init_chain(); + } +}); + +// node_modules/viem/_esm/utils/errors/getCallError.js +function getCallError(err, { docsPath: docsPath6, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new CallExecutionError(cause, { + docsPath: docsPath6, + ...args + }); +} +var init_getCallError = __esm({ + "node_modules/viem/_esm/utils/errors/getCallError.js"() { + init_contract(); + init_node(); + init_getNodeError(); + } +}); + +// node_modules/viem/_esm/utils/promise/withResolvers.js +function withResolvers() { + let resolve = () => void 0; + let reject = () => void 0; + const promise = new Promise((resolve_, reject_) => { + resolve = resolve_; + reject = reject_; + }); + return { promise, resolve, reject }; +} +var init_withResolvers = __esm({ + "node_modules/viem/_esm/utils/promise/withResolvers.js"() { + } +}); + +// node_modules/viem/_esm/utils/promise/createBatchScheduler.js +function createBatchScheduler({ fn: fn2, id: id2, shouldSplitBatch, wait: wait2 = 0, sort }) { + const exec = async () => { + const scheduler = getScheduler(); + flush(); + const args = scheduler.map(({ args: args2 }) => args2); + if (args.length === 0) + return; + fn2(args).then((data) => { + if (sort && Array.isArray(data)) + data.sort(sort); + for (let i = 0; i < scheduler.length; i++) { + const { resolve } = scheduler[i]; + resolve?.([data[i], data]); + } + }).catch((err) => { + for (let i = 0; i < scheduler.length; i++) { + const { reject } = scheduler[i]; + reject?.(err); + } + }); + }; + const flush = () => schedulerCache.delete(id2); + const getBatchedArgs = () => getScheduler().map(({ args }) => args); + const getScheduler = () => schedulerCache.get(id2) || []; + const setScheduler = (item) => schedulerCache.set(id2, [...getScheduler(), item]); + return { + flush, + async schedule(args) { + const { promise, resolve, reject } = withResolvers(); + const split3 = shouldSplitBatch?.([...getBatchedArgs(), args]); + if (split3) + exec(); + const hasActiveScheduler = getScheduler().length > 0; + if (hasActiveScheduler) { + setScheduler({ args, resolve, reject }); + return promise; + } + setScheduler({ args, resolve, reject }); + setTimeout(exec, wait2); + return promise; + } + }; +} +var schedulerCache; +var init_createBatchScheduler = __esm({ + "node_modules/viem/_esm/utils/promise/createBatchScheduler.js"() { + init_withResolvers(); + schedulerCache = /* @__PURE__ */ new Map(); + } +}); + +// node_modules/viem/_esm/errors/ccip.js +var OffchainLookupError, OffchainLookupResponseMalformedError, OffchainLookupSenderMismatchError; +var init_ccip = __esm({ + "node_modules/viem/_esm/errors/ccip.js"() { + init_stringify(); + init_base(); + init_utils3(); + OffchainLookupError = class extends BaseError2 { + constructor({ callbackSelector, cause, data, extraData, sender, urls }) { + super(cause.shortMessage || "An error occurred while fetching for an offchain result.", { + cause, + metaMessages: [ + ...cause.metaMessages || [], + cause.metaMessages?.length ? "" : [], + "Offchain Gateway Call:", + urls && [ + " Gateway URL(s):", + ...urls.map((url2) => ` ${getUrl(url2)}`) + ], + ` Sender: ${sender}`, + ` Data: ${data}`, + ` Callback selector: ${callbackSelector}`, + ` Extra data: ${extraData}` + ].flat(), + name: "OffchainLookupError" }); - emitter.once("abort", (err) => { - reject(err); - req.destroy(err); + } + }; + OffchainLookupResponseMalformedError = class extends BaseError2 { + constructor({ result, url: url2 }) { + super("Offchain gateway response is malformed. Response data must be a hex value.", { + metaMessages: [ + `Gateway URL: ${getUrl(url2)}`, + `Response: ${stringify(result)}` + ], + name: "OffchainLookupResponseMalformedError" }); - req.on("error", function handleRequestError(err) { - reject(AxiosError3.from(err, null, config3, req)); + } + }; + OffchainLookupSenderMismatchError = class extends BaseError2 { + constructor({ sender, to: to2 }) { + super("Reverted sender address does not match target contract address (`to`).", { + metaMessages: [ + `Contract address: ${to2}`, + `OffchainLookup sender address: ${sender}` + ], + name: "OffchainLookupSenderMismatchError" }); - req.on("socket", function handleRequestSocket(socket) { - socket.setKeepAlive(true, 1e3 * 60); + } + }; + } +}); + +// node_modules/viem/_esm/utils/ccip.js +var ccip_exports = {}; +__export(ccip_exports, { + ccipRequest: () => ccipRequest, + offchainLookup: () => offchainLookup, + offchainLookupAbiItem: () => offchainLookupAbiItem, + offchainLookupSignature: () => offchainLookupSignature +}); +async function offchainLookup(client, { blockNumber, blockTag, data, to: to2 }) { + const { args } = decodeErrorResult({ + data, + abi: [offchainLookupAbiItem] + }); + const [sender, urls, callData, callbackSelector, extraData] = args; + const { ccipRead } = client; + const ccipRequest_ = ccipRead && typeof ccipRead?.request === "function" ? ccipRead.request : ccipRequest; + try { + if (!isAddressEqual(to2, sender)) + throw new OffchainLookupSenderMismatchError({ sender, to: to2 }); + const result = await ccipRequest_({ data: callData, sender, urls }); + const { data: data_ } = await call(client, { + blockNumber, + blockTag, + data: concat([ + callbackSelector, + encodeAbiParameters([{ type: "bytes" }, { type: "bytes" }], [result, extraData]) + ]), + to: to2 + }); + return data_; + } catch (err) { + throw new OffchainLookupError({ + callbackSelector, + cause: err, + data, + extraData, + sender, + urls + }); + } +} +async function ccipRequest({ data, sender, urls }) { + let error = new Error("An unknown error occurred."); + for (let i = 0; i < urls.length; i++) { + const url2 = urls[i]; + const method = url2.includes("{data}") ? "GET" : "POST"; + const body = method === "POST" ? { data, sender } : void 0; + const headers = method === "POST" ? { "Content-Type": "application/json" } : {}; + try { + const response = await fetch(url2.replace("{sender}", sender.toLowerCase()).replace("{data}", data), { + body: JSON.stringify(body), + headers, + method + }); + let result; + if (response.headers.get("Content-Type")?.startsWith("application/json")) { + result = (await response.json()).data; + } else { + result = await response.text(); + } + if (!response.ok) { + error = new HttpRequestError({ + body, + details: result?.error ? stringify(result.error) : response.statusText, + headers: response.headers, + status: response.status, + url: url2 }); - if (config3.timeout) { - const timeout = parseInt(config3.timeout, 10); - if (Number.isNaN(timeout)) { - reject(new AxiosError3( - "error trying to parse `config.timeout` to int", - AxiosError3.ERR_BAD_OPTION_VALUE, - config3, - req - )); - return; - } - req.setTimeout(timeout, function handleRequestTimeout() { - if (isDone) return; - let timeoutErrorMessage = config3.timeout ? "timeout of " + config3.timeout + "ms exceeded" : "timeout exceeded"; - const transitional2 = config3.transitional || transitionalDefaults; - if (config3.timeoutErrorMessage) { - timeoutErrorMessage = config3.timeoutErrorMessage; - } - reject(new AxiosError3( - timeoutErrorMessage, - transitional2.clarifyTimeoutError ? AxiosError3.ETIMEDOUT : AxiosError3.ECONNABORTED, - config3, - req - )); - abort(); - }); - } - if (utils$1.isStream(data)) { - let ended = false; - let errored = false; - data.on("end", () => { - ended = true; - }); - data.once("error", (err) => { - errored = true; - req.destroy(err); - }); - data.on("close", () => { - if (!ended && !errored) { - abort(new CanceledError3("Request stream has been aborted", config3, req)); - } - }); - data.pipe(req); - } else { - req.end(data); - } + continue; + } + if (!isHex(result)) { + error = new OffchainLookupResponseMalformedError({ + result, + url: url2 + }); + continue; + } + return result; + } catch (err) { + error = new HttpRequestError({ + body, + details: err.message, + url: url2 }); - }; - var isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin3, isMSIE) => (url3) => { - url3 = new URL(url3, platform.origin); - return origin3.protocol === url3.protocol && origin3.host === url3.host && (isMSIE || origin3.port === url3.port); - })( - new URL(platform.origin), - platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) - ) : () => true; - var cookies = platform.hasStandardBrowserEnv ? ( - // Standard browser envs support document.cookie - { - write(name, value, expires, path, domain, secure) { - const cookie = [name + "=" + encodeURIComponent(value)]; - utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); - utils$1.isString(path) && cookie.push("path=" + path); - utils$1.isString(domain) && cookie.push("domain=" + domain); - secure === true && cookie.push("secure"); - document.cookie = cookie.join("; "); + } + } + throw error; +} +var offchainLookupSignature, offchainLookupAbiItem; +var init_ccip2 = __esm({ + "node_modules/viem/_esm/utils/ccip.js"() { + init_call(); + init_ccip(); + init_request(); + init_decodeErrorResult(); + init_encodeAbiParameters(); + init_isAddressEqual(); + init_concat(); + init_isHex(); + init_stringify(); + offchainLookupSignature = "0x556f1830"; + offchainLookupAbiItem = { + name: "OffchainLookup", + type: "error", + inputs: [ + { + name: "sender", + type: "address" }, - read(name) { - const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)")); - return match ? decodeURIComponent(match[3]) : null; + { + name: "urls", + type: "string[]" }, - remove(name) { - this.write(name, "", Date.now() - 864e5); - } - } - ) : ( - // Non-standard browser env (web workers, react-native) lack needed support. - { - write() { + { + name: "callData", + type: "bytes" }, - read() { - return null; + { + name: "callbackFunction", + type: "bytes4" }, - remove() { - } - } - ); - var headersToObject2 = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; - function mergeConfig3(config1, config22) { - config22 = config22 || {}; - const config3 = {}; - function getMergedValue(target, source, prop, caseless) { - if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { - return utils$1.merge.call({ caseless }, target, source); - } else if (utils$1.isPlainObject(source)) { - return utils$1.merge({}, source); - } else if (utils$1.isArray(source)) { - return source.slice(); - } - return source; - } - function mergeDeepProperties(a, b2, prop, caseless) { - if (!utils$1.isUndefined(b2)) { - return getMergedValue(a, b2, prop, caseless); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(void 0, a, prop, caseless); - } - } - function valueFromConfig2(a, b2) { - if (!utils$1.isUndefined(b2)) { - return getMergedValue(void 0, b2); - } - } - function defaultToConfig2(a, b2) { - if (!utils$1.isUndefined(b2)) { - return getMergedValue(void 0, b2); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(void 0, a); + { + name: "extraData", + type: "bytes" } + ] + }; + } +}); + +// node_modules/viem/_esm/actions/public/call.js +async function call(client, args) { + const { account: account_ = client.account, batch = Boolean(client.batch?.multicall), blockNumber, blockTag = "latest", accessList, blobs, code, data: data_, factory, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value, stateOverride, ...rest } = args; + const account = account_ ? parseAccount(account_) : void 0; + if (code && (factory || factoryData)) + throw new BaseError2("Cannot provide both `code` & `factory`/`factoryData` as parameters."); + if (code && to2) + throw new BaseError2("Cannot provide both `code` & `to` as parameters."); + const deploylessCallViaBytecode = code && data_; + const deploylessCallViaFactory = factory && factoryData && to2 && data_; + const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory; + const data = (() => { + if (deploylessCallViaBytecode) + return toDeploylessCallViaBytecodeData({ + code, + data: data_ + }); + if (deploylessCallViaFactory) + return toDeploylessCallViaFactoryData({ + data: data_, + factory, + factoryData, + to: to2 + }); + return data_; + })(); + try { + assertRequest(args); + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const rpcStateOverride = serializeStateOverride(stateOverride); + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format = chainFormat || formatTransactionRequest; + const request = format({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + from: account?.address, + accessList, + blobs, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to: deploylessCall ? void 0 : to2, + value + }); + if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride) { + try { + return await scheduleMulticall(client, { + ...request, + blockNumber, + blockTag + }); + } catch (err) { + if (!(err instanceof ClientChainNotConfiguredError) && !(err instanceof ChainDoesNotSupportContract)) + throw err; } - function mergeDirectKeys(a, b2, prop) { - if (prop in config22) { - return getMergedValue(a, b2); - } else if (prop in config1) { - return getMergedValue(void 0, a); - } + } + const response = await client.request({ + method: "eth_call", + params: rpcStateOverride ? [ + request, + block, + rpcStateOverride + ] : [request, block] + }); + if (response === "0x") + return { data: void 0 }; + return { data: response }; + } catch (err) { + const data2 = getRevertErrorData(err); + const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await Promise.resolve().then(() => (init_ccip2(), ccip_exports)); + if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to2) + return { data: await offchainLookup2(client, { data: data2, to: to2 }) }; + if (deploylessCall && data2?.slice(0, 10) === "0x101bb98d") + throw new CounterfactualDeploymentFailedError({ factory }); + throw getCallError(err, { + ...args, + account, + chain: client.chain + }); + } +} +function shouldPerformMulticall({ request }) { + const { data, to: to2, ...request_ } = request; + if (!data) + return false; + if (data.startsWith(aggregate3Signature)) + return false; + if (!to2) + return false; + if (Object.values(request_).filter((x2) => typeof x2 !== "undefined").length > 0) + return false; + return true; +} +async function scheduleMulticall(client, args) { + const { batchSize = 1024, wait: wait2 = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; + const { blockNumber, blockTag = "latest", data, multicallAddress: multicallAddress_, to: to2 } = args; + let multicallAddress = multicallAddress_; + if (!multicallAddress) { + if (!client.chain) + throw new ClientChainNotConfiguredError(); + multicallAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "multicall3" + }); + } + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const { schedule } = createBatchScheduler({ + id: `${client.uid}.${block}`, + wait: wait2, + shouldSplitBatch(args2) { + const size5 = args2.reduce((size6, { data: data2 }) => size6 + (data2.length - 2), 0); + return size5 > batchSize * 2; + }, + fn: async (requests) => { + const calls = requests.map((request) => ({ + allowFailure: true, + callData: request.data, + target: request.to + })); + const calldata = encodeFunctionData({ + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3" + }); + const data2 = await client.request({ + method: "eth_call", + params: [ + { + data: calldata, + to: multicallAddress + }, + block + ] + }); + return decodeFunctionResult({ + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3", + data: data2 || "0x" + }); + } + }); + const [{ returnData, success }] = await schedule({ data, to: to2 }); + if (!success) + throw new RawContractError({ data: returnData }); + if (returnData === "0x") + return { data: void 0 }; + return { data: returnData }; +} +function toDeploylessCallViaBytecodeData(parameters) { + const { code, data } = parameters; + return encodeDeployData({ + abi: parseAbi(["constructor(bytes, bytes)"]), + bytecode: deploylessCallViaBytecodeBytecode, + args: [code, data] + }); +} +function toDeploylessCallViaFactoryData(parameters) { + const { data, factory, factoryData, to: to2 } = parameters; + return encodeDeployData({ + abi: parseAbi(["constructor(address, bytes, address, bytes)"]), + bytecode: deploylessCallViaFactoryBytecode, + args: [to2, data, factory, factoryData] + }); +} +function getRevertErrorData(err) { + if (!(err instanceof BaseError2)) + return void 0; + const error = err.walk(); + return typeof error?.data === "object" ? error.data?.data : error.data; +} +var init_call = __esm({ + "node_modules/viem/_esm/actions/public/call.js"() { + init_exports(); + init_parseAccount(); + init_abis(); + init_contract2(); + init_contracts(); + init_base(); + init_chain(); + init_contract(); + init_decodeFunctionResult(); + init_encodeDeployData(); + init_encodeFunctionData(); + init_getChainContractAddress(); + init_toHex(); + init_getCallError(); + init_extract(); + init_transactionRequest(); + init_createBatchScheduler(); + init_stateOverride2(); + init_assertRequest(); + } +}); + +// node_modules/delayed-stream/lib/delayed_stream.js +var require_delayed_stream = __commonJS({ + "node_modules/delayed-stream/lib/delayed_stream.js"(exports2, module2) { + var Stream = __require("stream").Stream; + var util3 = __require("util"); + module2.exports = DelayedStream; + function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; + } + util3.inherits(DelayedStream, Stream); + DelayedStream.create = function(source, options) { + var delayedStream = new this(); + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; } - const mergeMap = { - url: valueFromConfig2, - method: valueFromConfig2, - data: valueFromConfig2, - baseURL: defaultToConfig2, - transformRequest: defaultToConfig2, - transformResponse: defaultToConfig2, - paramsSerializer: defaultToConfig2, - timeout: defaultToConfig2, - timeoutMessage: defaultToConfig2, - withCredentials: defaultToConfig2, - withXSRFToken: defaultToConfig2, - adapter: defaultToConfig2, - responseType: defaultToConfig2, - xsrfCookieName: defaultToConfig2, - xsrfHeaderName: defaultToConfig2, - onUploadProgress: defaultToConfig2, - onDownloadProgress: defaultToConfig2, - decompress: defaultToConfig2, - maxContentLength: defaultToConfig2, - maxBodyLength: defaultToConfig2, - beforeRedirect: defaultToConfig2, - transport: defaultToConfig2, - httpAgent: defaultToConfig2, - httpsAgent: defaultToConfig2, - cancelToken: defaultToConfig2, - socketPath: defaultToConfig2, - responseEncoding: defaultToConfig2, - validateStatus: mergeDirectKeys, - headers: (a, b2, prop) => mergeDeepProperties(headersToObject2(a), headersToObject2(b2), prop, true) + delayedStream.source = source; + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); }; - utils$1.forEach(Object.keys(Object.assign({}, config1, config22)), function computeConfigValue(prop) { - const merge3 = mergeMap[prop] || mergeDeepProperties; - const configValue = merge3(config1[prop], config22[prop], prop); - utils$1.isUndefined(configValue) && merge3 !== mergeDirectKeys || (config3[prop] = configValue); + source.on("error", function() { }); - return config3; - } - var resolveConfig = (config3) => { - const newConfig = mergeConfig3({}, config3); - let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; - newConfig.headers = headers = AxiosHeaders$1.from(headers); - newConfig.url = buildURL2(buildFullPath2(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config3.params, config3.paramsSerializer); - if (auth) { - headers.set( - "Authorization", - "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : "")) - ); + if (delayedStream.pauseStream) { + source.pause(); } - let contentType; - if (utils$1.isFormData(data)) { - if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { - headers.setContentType(void 0); - } else if ((contentType = headers.getContentType()) !== false) { - const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; - headers.setContentType([type || "multipart/form-data", ...tokens].join("; ")); - } + return delayedStream; + }; + Object.defineProperty(DelayedStream.prototype, "readable", { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; } - if (platform.hasStandardBrowserEnv) { - withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); - if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) { - const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); - if (xsrfValue) { - headers.set(xsrfHeaderName, xsrfValue); - } - } + }); + DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); + }; + DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); } - return newConfig; + this.source.resume(); }; - var isXHRAdapterSupported2 = typeof XMLHttpRequest !== "undefined"; - var xhrAdapter = isXHRAdapterSupported2 && function(config3) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - const _config = resolveConfig(config3); - let requestData = _config.data; - const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); - let { responseType, onUploadProgress, onDownloadProgress } = _config; - let onCanceled; - let uploadThrottled, downloadThrottled; - let flushUpload, flushDownload; - function done() { - flushUpload && flushUpload(); - flushDownload && flushDownload(); - _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); - _config.signal && _config.signal.removeEventListener("abort", onCanceled); - } - let request = new XMLHttpRequest(); - request.open(_config.method.toUpperCase(), _config.url, true); - request.timeout = _config.timeout; - function onloadend() { - if (!request) { - return; - } - const responseHeaders = AxiosHeaders$1.from( - "getAllResponseHeaders" in request && request.getAllResponseHeaders() - ); - const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; - const response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config3, - request - }; - settle2(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); - request = null; - } - if ("onloadend" in request) { - request.onloadend = onloadend; - } else { - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { - return; - } - setTimeout(onloadend); - }; - } - request.onabort = function handleAbort() { - if (!request) { - return; - } - reject(new AxiosError3("Request aborted", AxiosError3.ECONNABORTED, config3, request)); - request = null; - }; - request.onerror = function handleError() { - reject(new AxiosError3("Network Error", AxiosError3.ERR_NETWORK, config3, request)); - request = null; - }; - request.ontimeout = function handleTimeout() { - let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded"; - const transitional2 = _config.transitional || transitionalDefaults; - if (_config.timeoutErrorMessage) { - timeoutErrorMessage = _config.timeoutErrorMessage; - } - reject(new AxiosError3( - timeoutErrorMessage, - transitional2.clarifyTimeoutError ? AxiosError3.ETIMEDOUT : AxiosError3.ECONNABORTED, - config3, - request - )); - request = null; - }; - requestData === void 0 && requestHeaders.setContentType(null); - if ("setRequestHeader" in request) { - utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { - request.setRequestHeader(key, val); - }); - } - if (!utils$1.isUndefined(_config.withCredentials)) { - request.withCredentials = !!_config.withCredentials; - } - if (responseType && responseType !== "json") { - request.responseType = _config.responseType; - } - if (onDownloadProgress) { - [downloadThrottled, flushDownload] = progressEventReducer2(onDownloadProgress, true); - request.addEventListener("progress", downloadThrottled); - } - if (onUploadProgress && request.upload) { - [uploadThrottled, flushUpload] = progressEventReducer2(onUploadProgress); - request.upload.addEventListener("progress", uploadThrottled); - request.upload.addEventListener("loadend", flushUpload); - } - if (_config.cancelToken || _config.signal) { - onCanceled = (cancel) => { - if (!request) { - return; - } - reject(!cancel || cancel.type ? new CanceledError3(null, config3, request) : cancel); - request.abort(); - request = null; - }; - _config.cancelToken && _config.cancelToken.subscribe(onCanceled); - if (_config.signal) { - _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled); - } - } - const protocol = parseProtocol2(_config.url); - if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError3("Unsupported protocol " + protocol + ":", AxiosError3.ERR_BAD_REQUEST, config3)); - return; - } - request.send(requestData || null); - }); + DelayedStream.prototype.pause = function() { + this.source.pause(); }; - var composeSignals2 = (signals, timeout) => { - const { length } = signals = signals ? signals.filter(Boolean) : []; - if (timeout || length) { - let controller = new AbortController(); - let aborted; - const onabort = function(reason) { - if (!aborted) { - aborted = true; - unsubscribe(); - const err = reason instanceof Error ? reason : this.reason; - controller.abort(err instanceof AxiosError3 ? err : new CanceledError3(err instanceof Error ? err.message : err)); - } - }; - let timer = timeout && setTimeout(() => { - timer = null; - onabort(new AxiosError3(`timeout ${timeout} of ms exceeded`, AxiosError3.ETIMEDOUT)); - }, timeout); - const unsubscribe = () => { - if (signals) { - timer && clearTimeout(timer); - timer = null; - signals.forEach((signal2) => { - signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort); - }); - signals = null; - } - }; - signals.forEach((signal2) => signal2.addEventListener("abort", onabort)); - const { signal } = controller; - signal.unsubscribe = () => utils$1.asap(unsubscribe); - return signal; - } + DelayedStream.prototype.release = function() { + this._released = true; + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; }; - var composeSignals$1 = composeSignals2; - var streamChunk2 = function* (chunk, chunkSize) { - let len = chunk.byteLength; - if (!chunkSize || len < chunkSize) { - yield chunk; + DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; + }; + DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); return; } - let pos = 0; - let end; - while (pos < len) { - end = pos + chunkSize; - yield chunk.slice(pos, end); - pos = end; - } - }; - var readBytes2 = async function* (iterable, chunkSize) { - for await (const chunk of readStream2(iterable)) { - yield* streamChunk2(chunk, chunkSize); + if (args[0] === "data") { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); } + this._bufferedEvents.push(args); }; - var readStream2 = async function* (stream5) { - if (stream5[Symbol.asyncIterator]) { - yield* stream5; + DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { return; } - const reader = stream5.getReader(); - try { - for (; ; ) { - const { done, value } = await reader.read(); - if (done) { - break; - } - yield value; - } - } finally { - await reader.cancel(); - } - }; - var trackStream2 = (stream5, chunkSize, onProgress, onFinish) => { - const iterator3 = readBytes2(stream5, chunkSize); - let bytes = 0; - let done; - let _onFinish = (e) => { - if (!done) { - done = true; - onFinish && onFinish(e); - } - }; - return new ReadableStream({ - async pull(controller) { - try { - const { done: done2, value } = await iterator3.next(); - if (done2) { - _onFinish(); - controller.close(); - return; - } - let len = value.byteLength; - if (onProgress) { - let loadedBytes = bytes += len; - onProgress(loadedBytes); - } - controller.enqueue(new Uint8Array(value)); - } catch (err) { - _onFinish(err); - throw err; - } - }, - cancel(reason) { - _onFinish(reason); - return iterator3.return(); - } - }, { - highWaterMark: 2 - }); - }; - var isFetchSupported2 = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function"; - var isReadableStreamSupported2 = isFetchSupported2 && typeof ReadableStream === "function"; - var encodeText2 = isFetchSupported2 && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder5) => (str) => encoder5.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Response(str).arrayBuffer())); - var test2 = (fn2, ...args) => { - try { - return !!fn2(...args); - } catch (e) { - return false; + if (this.dataSize <= this.maxDataSize) { + return; } + this._maxDataSizeExceeded = true; + var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; + this.emit("error", new Error(message)); }; - var supportsRequestStream2 = isReadableStreamSupported2 && test2(() => { - let duplexAccessed = false; - const hasContentType = new Request(platform.origin, { - body: new ReadableStream(), - method: "POST", - get duplex() { - duplexAccessed = true; - return "half"; - } - }).headers.has("Content-Type"); - return duplexAccessed && !hasContentType; - }); - var DEFAULT_CHUNK_SIZE2 = 64 * 1024; - var supportsResponseStream2 = isReadableStreamSupported2 && test2(() => utils$1.isReadableStream(new Response("").body)); - var resolvers2 = { - stream: supportsResponseStream2 && ((res) => res.body) - }; - isFetchSupported2 && ((res) => { - ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => { - !resolvers2[type] && (resolvers2[type] = utils$1.isFunction(res[type]) ? (res2) => res2[type]() : (_, config3) => { - throw new AxiosError3(`Response type '${type}' is not supported`, AxiosError3.ERR_NOT_SUPPORT, config3); - }); - }); - })(new Response()); - var getBodyLength2 = async (body) => { - if (body == null) { - return 0; - } - if (utils$1.isBlob(body)) { - return body.size; - } - if (utils$1.isSpecCompliantForm(body)) { - const _request = new Request(platform.origin, { - method: "POST", - body - }); - return (await _request.arrayBuffer()).byteLength; - } - if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { - return body.byteLength; - } - if (utils$1.isURLSearchParams(body)) { - body = body + ""; - } - if (utils$1.isString(body)) { - return (await encodeText2(body)).byteLength; + } +}); + +// node_modules/combined-stream/lib/combined_stream.js +var require_combined_stream = __commonJS({ + "node_modules/combined-stream/lib/combined_stream.js"(exports2, module2) { + var util3 = __require("util"); + var Stream = __require("stream").Stream; + var DelayedStream = require_delayed_stream(); + module2.exports = CombinedStream; + function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; + } + util3.inherits(CombinedStream, Stream); + CombinedStream.create = function(options) { + var combinedStream = new this(); + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; } - }; - var resolveBodyLength2 = async (headers, body) => { - const length = utils$1.toFiniteNumber(headers.getContentLength()); - return length == null ? getBodyLength2(body) : length; - }; - var fetchAdapter = isFetchSupported2 && (async (config3) => { - let { - url: url3, - method, - data, - signal, - cancelToken, - timeout, - onDownloadProgress, - onUploadProgress, - responseType, - headers, - withCredentials = "same-origin", - fetchOptions - } = resolveConfig(config3); - responseType = responseType ? (responseType + "").toLowerCase() : "text"; - let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); - let request; - const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { - composedSignal.unsubscribe(); - }); - let requestContentLength; - try { - if (onUploadProgress && supportsRequestStream2 && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength2(headers, data)) !== 0) { - let _request = new Request(url3, { - method: "POST", - body: data, - duplex: "half" - }); - let contentTypeHeader; - if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) { - headers.setContentType(contentTypeHeader); - } - if (_request.body) { - const [onProgress, flush] = progressEventDecorator2( - requestContentLength, - progressEventReducer2(asyncDecorator2(onUploadProgress)) - ); - data = trackStream2(_request.body, DEFAULT_CHUNK_SIZE2, onProgress, flush); - } - } - if (!utils$1.isString(withCredentials)) { - withCredentials = withCredentials ? "include" : "omit"; - } - const isCredentialsSupported = "credentials" in Request.prototype; - request = new Request(url3, { - ...fetchOptions, - signal: composedSignal, - method: method.toUpperCase(), - headers: headers.normalize().toJSON(), - body: data, - duplex: "half", - credentials: isCredentialsSupported ? withCredentials : void 0 - }); - let response = await fetch(request); - const isStreamResponse = supportsResponseStream2 && (responseType === "stream" || responseType === "response"); - if (supportsResponseStream2 && (onDownloadProgress || isStreamResponse && unsubscribe)) { - const options = {}; - ["status", "statusText", "headers"].forEach((prop) => { - options[prop] = response[prop]; - }); - const responseContentLength = utils$1.toFiniteNumber(response.headers.get("content-length")); - const [onProgress, flush] = onDownloadProgress && progressEventDecorator2( - responseContentLength, - progressEventReducer2(asyncDecorator2(onDownloadProgress), true) - ) || []; - response = new Response( - trackStream2(response.body, DEFAULT_CHUNK_SIZE2, onProgress, () => { - flush && flush(); - unsubscribe && unsubscribe(); - }), - options - ); - } - responseType = responseType || "text"; - let responseData = await resolvers2[utils$1.findKey(resolvers2, responseType) || "text"](response, config3); - !isStreamResponse && unsubscribe && unsubscribe(); - return await new Promise((resolve, reject) => { - settle2(resolve, reject, { - data: responseData, - headers: AxiosHeaders$1.from(response.headers), - status: response.status, - statusText: response.statusText, - config: config3, - request + return combinedStream; + }; + CombinedStream.isStreamLike = function(stream4) { + return typeof stream4 !== "function" && typeof stream4 !== "string" && typeof stream4 !== "boolean" && typeof stream4 !== "number" && !Buffer.isBuffer(stream4); + }; + CombinedStream.prototype.append = function(stream4) { + var isStreamLike = CombinedStream.isStreamLike(stream4); + if (isStreamLike) { + if (!(stream4 instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream4, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams }); - }); - } catch (err) { - unsubscribe && unsubscribe(); - if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) { - throw Object.assign( - new AxiosError3("Network Error", AxiosError3.ERR_NETWORK, config3, request), - { - cause: err.cause || err - } - ); + stream4.on("data", this._checkDataSize.bind(this)); + stream4 = newStream; + } + this._handleErrors(stream4); + if (this.pauseStreams) { + stream4.pause(); } - throw AxiosError3.from(err, err && err.code, config3, request); } - }); - var knownAdapters2 = { - http: httpAdapter2, - xhr: xhrAdapter, - fetch: fetchAdapter + this._streams.push(stream4); + return this; }; - utils$1.forEach(knownAdapters2, (fn2, value) => { - if (fn2) { - try { - Object.defineProperty(fn2, "name", { value }); - } catch (e) { - } - Object.defineProperty(fn2, "adapterName", { value }); + CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; + }; + CombinedStream.prototype._getNext = function() { + this._currentStream = null; + if (this._insideLoop) { + this._pendingNext = true; + return; } - }); - var renderReason2 = (reason) => `- ${reason}`; - var isResolvedHandle2 = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; - var adapters = { - getAdapter: (adapters2) => { - adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2]; - const { length } = adapters2; - let nameOrAdapter; - let adapter; - const rejectedReasons = {}; - for (let i = 0; i < length; i++) { - nameOrAdapter = adapters2[i]; - let id2; - adapter = nameOrAdapter; - if (!isResolvedHandle2(nameOrAdapter)) { - adapter = knownAdapters2[(id2 = String(nameOrAdapter)).toLowerCase()]; - if (adapter === void 0) { - throw new AxiosError3(`Unknown adapter '${id2}'`); - } - } - if (adapter) { - break; - } - rejectedReasons[id2 || "#" + i] = adapter; + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } + }; + CombinedStream.prototype._realGetNext = function() { + var stream4 = this._streams.shift(); + if (typeof stream4 == "undefined") { + this.end(); + return; + } + if (typeof stream4 !== "function") { + this._pipeNext(stream4); + return; + } + var getStream = stream4; + getStream(function(stream5) { + var isStreamLike = CombinedStream.isStreamLike(stream5); + if (isStreamLike) { + stream5.on("data", this._checkDataSize.bind(this)); + this._handleErrors(stream5); } - if (!adapter) { - const reasons = Object.entries(rejectedReasons).map( - ([id2, state]) => `adapter ${id2} ` + (state === false ? "is not supported by the environment" : "is not available in the build") - ); - let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason2).join("\n") : " " + renderReason2(reasons[0]) : "as no adapter specified"; - throw new AxiosError3( - `There is no suitable adapter to dispatch the request ` + s, - "ERR_NOT_SUPPORT" - ); + this._pipeNext(stream5); + }.bind(this)); + }; + CombinedStream.prototype._pipeNext = function(stream4) { + this._currentStream = stream4; + var isStreamLike = CombinedStream.isStreamLike(stream4); + if (isStreamLike) { + stream4.on("end", this._getNext.bind(this)); + stream4.pipe(this, { end: false }); + return; + } + var value = stream4; + this.write(value); + this._getNext(); + }; + CombinedStream.prototype._handleErrors = function(stream4) { + var self2 = this; + stream4.on("error", function(err) { + self2._emitError(err); + }); + }; + CombinedStream.prototype.write = function(data) { + this.emit("data", data); + }; + CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + if (this.pauseStreams && this._currentStream && typeof this._currentStream.pause == "function") this._currentStream.pause(); + this.emit("pause"); + }; + CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + if (this.pauseStreams && this._currentStream && typeof this._currentStream.resume == "function") this._currentStream.resume(); + this.emit("resume"); + }; + CombinedStream.prototype.end = function() { + this._reset(); + this.emit("end"); + }; + CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit("close"); + }; + CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; + }; + CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; + this._emitError(new Error(message)); + }; + CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + var self2 = this; + this._streams.forEach(function(stream4) { + if (!stream4.dataSize) { + return; } - return adapter; + self2.dataSize += stream4.dataSize; + }); + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } + }; + CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit("error", err); + }; + } +}); + +// node_modules/mime-db/db.json +var require_db = __commonJS({ + "node_modules/mime-db/db.json"(exports2, module2) { + module2.exports = { + "application/1d-interleaved-parityfec": { + source: "iana" + }, + "application/3gpdash-qoe-report+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/3gpp-ims+xml": { + source: "iana", + compressible: true + }, + "application/3gpphal+json": { + source: "iana", + compressible: true + }, + "application/3gpphalforms+json": { + source: "iana", + compressible: true + }, + "application/a2l": { + source: "iana" + }, + "application/ace+cbor": { + source: "iana" + }, + "application/activemessage": { + source: "iana" + }, + "application/activity+json": { + source: "iana", + compressible: true + }, + "application/alto-costmap+json": { + source: "iana", + compressible: true + }, + "application/alto-costmapfilter+json": { + source: "iana", + compressible: true + }, + "application/alto-directory+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointcost+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointcostparams+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointprop+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointpropparams+json": { + source: "iana", + compressible: true + }, + "application/alto-error+json": { + source: "iana", + compressible: true + }, + "application/alto-networkmap+json": { + source: "iana", + compressible: true + }, + "application/alto-networkmapfilter+json": { + source: "iana", + compressible: true + }, + "application/alto-updatestreamcontrol+json": { + source: "iana", + compressible: true + }, + "application/alto-updatestreamparams+json": { + source: "iana", + compressible: true + }, + "application/aml": { + source: "iana" + }, + "application/andrew-inset": { + source: "iana", + extensions: ["ez"] + }, + "application/applefile": { + source: "iana" + }, + "application/applixware": { + source: "apache", + extensions: ["aw"] + }, + "application/at+jwt": { + source: "iana" + }, + "application/atf": { + source: "iana" + }, + "application/atfx": { + source: "iana" + }, + "application/atom+xml": { + source: "iana", + compressible: true, + extensions: ["atom"] + }, + "application/atomcat+xml": { + source: "iana", + compressible: true, + extensions: ["atomcat"] + }, + "application/atomdeleted+xml": { + source: "iana", + compressible: true, + extensions: ["atomdeleted"] + }, + "application/atomicmail": { + source: "iana" + }, + "application/atomsvc+xml": { + source: "iana", + compressible: true, + extensions: ["atomsvc"] + }, + "application/atsc-dwd+xml": { + source: "iana", + compressible: true, + extensions: ["dwd"] + }, + "application/atsc-dynamic-event-message": { + source: "iana" + }, + "application/atsc-held+xml": { + source: "iana", + compressible: true, + extensions: ["held"] + }, + "application/atsc-rdt+json": { + source: "iana", + compressible: true + }, + "application/atsc-rsat+xml": { + source: "iana", + compressible: true, + extensions: ["rsat"] + }, + "application/atxml": { + source: "iana" + }, + "application/auth-policy+xml": { + source: "iana", + compressible: true + }, + "application/bacnet-xdd+zip": { + source: "iana", + compressible: false + }, + "application/batch-smtp": { + source: "iana" + }, + "application/bdoc": { + compressible: false, + extensions: ["bdoc"] + }, + "application/beep+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/calendar+json": { + source: "iana", + compressible: true + }, + "application/calendar+xml": { + source: "iana", + compressible: true, + extensions: ["xcs"] + }, + "application/call-completion": { + source: "iana" + }, + "application/cals-1840": { + source: "iana" + }, + "application/captive+json": { + source: "iana", + compressible: true + }, + "application/cbor": { + source: "iana" + }, + "application/cbor-seq": { + source: "iana" + }, + "application/cccex": { + source: "iana" + }, + "application/ccmp+xml": { + source: "iana", + compressible: true + }, + "application/ccxml+xml": { + source: "iana", + compressible: true, + extensions: ["ccxml"] + }, + "application/cdfx+xml": { + source: "iana", + compressible: true, + extensions: ["cdfx"] + }, + "application/cdmi-capability": { + source: "iana", + extensions: ["cdmia"] + }, + "application/cdmi-container": { + source: "iana", + extensions: ["cdmic"] + }, + "application/cdmi-domain": { + source: "iana", + extensions: ["cdmid"] + }, + "application/cdmi-object": { + source: "iana", + extensions: ["cdmio"] + }, + "application/cdmi-queue": { + source: "iana", + extensions: ["cdmiq"] + }, + "application/cdni": { + source: "iana" + }, + "application/cea": { + source: "iana" + }, + "application/cea-2018+xml": { + source: "iana", + compressible: true + }, + "application/cellml+xml": { + source: "iana", + compressible: true + }, + "application/cfw": { + source: "iana" + }, + "application/city+json": { + source: "iana", + compressible: true + }, + "application/clr": { + source: "iana" + }, + "application/clue+xml": { + source: "iana", + compressible: true + }, + "application/clue_info+xml": { + source: "iana", + compressible: true + }, + "application/cms": { + source: "iana" + }, + "application/cnrp+xml": { + source: "iana", + compressible: true + }, + "application/coap-group+json": { + source: "iana", + compressible: true + }, + "application/coap-payload": { + source: "iana" + }, + "application/commonground": { + source: "iana" + }, + "application/conference-info+xml": { + source: "iana", + compressible: true + }, + "application/cose": { + source: "iana" + }, + "application/cose-key": { + source: "iana" + }, + "application/cose-key-set": { + source: "iana" + }, + "application/cpl+xml": { + source: "iana", + compressible: true, + extensions: ["cpl"] + }, + "application/csrattrs": { + source: "iana" + }, + "application/csta+xml": { + source: "iana", + compressible: true + }, + "application/cstadata+xml": { + source: "iana", + compressible: true + }, + "application/csvm+json": { + source: "iana", + compressible: true + }, + "application/cu-seeme": { + source: "apache", + extensions: ["cu"] + }, + "application/cwt": { + source: "iana" + }, + "application/cybercash": { + source: "iana" + }, + "application/dart": { + compressible: true + }, + "application/dash+xml": { + source: "iana", + compressible: true, + extensions: ["mpd"] + }, + "application/dash-patch+xml": { + source: "iana", + compressible: true, + extensions: ["mpp"] + }, + "application/dashdelta": { + source: "iana" + }, + "application/davmount+xml": { + source: "iana", + compressible: true, + extensions: ["davmount"] + }, + "application/dca-rft": { + source: "iana" + }, + "application/dcd": { + source: "iana" + }, + "application/dec-dx": { + source: "iana" + }, + "application/dialog-info+xml": { + source: "iana", + compressible: true + }, + "application/dicom": { + source: "iana" + }, + "application/dicom+json": { + source: "iana", + compressible: true + }, + "application/dicom+xml": { + source: "iana", + compressible: true + }, + "application/dii": { + source: "iana" + }, + "application/dit": { + source: "iana" + }, + "application/dns": { + source: "iana" + }, + "application/dns+json": { + source: "iana", + compressible: true + }, + "application/dns-message": { + source: "iana" + }, + "application/docbook+xml": { + source: "apache", + compressible: true, + extensions: ["dbk"] + }, + "application/dots+cbor": { + source: "iana" + }, + "application/dskpp+xml": { + source: "iana", + compressible: true + }, + "application/dssc+der": { + source: "iana", + extensions: ["dssc"] + }, + "application/dssc+xml": { + source: "iana", + compressible: true, + extensions: ["xdssc"] + }, + "application/dvcs": { + source: "iana" + }, + "application/ecmascript": { + source: "iana", + compressible: true, + extensions: ["es", "ecma"] + }, + "application/edi-consent": { + source: "iana" + }, + "application/edi-x12": { + source: "iana", + compressible: false + }, + "application/edifact": { + source: "iana", + compressible: false + }, + "application/efi": { + source: "iana" + }, + "application/elm+json": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/elm+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.cap+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/emergencycalldata.comment+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.control+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.deviceinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.ecall.msd": { + source: "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.serviceinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.subscriberinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.veds+xml": { + source: "iana", + compressible: true + }, + "application/emma+xml": { + source: "iana", + compressible: true, + extensions: ["emma"] + }, + "application/emotionml+xml": { + source: "iana", + compressible: true, + extensions: ["emotionml"] + }, + "application/encaprtp": { + source: "iana" + }, + "application/epp+xml": { + source: "iana", + compressible: true + }, + "application/epub+zip": { + source: "iana", + compressible: false, + extensions: ["epub"] + }, + "application/eshop": { + source: "iana" + }, + "application/exi": { + source: "iana", + extensions: ["exi"] + }, + "application/expect-ct-report+json": { + source: "iana", + compressible: true + }, + "application/express": { + source: "iana", + extensions: ["exp"] + }, + "application/fastinfoset": { + source: "iana" + }, + "application/fastsoap": { + source: "iana" + }, + "application/fdt+xml": { + source: "iana", + compressible: true, + extensions: ["fdt"] + }, + "application/fhir+json": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/fhir+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/fido.trusted-apps+json": { + compressible: true + }, + "application/fits": { + source: "iana" + }, + "application/flexfec": { + source: "iana" + }, + "application/font-sfnt": { + source: "iana" + }, + "application/font-tdpfr": { + source: "iana", + extensions: ["pfr"] + }, + "application/font-woff": { + source: "iana", + compressible: false + }, + "application/framework-attributes+xml": { + source: "iana", + compressible: true + }, + "application/geo+json": { + source: "iana", + compressible: true, + extensions: ["geojson"] + }, + "application/geo+json-seq": { + source: "iana" + }, + "application/geopackage+sqlite3": { + source: "iana" + }, + "application/geoxacml+xml": { + source: "iana", + compressible: true + }, + "application/gltf-buffer": { + source: "iana" + }, + "application/gml+xml": { + source: "iana", + compressible: true, + extensions: ["gml"] + }, + "application/gpx+xml": { + source: "apache", + compressible: true, + extensions: ["gpx"] + }, + "application/gxf": { + source: "apache", + extensions: ["gxf"] + }, + "application/gzip": { + source: "iana", + compressible: false, + extensions: ["gz"] + }, + "application/h224": { + source: "iana" + }, + "application/held+xml": { + source: "iana", + compressible: true + }, + "application/hjson": { + extensions: ["hjson"] + }, + "application/http": { + source: "iana" + }, + "application/hyperstudio": { + source: "iana", + extensions: ["stk"] + }, + "application/ibe-key-request+xml": { + source: "iana", + compressible: true + }, + "application/ibe-pkg-reply+xml": { + source: "iana", + compressible: true + }, + "application/ibe-pp-data": { + source: "iana" + }, + "application/iges": { + source: "iana" + }, + "application/im-iscomposing+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/index": { + source: "iana" + }, + "application/index.cmd": { + source: "iana" + }, + "application/index.obj": { + source: "iana" + }, + "application/index.response": { + source: "iana" + }, + "application/index.vnd": { + source: "iana" + }, + "application/inkml+xml": { + source: "iana", + compressible: true, + extensions: ["ink", "inkml"] + }, + "application/iotp": { + source: "iana" + }, + "application/ipfix": { + source: "iana", + extensions: ["ipfix"] + }, + "application/ipp": { + source: "iana" + }, + "application/isup": { + source: "iana" + }, + "application/its+xml": { + source: "iana", + compressible: true, + extensions: ["its"] + }, + "application/java-archive": { + source: "apache", + compressible: false, + extensions: ["jar", "war", "ear"] + }, + "application/java-serialized-object": { + source: "apache", + compressible: false, + extensions: ["ser"] + }, + "application/java-vm": { + source: "apache", + compressible: false, + extensions: ["class"] + }, + "application/javascript": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["js", "mjs"] + }, + "application/jf2feed+json": { + source: "iana", + compressible: true + }, + "application/jose": { + source: "iana" + }, + "application/jose+json": { + source: "iana", + compressible: true + }, + "application/jrd+json": { + source: "iana", + compressible: true + }, + "application/jscalendar+json": { + source: "iana", + compressible: true + }, + "application/json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["json", "map"] + }, + "application/json-patch+json": { + source: "iana", + compressible: true + }, + "application/json-seq": { + source: "iana" + }, + "application/json5": { + extensions: ["json5"] + }, + "application/jsonml+json": { + source: "apache", + compressible: true, + extensions: ["jsonml"] + }, + "application/jwk+json": { + source: "iana", + compressible: true + }, + "application/jwk-set+json": { + source: "iana", + compressible: true + }, + "application/jwt": { + source: "iana" + }, + "application/kpml-request+xml": { + source: "iana", + compressible: true + }, + "application/kpml-response+xml": { + source: "iana", + compressible: true + }, + "application/ld+json": { + source: "iana", + compressible: true, + extensions: ["jsonld"] + }, + "application/lgr+xml": { + source: "iana", + compressible: true, + extensions: ["lgr"] + }, + "application/link-format": { + source: "iana" + }, + "application/load-control+xml": { + source: "iana", + compressible: true + }, + "application/lost+xml": { + source: "iana", + compressible: true, + extensions: ["lostxml"] + }, + "application/lostsync+xml": { + source: "iana", + compressible: true + }, + "application/lpf+zip": { + source: "iana", + compressible: false + }, + "application/lxf": { + source: "iana" + }, + "application/mac-binhex40": { + source: "iana", + extensions: ["hqx"] + }, + "application/mac-compactpro": { + source: "apache", + extensions: ["cpt"] + }, + "application/macwriteii": { + source: "iana" + }, + "application/mads+xml": { + source: "iana", + compressible: true, + extensions: ["mads"] + }, + "application/manifest+json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["webmanifest"] + }, + "application/marc": { + source: "iana", + extensions: ["mrc"] + }, + "application/marcxml+xml": { + source: "iana", + compressible: true, + extensions: ["mrcx"] + }, + "application/mathematica": { + source: "iana", + extensions: ["ma", "nb", "mb"] + }, + "application/mathml+xml": { + source: "iana", + compressible: true, + extensions: ["mathml"] + }, + "application/mathml-content+xml": { + source: "iana", + compressible: true + }, + "application/mathml-presentation+xml": { + source: "iana", + compressible: true + }, + "application/mbms-associated-procedure-description+xml": { + source: "iana", + compressible: true + }, + "application/mbms-deregister+xml": { + source: "iana", + compressible: true + }, + "application/mbms-envelope+xml": { + source: "iana", + compressible: true + }, + "application/mbms-msk+xml": { + source: "iana", + compressible: true + }, + "application/mbms-msk-response+xml": { + source: "iana", + compressible: true + }, + "application/mbms-protection-description+xml": { + source: "iana", + compressible: true + }, + "application/mbms-reception-report+xml": { + source: "iana", + compressible: true + }, + "application/mbms-register+xml": { + source: "iana", + compressible: true + }, + "application/mbms-register-response+xml": { + source: "iana", + compressible: true + }, + "application/mbms-schedule+xml": { + source: "iana", + compressible: true + }, + "application/mbms-user-service-description+xml": { + source: "iana", + compressible: true + }, + "application/mbox": { + source: "iana", + extensions: ["mbox"] + }, + "application/media-policy-dataset+xml": { + source: "iana", + compressible: true, + extensions: ["mpf"] + }, + "application/media_control+xml": { + source: "iana", + compressible: true + }, + "application/mediaservercontrol+xml": { + source: "iana", + compressible: true, + extensions: ["mscml"] + }, + "application/merge-patch+json": { + source: "iana", + compressible: true + }, + "application/metalink+xml": { + source: "apache", + compressible: true, + extensions: ["metalink"] + }, + "application/metalink4+xml": { + source: "iana", + compressible: true, + extensions: ["meta4"] + }, + "application/mets+xml": { + source: "iana", + compressible: true, + extensions: ["mets"] + }, + "application/mf4": { + source: "iana" + }, + "application/mikey": { + source: "iana" + }, + "application/mipc": { + source: "iana" + }, + "application/missing-blocks+cbor-seq": { + source: "iana" + }, + "application/mmt-aei+xml": { + source: "iana", + compressible: true, + extensions: ["maei"] + }, + "application/mmt-usd+xml": { + source: "iana", + compressible: true, + extensions: ["musd"] + }, + "application/mods+xml": { + source: "iana", + compressible: true, + extensions: ["mods"] + }, + "application/moss-keys": { + source: "iana" + }, + "application/moss-signature": { + source: "iana" + }, + "application/mosskey-data": { + source: "iana" + }, + "application/mosskey-request": { + source: "iana" + }, + "application/mp21": { + source: "iana", + extensions: ["m21", "mp21"] + }, + "application/mp4": { + source: "iana", + extensions: ["mp4s", "m4p"] + }, + "application/mpeg4-generic": { + source: "iana" + }, + "application/mpeg4-iod": { + source: "iana" + }, + "application/mpeg4-iod-xmt": { + source: "iana" + }, + "application/mrb-consumer+xml": { + source: "iana", + compressible: true + }, + "application/mrb-publish+xml": { + source: "iana", + compressible: true + }, + "application/msc-ivr+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/msc-mixer+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/msword": { + source: "iana", + compressible: false, + extensions: ["doc", "dot"] + }, + "application/mud+json": { + source: "iana", + compressible: true + }, + "application/multipart-core": { + source: "iana" + }, + "application/mxf": { + source: "iana", + extensions: ["mxf"] + }, + "application/n-quads": { + source: "iana", + extensions: ["nq"] + }, + "application/n-triples": { + source: "iana", + extensions: ["nt"] + }, + "application/nasdata": { + source: "iana" + }, + "application/news-checkgroups": { + source: "iana", + charset: "US-ASCII" + }, + "application/news-groupinfo": { + source: "iana", + charset: "US-ASCII" + }, + "application/news-transmission": { + source: "iana" + }, + "application/nlsml+xml": { + source: "iana", + compressible: true + }, + "application/node": { + source: "iana", + extensions: ["cjs"] + }, + "application/nss": { + source: "iana" + }, + "application/oauth-authz-req+jwt": { + source: "iana" + }, + "application/oblivious-dns-message": { + source: "iana" + }, + "application/ocsp-request": { + source: "iana" + }, + "application/ocsp-response": { + source: "iana" + }, + "application/octet-stream": { + source: "iana", + compressible: false, + extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"] + }, + "application/oda": { + source: "iana", + extensions: ["oda"] + }, + "application/odm+xml": { + source: "iana", + compressible: true + }, + "application/odx": { + source: "iana" + }, + "application/oebps-package+xml": { + source: "iana", + compressible: true, + extensions: ["opf"] + }, + "application/ogg": { + source: "iana", + compressible: false, + extensions: ["ogx"] + }, + "application/omdoc+xml": { + source: "apache", + compressible: true, + extensions: ["omdoc"] + }, + "application/onenote": { + source: "apache", + extensions: ["onetoc", "onetoc2", "onetmp", "onepkg"] + }, + "application/opc-nodeset+xml": { + source: "iana", + compressible: true + }, + "application/oscore": { + source: "iana" + }, + "application/oxps": { + source: "iana", + extensions: ["oxps"] + }, + "application/p21": { + source: "iana" + }, + "application/p21+zip": { + source: "iana", + compressible: false + }, + "application/p2p-overlay+xml": { + source: "iana", + compressible: true, + extensions: ["relo"] + }, + "application/parityfec": { + source: "iana" + }, + "application/passport": { + source: "iana" + }, + "application/patch-ops-error+xml": { + source: "iana", + compressible: true, + extensions: ["xer"] + }, + "application/pdf": { + source: "iana", + compressible: false, + extensions: ["pdf"] + }, + "application/pdx": { + source: "iana" + }, + "application/pem-certificate-chain": { + source: "iana" + }, + "application/pgp-encrypted": { + source: "iana", + compressible: false, + extensions: ["pgp"] + }, + "application/pgp-keys": { + source: "iana", + extensions: ["asc"] + }, + "application/pgp-signature": { + source: "iana", + extensions: ["asc", "sig"] + }, + "application/pics-rules": { + source: "apache", + extensions: ["prf"] + }, + "application/pidf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/pidf-diff+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/pkcs10": { + source: "iana", + extensions: ["p10"] + }, + "application/pkcs12": { + source: "iana" + }, + "application/pkcs7-mime": { + source: "iana", + extensions: ["p7m", "p7c"] + }, + "application/pkcs7-signature": { + source: "iana", + extensions: ["p7s"] + }, + "application/pkcs8": { + source: "iana", + extensions: ["p8"] + }, + "application/pkcs8-encrypted": { + source: "iana" + }, + "application/pkix-attr-cert": { + source: "iana", + extensions: ["ac"] + }, + "application/pkix-cert": { + source: "iana", + extensions: ["cer"] + }, + "application/pkix-crl": { + source: "iana", + extensions: ["crl"] + }, + "application/pkix-pkipath": { + source: "iana", + extensions: ["pkipath"] + }, + "application/pkixcmp": { + source: "iana", + extensions: ["pki"] + }, + "application/pls+xml": { + source: "iana", + compressible: true, + extensions: ["pls"] + }, + "application/poc-settings+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/postscript": { + source: "iana", + compressible: true, + extensions: ["ai", "eps", "ps"] + }, + "application/ppsp-tracker+json": { + source: "iana", + compressible: true + }, + "application/problem+json": { + source: "iana", + compressible: true + }, + "application/problem+xml": { + source: "iana", + compressible: true + }, + "application/provenance+xml": { + source: "iana", + compressible: true, + extensions: ["provx"] + }, + "application/prs.alvestrand.titrax-sheet": { + source: "iana" + }, + "application/prs.cww": { + source: "iana", + extensions: ["cww"] + }, + "application/prs.cyn": { + source: "iana", + charset: "7-BIT" + }, + "application/prs.hpub+zip": { + source: "iana", + compressible: false + }, + "application/prs.nprend": { + source: "iana" + }, + "application/prs.plucker": { + source: "iana" + }, + "application/prs.rdf-xml-crypt": { + source: "iana" + }, + "application/prs.xsf+xml": { + source: "iana", + compressible: true + }, + "application/pskc+xml": { + source: "iana", + compressible: true, + extensions: ["pskcxml"] + }, + "application/pvd+json": { + source: "iana", + compressible: true + }, + "application/qsig": { + source: "iana" + }, + "application/raml+yaml": { + compressible: true, + extensions: ["raml"] + }, + "application/raptorfec": { + source: "iana" + }, + "application/rdap+json": { + source: "iana", + compressible: true + }, + "application/rdf+xml": { + source: "iana", + compressible: true, + extensions: ["rdf", "owl"] + }, + "application/reginfo+xml": { + source: "iana", + compressible: true, + extensions: ["rif"] + }, + "application/relax-ng-compact-syntax": { + source: "iana", + extensions: ["rnc"] + }, + "application/remote-printing": { + source: "iana" + }, + "application/reputon+json": { + source: "iana", + compressible: true + }, + "application/resource-lists+xml": { + source: "iana", + compressible: true, + extensions: ["rl"] + }, + "application/resource-lists-diff+xml": { + source: "iana", + compressible: true, + extensions: ["rld"] + }, + "application/rfc+xml": { + source: "iana", + compressible: true + }, + "application/riscos": { + source: "iana" + }, + "application/rlmi+xml": { + source: "iana", + compressible: true + }, + "application/rls-services+xml": { + source: "iana", + compressible: true, + extensions: ["rs"] + }, + "application/route-apd+xml": { + source: "iana", + compressible: true, + extensions: ["rapd"] + }, + "application/route-s-tsid+xml": { + source: "iana", + compressible: true, + extensions: ["sls"] + }, + "application/route-usd+xml": { + source: "iana", + compressible: true, + extensions: ["rusd"] + }, + "application/rpki-ghostbusters": { + source: "iana", + extensions: ["gbr"] + }, + "application/rpki-manifest": { + source: "iana", + extensions: ["mft"] + }, + "application/rpki-publication": { + source: "iana" + }, + "application/rpki-roa": { + source: "iana", + extensions: ["roa"] + }, + "application/rpki-updown": { + source: "iana" + }, + "application/rsd+xml": { + source: "apache", + compressible: true, + extensions: ["rsd"] + }, + "application/rss+xml": { + source: "apache", + compressible: true, + extensions: ["rss"] + }, + "application/rtf": { + source: "iana", + compressible: true, + extensions: ["rtf"] + }, + "application/rtploopback": { + source: "iana" + }, + "application/rtx": { + source: "iana" + }, + "application/samlassertion+xml": { + source: "iana", + compressible: true + }, + "application/samlmetadata+xml": { + source: "iana", + compressible: true + }, + "application/sarif+json": { + source: "iana", + compressible: true + }, + "application/sarif-external-properties+json": { + source: "iana", + compressible: true + }, + "application/sbe": { + source: "iana" + }, + "application/sbml+xml": { + source: "iana", + compressible: true, + extensions: ["sbml"] + }, + "application/scaip+xml": { + source: "iana", + compressible: true + }, + "application/scim+json": { + source: "iana", + compressible: true + }, + "application/scvp-cv-request": { + source: "iana", + extensions: ["scq"] + }, + "application/scvp-cv-response": { + source: "iana", + extensions: ["scs"] + }, + "application/scvp-vp-request": { + source: "iana", + extensions: ["spq"] + }, + "application/scvp-vp-response": { + source: "iana", + extensions: ["spp"] + }, + "application/sdp": { + source: "iana", + extensions: ["sdp"] + }, + "application/secevent+jwt": { + source: "iana" + }, + "application/senml+cbor": { + source: "iana" + }, + "application/senml+json": { + source: "iana", + compressible: true + }, + "application/senml+xml": { + source: "iana", + compressible: true, + extensions: ["senmlx"] + }, + "application/senml-etch+cbor": { + source: "iana" + }, + "application/senml-etch+json": { + source: "iana", + compressible: true + }, + "application/senml-exi": { + source: "iana" + }, + "application/sensml+cbor": { + source: "iana" + }, + "application/sensml+json": { + source: "iana", + compressible: true + }, + "application/sensml+xml": { + source: "iana", + compressible: true, + extensions: ["sensmlx"] + }, + "application/sensml-exi": { + source: "iana" + }, + "application/sep+xml": { + source: "iana", + compressible: true + }, + "application/sep-exi": { + source: "iana" + }, + "application/session-info": { + source: "iana" + }, + "application/set-payment": { + source: "iana" + }, + "application/set-payment-initiation": { + source: "iana", + extensions: ["setpay"] + }, + "application/set-registration": { + source: "iana" + }, + "application/set-registration-initiation": { + source: "iana", + extensions: ["setreg"] + }, + "application/sgml": { + source: "iana" + }, + "application/sgml-open-catalog": { + source: "iana" + }, + "application/shf+xml": { + source: "iana", + compressible: true, + extensions: ["shf"] + }, + "application/sieve": { + source: "iana", + extensions: ["siv", "sieve"] + }, + "application/simple-filter+xml": { + source: "iana", + compressible: true + }, + "application/simple-message-summary": { + source: "iana" + }, + "application/simplesymbolcontainer": { + source: "iana" + }, + "application/sipc": { + source: "iana" + }, + "application/slate": { + source: "iana" + }, + "application/smil": { + source: "iana" + }, + "application/smil+xml": { + source: "iana", + compressible: true, + extensions: ["smi", "smil"] + }, + "application/smpte336m": { + source: "iana" + }, + "application/soap+fastinfoset": { + source: "iana" + }, + "application/soap+xml": { + source: "iana", + compressible: true + }, + "application/sparql-query": { + source: "iana", + extensions: ["rq"] + }, + "application/sparql-results+xml": { + source: "iana", + compressible: true, + extensions: ["srx"] + }, + "application/spdx+json": { + source: "iana", + compressible: true + }, + "application/spirits-event+xml": { + source: "iana", + compressible: true + }, + "application/sql": { + source: "iana" + }, + "application/srgs": { + source: "iana", + extensions: ["gram"] + }, + "application/srgs+xml": { + source: "iana", + compressible: true, + extensions: ["grxml"] + }, + "application/sru+xml": { + source: "iana", + compressible: true, + extensions: ["sru"] + }, + "application/ssdl+xml": { + source: "apache", + compressible: true, + extensions: ["ssdl"] + }, + "application/ssml+xml": { + source: "iana", + compressible: true, + extensions: ["ssml"] + }, + "application/stix+json": { + source: "iana", + compressible: true + }, + "application/swid+xml": { + source: "iana", + compressible: true, + extensions: ["swidtag"] + }, + "application/tamp-apex-update": { + source: "iana" + }, + "application/tamp-apex-update-confirm": { + source: "iana" + }, + "application/tamp-community-update": { + source: "iana" + }, + "application/tamp-community-update-confirm": { + source: "iana" + }, + "application/tamp-error": { + source: "iana" + }, + "application/tamp-sequence-adjust": { + source: "iana" + }, + "application/tamp-sequence-adjust-confirm": { + source: "iana" + }, + "application/tamp-status-query": { + source: "iana" + }, + "application/tamp-status-response": { + source: "iana" + }, + "application/tamp-update": { + source: "iana" + }, + "application/tamp-update-confirm": { + source: "iana" + }, + "application/tar": { + compressible: true + }, + "application/taxii+json": { + source: "iana", + compressible: true + }, + "application/td+json": { + source: "iana", + compressible: true + }, + "application/tei+xml": { + source: "iana", + compressible: true, + extensions: ["tei", "teicorpus"] + }, + "application/tetra_isi": { + source: "iana" + }, + "application/thraud+xml": { + source: "iana", + compressible: true, + extensions: ["tfi"] + }, + "application/timestamp-query": { + source: "iana" + }, + "application/timestamp-reply": { + source: "iana" + }, + "application/timestamped-data": { + source: "iana", + extensions: ["tsd"] + }, + "application/tlsrpt+gzip": { + source: "iana" + }, + "application/tlsrpt+json": { + source: "iana", + compressible: true + }, + "application/tnauthlist": { + source: "iana" + }, + "application/token-introspection+jwt": { + source: "iana" + }, + "application/toml": { + compressible: true, + extensions: ["toml"] + }, + "application/trickle-ice-sdpfrag": { + source: "iana" + }, + "application/trig": { + source: "iana", + extensions: ["trig"] + }, + "application/ttml+xml": { + source: "iana", + compressible: true, + extensions: ["ttml"] + }, + "application/tve-trigger": { + source: "iana" + }, + "application/tzif": { + source: "iana" + }, + "application/tzif-leap": { + source: "iana" + }, + "application/ubjson": { + compressible: false, + extensions: ["ubj"] + }, + "application/ulpfec": { + source: "iana" + }, + "application/urc-grpsheet+xml": { + source: "iana", + compressible: true + }, + "application/urc-ressheet+xml": { + source: "iana", + compressible: true, + extensions: ["rsheet"] + }, + "application/urc-targetdesc+xml": { + source: "iana", + compressible: true, + extensions: ["td"] + }, + "application/urc-uisocketdesc+xml": { + source: "iana", + compressible: true + }, + "application/vcard+json": { + source: "iana", + compressible: true + }, + "application/vcard+xml": { + source: "iana", + compressible: true + }, + "application/vemmi": { + source: "iana" + }, + "application/vividence.scriptfile": { + source: "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + source: "iana", + compressible: true, + extensions: ["1km"] + }, + "application/vnd.3gpp-prose+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-v2x-local-service-information": { + source: "iana" + }, + "application/vnd.3gpp.5gnas": { + source: "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.bsf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.gmop+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.gtpc": { + source: "iana" + }, + "application/vnd.3gpp.interworking-data": { + source: "iana" + }, + "application/vnd.3gpp.lpp": { + source: "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-payload": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-signalling": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mid-call+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.ngap": { + source: "iana" + }, + "application/vnd.3gpp.pfcp": { + source: "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + source: "iana", + extensions: ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + source: "iana", + extensions: ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + source: "iana", + extensions: ["pvb"] + }, + "application/vnd.3gpp.s1ap": { + source: "iana" + }, + "application/vnd.3gpp.sms": { + source: "iana" + }, + "application/vnd.3gpp.sms+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.srvcc-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.ussd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp2.sms": { + source: "iana" + }, + "application/vnd.3gpp2.tcap": { + source: "iana", + extensions: ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + source: "iana" + }, + "application/vnd.3m.post-it-notes": { + source: "iana", + extensions: ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + source: "iana", + extensions: ["aso"] + }, + "application/vnd.accpac.simply.imp": { + source: "iana", + extensions: ["imp"] + }, + "application/vnd.acucobol": { + source: "iana", + extensions: ["acu"] + }, + "application/vnd.acucorp": { + source: "iana", + extensions: ["atc", "acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + source: "apache", + compressible: false, + extensions: ["air"] + }, + "application/vnd.adobe.flash.movie": { + source: "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + source: "iana", + extensions: ["fcdt"] + }, + "application/vnd.adobe.fxp": { + source: "iana", + extensions: ["fxp", "fxpl"] + }, + "application/vnd.adobe.partial-upload": { + source: "iana" + }, + "application/vnd.adobe.xdp+xml": { + source: "iana", + compressible: true, + extensions: ["xdp"] + }, + "application/vnd.adobe.xfdf": { + source: "iana", + extensions: ["xfdf"] + }, + "application/vnd.aether.imp": { + source: "iana" + }, + "application/vnd.afpc.afplinedata": { + source: "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + source: "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + source: "iana" + }, + "application/vnd.afpc.foca-charset": { + source: "iana" + }, + "application/vnd.afpc.foca-codedfont": { + source: "iana" + }, + "application/vnd.afpc.foca-codepage": { + source: "iana" + }, + "application/vnd.afpc.modca": { + source: "iana" + }, + "application/vnd.afpc.modca-cmtable": { + source: "iana" + }, + "application/vnd.afpc.modca-formdef": { + source: "iana" + }, + "application/vnd.afpc.modca-mediummap": { + source: "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + source: "iana" + }, + "application/vnd.afpc.modca-overlay": { + source: "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + source: "iana" + }, + "application/vnd.age": { + source: "iana", + extensions: ["age"] + }, + "application/vnd.ah-barcode": { + source: "iana" + }, + "application/vnd.ahead.space": { + source: "iana", + extensions: ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + source: "iana", + extensions: ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + source: "iana", + extensions: ["azs"] + }, + "application/vnd.amadeus+json": { + source: "iana", + compressible: true + }, + "application/vnd.amazon.ebook": { + source: "apache", + extensions: ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + source: "iana" + }, + "application/vnd.americandynamics.acc": { + source: "iana", + extensions: ["acc"] + }, + "application/vnd.amiga.ami": { + source: "iana", + extensions: ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + source: "iana", + compressible: true + }, + "application/vnd.android.ota": { + source: "iana" + }, + "application/vnd.android.package-archive": { + source: "apache", + compressible: false, + extensions: ["apk"] + }, + "application/vnd.anki": { + source: "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + source: "iana", + extensions: ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + source: "apache", + extensions: ["fti"] + }, + "application/vnd.antix.game-component": { + source: "iana", + extensions: ["atx"] + }, + "application/vnd.apache.arrow.file": { + source: "iana" + }, + "application/vnd.apache.arrow.stream": { + source: "iana" + }, + "application/vnd.apache.thrift.binary": { + source: "iana" + }, + "application/vnd.apache.thrift.compact": { + source: "iana" + }, + "application/vnd.apache.thrift.json": { + source: "iana" + }, + "application/vnd.api+json": { + source: "iana", + compressible: true + }, + "application/vnd.aplextor.warrp+json": { + source: "iana", + compressible: true + }, + "application/vnd.apothekende.reservation+json": { + source: "iana", + compressible: true + }, + "application/vnd.apple.installer+xml": { + source: "iana", + compressible: true, + extensions: ["mpkg"] + }, + "application/vnd.apple.keynote": { + source: "iana", + extensions: ["key"] + }, + "application/vnd.apple.mpegurl": { + source: "iana", + extensions: ["m3u8"] + }, + "application/vnd.apple.numbers": { + source: "iana", + extensions: ["numbers"] + }, + "application/vnd.apple.pages": { + source: "iana", + extensions: ["pages"] + }, + "application/vnd.apple.pkpass": { + compressible: false, + extensions: ["pkpass"] + }, + "application/vnd.arastra.swi": { + source: "iana" + }, + "application/vnd.aristanetworks.swi": { + source: "iana", + extensions: ["swi"] + }, + "application/vnd.artisan+json": { + source: "iana", + compressible: true + }, + "application/vnd.artsquare": { + source: "iana" + }, + "application/vnd.astraea-software.iota": { + source: "iana", + extensions: ["iota"] + }, + "application/vnd.audiograph": { + source: "iana", + extensions: ["aep"] + }, + "application/vnd.autopackage": { + source: "iana" + }, + "application/vnd.avalon+json": { + source: "iana", + compressible: true + }, + "application/vnd.avistar+xml": { + source: "iana", + compressible: true + }, + "application/vnd.balsamiq.bmml+xml": { + source: "iana", + compressible: true, + extensions: ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + source: "iana" + }, + "application/vnd.banana-accounting": { + source: "iana" + }, + "application/vnd.bbf.usp.error": { + source: "iana" + }, + "application/vnd.bbf.usp.msg": { + source: "iana" + }, + "application/vnd.bbf.usp.msg+json": { + source: "iana", + compressible: true + }, + "application/vnd.bekitzur-stech+json": { + source: "iana", + compressible: true + }, + "application/vnd.bint.med-content": { + source: "iana" + }, + "application/vnd.biopax.rdf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.blink-idb-value-wrapper": { + source: "iana" + }, + "application/vnd.blueice.multipass": { + source: "iana", + extensions: ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + source: "iana" + }, + "application/vnd.bluetooth.le.oob": { + source: "iana" + }, + "application/vnd.bmi": { + source: "iana", + extensions: ["bmi"] + }, + "application/vnd.bpf": { + source: "iana" + }, + "application/vnd.bpf3": { + source: "iana" + }, + "application/vnd.businessobjects": { + source: "iana", + extensions: ["rep"] + }, + "application/vnd.byu.uapi+json": { + source: "iana", + compressible: true + }, + "application/vnd.cab-jscript": { + source: "iana" + }, + "application/vnd.canon-cpdl": { + source: "iana" + }, + "application/vnd.canon-lips": { + source: "iana" + }, + "application/vnd.capasystems-pg+json": { + source: "iana", + compressible: true + }, + "application/vnd.cendio.thinlinc.clientconf": { + source: "iana" + }, + "application/vnd.century-systems.tcp_stream": { + source: "iana" + }, + "application/vnd.chemdraw+xml": { + source: "iana", + compressible: true, + extensions: ["cdxml"] + }, + "application/vnd.chess-pgn": { + source: "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + source: "iana", + extensions: ["mmd"] + }, + "application/vnd.ciedi": { + source: "iana" + }, + "application/vnd.cinderella": { + source: "iana", + extensions: ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + source: "iana" + }, + "application/vnd.citationstyles.style+xml": { + source: "iana", + compressible: true, + extensions: ["csl"] + }, + "application/vnd.claymore": { + source: "iana", + extensions: ["cla"] + }, + "application/vnd.cloanto.rp9": { + source: "iana", + extensions: ["rp9"] + }, + "application/vnd.clonk.c4group": { + source: "iana", + extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + source: "iana", + extensions: ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + source: "iana", + extensions: ["c11amz"] + }, + "application/vnd.coffeescript": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.document": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + source: "iana" + }, + "application/vnd.collection+json": { + source: "iana", + compressible: true + }, + "application/vnd.collection.doc+json": { + source: "iana", + compressible: true + }, + "application/vnd.collection.next+json": { + source: "iana", + compressible: true + }, + "application/vnd.comicbook+zip": { + source: "iana", + compressible: false + }, + "application/vnd.comicbook-rar": { + source: "iana" + }, + "application/vnd.commerce-battelle": { + source: "iana" + }, + "application/vnd.commonspace": { + source: "iana", + extensions: ["csp"] + }, + "application/vnd.contact.cmsg": { + source: "iana", + extensions: ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + source: "iana", + compressible: true + }, + "application/vnd.cosmocaller": { + source: "iana", + extensions: ["cmc"] + }, + "application/vnd.crick.clicker": { + source: "iana", + extensions: ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + source: "iana", + extensions: ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + source: "iana", + extensions: ["clkp"] + }, + "application/vnd.crick.clicker.template": { + source: "iana", + extensions: ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + source: "iana", + extensions: ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + source: "iana", + compressible: true, + extensions: ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + source: "iana", + compressible: true + }, + "application/vnd.crypto-shade-file": { + source: "iana" + }, + "application/vnd.cryptomator.encrypted": { + source: "iana" + }, + "application/vnd.cryptomator.vault": { + source: "iana" + }, + "application/vnd.ctc-posml": { + source: "iana", + extensions: ["pml"] + }, + "application/vnd.ctct.ws+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cups-pdf": { + source: "iana" + }, + "application/vnd.cups-postscript": { + source: "iana" + }, + "application/vnd.cups-ppd": { + source: "iana", + extensions: ["ppd"] + }, + "application/vnd.cups-raster": { + source: "iana" + }, + "application/vnd.cups-raw": { + source: "iana" + }, + "application/vnd.curl": { + source: "iana" + }, + "application/vnd.curl.car": { + source: "apache", + extensions: ["car"] + }, + "application/vnd.curl.pcurl": { + source: "apache", + extensions: ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cybank": { + source: "iana" + }, + "application/vnd.cyclonedx+json": { + source: "iana", + compressible: true + }, + "application/vnd.cyclonedx+xml": { + source: "iana", + compressible: true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + source: "iana", + compressible: false + }, + "application/vnd.d3m-dataset": { + source: "iana" + }, + "application/vnd.d3m-problem": { + source: "iana" + }, + "application/vnd.dart": { + source: "iana", + compressible: true, + extensions: ["dart"] + }, + "application/vnd.data-vision.rdz": { + source: "iana", + extensions: ["rdz"] + }, + "application/vnd.datapackage+json": { + source: "iana", + compressible: true + }, + "application/vnd.dataresource+json": { + source: "iana", + compressible: true + }, + "application/vnd.dbf": { + source: "iana", + extensions: ["dbf"] + }, + "application/vnd.debian.binary-package": { + source: "iana" + }, + "application/vnd.dece.data": { + source: "iana", + extensions: ["uvf", "uvvf", "uvd", "uvvd"] + }, + "application/vnd.dece.ttml+xml": { + source: "iana", + compressible: true, + extensions: ["uvt", "uvvt"] + }, + "application/vnd.dece.unspecified": { + source: "iana", + extensions: ["uvx", "uvvx"] + }, + "application/vnd.dece.zip": { + source: "iana", + extensions: ["uvz", "uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + source: "iana", + extensions: ["fe_launch"] + }, + "application/vnd.desmume.movie": { + source: "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + source: "iana" + }, + "application/vnd.dm.delegation+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dna": { + source: "iana", + extensions: ["dna"] + }, + "application/vnd.document+json": { + source: "iana", + compressible: true + }, + "application/vnd.dolby.mlp": { + source: "apache", + extensions: ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + source: "iana" + }, + "application/vnd.dolby.mobile.2": { + source: "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + source: "iana" + }, + "application/vnd.dpgraph": { + source: "iana", + extensions: ["dpg"] + }, + "application/vnd.dreamfactory": { + source: "iana", + extensions: ["dfac"] + }, + "application/vnd.drive+json": { + source: "iana", + compressible: true + }, + "application/vnd.ds-keypoint": { + source: "apache", + extensions: ["kpxx"] + }, + "application/vnd.dtg.local": { + source: "iana" + }, + "application/vnd.dtg.local.flash": { + source: "iana" + }, + "application/vnd.dtg.local.html": { + source: "iana" + }, + "application/vnd.dvb.ait": { + source: "iana", + extensions: ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.dvbj": { + source: "iana" + }, + "application/vnd.dvb.esgcontainer": { + source: "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + source: "iana" + }, + "application/vnd.dvb.ipdcroaming": { + source: "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + source: "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + source: "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-container+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-generic+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-init+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.pfr": { + source: "iana" + }, + "application/vnd.dvb.service": { + source: "iana", + extensions: ["svc"] + }, + "application/vnd.dxr": { + source: "iana" + }, + "application/vnd.dynageo": { + source: "iana", + extensions: ["geo"] + }, + "application/vnd.dzr": { + source: "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + source: "iana" + }, + "application/vnd.ecdis-update": { + source: "iana" + }, + "application/vnd.ecip.rlp": { + source: "iana" + }, + "application/vnd.eclipse.ditto+json": { + source: "iana", + compressible: true + }, + "application/vnd.ecowin.chart": { + source: "iana", + extensions: ["mag"] + }, + "application/vnd.ecowin.filerequest": { + source: "iana" + }, + "application/vnd.ecowin.fileupdate": { + source: "iana" + }, + "application/vnd.ecowin.series": { + source: "iana" + }, + "application/vnd.ecowin.seriesrequest": { + source: "iana" + }, + "application/vnd.ecowin.seriesupdate": { + source: "iana" + }, + "application/vnd.efi.img": { + source: "iana" + }, + "application/vnd.efi.iso": { + source: "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + source: "iana", + compressible: true + }, + "application/vnd.enliven": { + source: "iana", + extensions: ["nml"] + }, + "application/vnd.enphase.envoy": { + source: "iana" + }, + "application/vnd.eprints.data+xml": { + source: "iana", + compressible: true + }, + "application/vnd.epson.esf": { + source: "iana", + extensions: ["esf"] + }, + "application/vnd.epson.msf": { + source: "iana", + extensions: ["msf"] + }, + "application/vnd.epson.quickanime": { + source: "iana", + extensions: ["qam"] + }, + "application/vnd.epson.salt": { + source: "iana", + extensions: ["slt"] + }, + "application/vnd.epson.ssf": { + source: "iana", + extensions: ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + source: "iana" + }, + "application/vnd.espass-espass+zip": { + source: "iana", + compressible: false + }, + "application/vnd.eszigno3+xml": { + source: "iana", + compressible: true, + extensions: ["es3", "et3"] + }, + "application/vnd.etsi.aoc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.asic-e+zip": { + source: "iana", + compressible: false + }, + "application/vnd.etsi.asic-s+zip": { + source: "iana", + compressible: false + }, + "application/vnd.etsi.cug+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvcommand+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvservice+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsync+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvueprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.mcid+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.mheg5": { + source: "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.pstn+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.sci+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.simservs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.timestamp-token": { + source: "iana" + }, + "application/vnd.etsi.tsl+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.tsl.der": { + source: "iana" + }, + "application/vnd.eu.kasparian.car+json": { + source: "iana", + compressible: true + }, + "application/vnd.eudora.data": { + source: "iana" + }, + "application/vnd.evolv.ecig.profile": { + source: "iana" + }, + "application/vnd.evolv.ecig.settings": { + source: "iana" + }, + "application/vnd.evolv.ecig.theme": { + source: "iana" + }, + "application/vnd.exstream-empower+zip": { + source: "iana", + compressible: false + }, + "application/vnd.exstream-package": { + source: "iana" + }, + "application/vnd.ezpix-album": { + source: "iana", + extensions: ["ez2"] + }, + "application/vnd.ezpix-package": { + source: "iana", + extensions: ["ez3"] + }, + "application/vnd.f-secure.mobile": { + source: "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + source: "iana", + compressible: false + }, + "application/vnd.fastcopy-disk-image": { + source: "iana" + }, + "application/vnd.fdf": { + source: "iana", + extensions: ["fdf"] + }, + "application/vnd.fdsn.mseed": { + source: "iana", + extensions: ["mseed"] + }, + "application/vnd.fdsn.seed": { + source: "iana", + extensions: ["seed", "dataless"] + }, + "application/vnd.ffsns": { + source: "iana" + }, + "application/vnd.ficlab.flb+zip": { + source: "iana", + compressible: false + }, + "application/vnd.filmit.zfc": { + source: "iana" + }, + "application/vnd.fints": { + source: "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + source: "iana" + }, + "application/vnd.flographit": { + source: "iana", + extensions: ["gph"] + }, + "application/vnd.fluxtime.clip": { + source: "iana", + extensions: ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + source: "iana" + }, + "application/vnd.framemaker": { + source: "iana", + extensions: ["fm", "frame", "maker", "book"] + }, + "application/vnd.frogans.fnc": { + source: "iana", + extensions: ["fnc"] + }, + "application/vnd.frogans.ltf": { + source: "iana", + extensions: ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + source: "iana", + extensions: ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + source: "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + source: "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + source: "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + source: "iana", + compressible: true + }, + "application/vnd.fujitsu.oasys": { + source: "iana", + extensions: ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + source: "iana", + extensions: ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + source: "iana", + extensions: ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + source: "iana", + extensions: ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + source: "iana", + extensions: ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + source: "iana" + }, + "application/vnd.fujixerox.art4": { + source: "iana" + }, + "application/vnd.fujixerox.ddd": { + source: "iana", + extensions: ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + source: "iana", + extensions: ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + source: "iana", + extensions: ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + source: "iana" + }, + "application/vnd.fujixerox.hbpl": { + source: "iana" + }, + "application/vnd.fut-misnet": { + source: "iana" + }, + "application/vnd.futoin+cbor": { + source: "iana" + }, + "application/vnd.futoin+json": { + source: "iana", + compressible: true + }, + "application/vnd.fuzzysheet": { + source: "iana", + extensions: ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + source: "iana", + extensions: ["txd"] + }, + "application/vnd.gentics.grd+json": { + source: "iana", + compressible: true + }, + "application/vnd.geo+json": { + source: "iana", + compressible: true + }, + "application/vnd.geocube+xml": { + source: "iana", + compressible: true + }, + "application/vnd.geogebra.file": { + source: "iana", + extensions: ["ggb"] + }, + "application/vnd.geogebra.slides": { + source: "iana" + }, + "application/vnd.geogebra.tool": { + source: "iana", + extensions: ["ggt"] + }, + "application/vnd.geometry-explorer": { + source: "iana", + extensions: ["gex", "gre"] + }, + "application/vnd.geonext": { + source: "iana", + extensions: ["gxt"] + }, + "application/vnd.geoplan": { + source: "iana", + extensions: ["g2w"] + }, + "application/vnd.geospace": { + source: "iana", + extensions: ["g3w"] + }, + "application/vnd.gerber": { + source: "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + source: "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + source: "iana" + }, + "application/vnd.gmx": { + source: "iana", + extensions: ["gmx"] + }, + "application/vnd.google-apps.document": { + compressible: false, + extensions: ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + compressible: false, + extensions: ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + compressible: false, + extensions: ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + source: "iana", + compressible: true, + extensions: ["kml"] + }, + "application/vnd.google-earth.kmz": { + source: "iana", + compressible: false, + extensions: ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + source: "iana", + compressible: true + }, + "application/vnd.gov.sk.e-form+zip": { + source: "iana", + compressible: false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + source: "iana", + compressible: true + }, + "application/vnd.grafeq": { + source: "iana", + extensions: ["gqf", "gqs"] + }, + "application/vnd.gridmp": { + source: "iana" + }, + "application/vnd.groove-account": { + source: "iana", + extensions: ["gac"] + }, + "application/vnd.groove-help": { + source: "iana", + extensions: ["ghf"] + }, + "application/vnd.groove-identity-message": { + source: "iana", + extensions: ["gim"] + }, + "application/vnd.groove-injector": { + source: "iana", + extensions: ["grv"] + }, + "application/vnd.groove-tool-message": { + source: "iana", + extensions: ["gtm"] + }, + "application/vnd.groove-tool-template": { + source: "iana", + extensions: ["tpl"] + }, + "application/vnd.groove-vcard": { + source: "iana", + extensions: ["vcg"] + }, + "application/vnd.hal+json": { + source: "iana", + compressible: true + }, + "application/vnd.hal+xml": { + source: "iana", + compressible: true, + extensions: ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + source: "iana", + compressible: true, + extensions: ["zmm"] + }, + "application/vnd.hbci": { + source: "iana", + extensions: ["hbci"] + }, + "application/vnd.hc+json": { + source: "iana", + compressible: true + }, + "application/vnd.hcl-bireports": { + source: "iana" + }, + "application/vnd.hdt": { + source: "iana" + }, + "application/vnd.heroku+json": { + source: "iana", + compressible: true + }, + "application/vnd.hhe.lesson-player": { + source: "iana", + extensions: ["les"] + }, + "application/vnd.hl7cda+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.hl7v2+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.hp-hpgl": { + source: "iana", + extensions: ["hpgl"] + }, + "application/vnd.hp-hpid": { + source: "iana", + extensions: ["hpid"] + }, + "application/vnd.hp-hps": { + source: "iana", + extensions: ["hps"] + }, + "application/vnd.hp-jlyt": { + source: "iana", + extensions: ["jlt"] + }, + "application/vnd.hp-pcl": { + source: "iana", + extensions: ["pcl"] + }, + "application/vnd.hp-pclxl": { + source: "iana", + extensions: ["pclxl"] + }, + "application/vnd.httphone": { + source: "iana" + }, + "application/vnd.hydrostatix.sof-data": { + source: "iana", + extensions: ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + source: "iana", + compressible: true + }, + "application/vnd.hyper-item+json": { + source: "iana", + compressible: true + }, + "application/vnd.hyperdrive+json": { + source: "iana", + compressible: true + }, + "application/vnd.hzn-3d-crossword": { + source: "iana" + }, + "application/vnd.ibm.afplinedata": { + source: "iana" + }, + "application/vnd.ibm.electronic-media": { + source: "iana" + }, + "application/vnd.ibm.minipay": { + source: "iana", + extensions: ["mpy"] + }, + "application/vnd.ibm.modcap": { + source: "iana", + extensions: ["afp", "listafp", "list3820"] + }, + "application/vnd.ibm.rights-management": { + source: "iana", + extensions: ["irm"] + }, + "application/vnd.ibm.secure-container": { + source: "iana", + extensions: ["sc"] + }, + "application/vnd.iccprofile": { + source: "iana", + extensions: ["icc", "icm"] + }, + "application/vnd.ieee.1905": { + source: "iana" + }, + "application/vnd.igloader": { + source: "iana", + extensions: ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + source: "iana", + compressible: false + }, + "application/vnd.imagemeter.image+zip": { + source: "iana", + compressible: false + }, + "application/vnd.immervision-ivp": { + source: "iana", + extensions: ["ivp"] + }, + "application/vnd.immervision-ivu": { + source: "iana", + extensions: ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + source: "iana" + }, + "application/vnd.ims.imsccv1p2": { + source: "iana" + }, + "application/vnd.ims.imsccv1p3": { + source: "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + source: "iana", + compressible: true + }, + "application/vnd.informedcontrol.rms+xml": { + source: "iana", + compressible: true + }, + "application/vnd.informix-visionary": { + source: "iana" + }, + "application/vnd.infotech.project": { + source: "iana" + }, + "application/vnd.infotech.project+xml": { + source: "iana", + compressible: true + }, + "application/vnd.innopath.wamp.notification": { + source: "iana" + }, + "application/vnd.insors.igm": { + source: "iana", + extensions: ["igm"] + }, + "application/vnd.intercon.formnet": { + source: "iana", + extensions: ["xpw", "xpx"] + }, + "application/vnd.intergeo": { + source: "iana", + extensions: ["i2g"] + }, + "application/vnd.intertrust.digibox": { + source: "iana" + }, + "application/vnd.intertrust.nncp": { + source: "iana" + }, + "application/vnd.intu.qbo": { + source: "iana", + extensions: ["qbo"] + }, + "application/vnd.intu.qfx": { + source: "iana", + extensions: ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.newsitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.packageitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.planningitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ipunplugged.rcprofile": { + source: "iana", + extensions: ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + source: "iana", + compressible: true, + extensions: ["irp"] + }, + "application/vnd.is-xpr": { + source: "iana", + extensions: ["xpr"] + }, + "application/vnd.isac.fcs": { + source: "iana", + extensions: ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + source: "iana", + compressible: false + }, + "application/vnd.jam": { + source: "iana", + extensions: ["jam"] + }, + "application/vnd.japannet-directory-service": { + source: "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + source: "iana" + }, + "application/vnd.japannet-payment-wakeup": { + source: "iana" + }, + "application/vnd.japannet-registration": { + source: "iana" + }, + "application/vnd.japannet-registration-wakeup": { + source: "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + source: "iana" + }, + "application/vnd.japannet-verification": { + source: "iana" + }, + "application/vnd.japannet-verification-wakeup": { + source: "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + source: "iana", + extensions: ["rms"] + }, + "application/vnd.jisp": { + source: "iana", + extensions: ["jisp"] + }, + "application/vnd.joost.joda-archive": { + source: "iana", + extensions: ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + source: "iana" + }, + "application/vnd.kahootz": { + source: "iana", + extensions: ["ktz", "ktr"] + }, + "application/vnd.kde.karbon": { + source: "iana", + extensions: ["karbon"] + }, + "application/vnd.kde.kchart": { + source: "iana", + extensions: ["chrt"] + }, + "application/vnd.kde.kformula": { + source: "iana", + extensions: ["kfo"] + }, + "application/vnd.kde.kivio": { + source: "iana", + extensions: ["flw"] + }, + "application/vnd.kde.kontour": { + source: "iana", + extensions: ["kon"] + }, + "application/vnd.kde.kpresenter": { + source: "iana", + extensions: ["kpr", "kpt"] + }, + "application/vnd.kde.kspread": { + source: "iana", + extensions: ["ksp"] + }, + "application/vnd.kde.kword": { + source: "iana", + extensions: ["kwd", "kwt"] + }, + "application/vnd.kenameaapp": { + source: "iana", + extensions: ["htke"] + }, + "application/vnd.kidspiration": { + source: "iana", + extensions: ["kia"] + }, + "application/vnd.kinar": { + source: "iana", + extensions: ["kne", "knp"] + }, + "application/vnd.koan": { + source: "iana", + extensions: ["skp", "skd", "skt", "skm"] + }, + "application/vnd.kodak-descriptor": { + source: "iana", + extensions: ["sse"] + }, + "application/vnd.las": { + source: "iana" + }, + "application/vnd.las.las+json": { + source: "iana", + compressible: true + }, + "application/vnd.las.las+xml": { + source: "iana", + compressible: true, + extensions: ["lasxml"] + }, + "application/vnd.laszip": { + source: "iana" + }, + "application/vnd.leap+json": { + source: "iana", + compressible: true + }, + "application/vnd.liberty-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + source: "iana", + extensions: ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + source: "iana", + compressible: true, + extensions: ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + source: "iana", + compressible: false + }, + "application/vnd.loom": { + source: "iana" + }, + "application/vnd.lotus-1-2-3": { + source: "iana", + extensions: ["123"] + }, + "application/vnd.lotus-approach": { + source: "iana", + extensions: ["apr"] + }, + "application/vnd.lotus-freelance": { + source: "iana", + extensions: ["pre"] + }, + "application/vnd.lotus-notes": { + source: "iana", + extensions: ["nsf"] + }, + "application/vnd.lotus-organizer": { + source: "iana", + extensions: ["org"] + }, + "application/vnd.lotus-screencam": { + source: "iana", + extensions: ["scm"] + }, + "application/vnd.lotus-wordpro": { + source: "iana", + extensions: ["lwp"] + }, + "application/vnd.macports.portpkg": { + source: "iana", + extensions: ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + source: "iana", + extensions: ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.conftoken+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.license+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.mdcf": { + source: "iana" + }, + "application/vnd.mason+json": { + source: "iana", + compressible: true + }, + "application/vnd.maxar.archive.3tz+zip": { + source: "iana", + compressible: false + }, + "application/vnd.maxmind.maxmind-db": { + source: "iana" + }, + "application/vnd.mcd": { + source: "iana", + extensions: ["mcd"] + }, + "application/vnd.medcalcdata": { + source: "iana", + extensions: ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + source: "iana", + extensions: ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + source: "iana" + }, + "application/vnd.mfer": { + source: "iana", + extensions: ["mwf"] + }, + "application/vnd.mfmp": { + source: "iana", + extensions: ["mfm"] + }, + "application/vnd.micro+json": { + source: "iana", + compressible: true + }, + "application/vnd.micrografx.flo": { + source: "iana", + extensions: ["flo"] + }, + "application/vnd.micrografx.igx": { + source: "iana", + extensions: ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + source: "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + source: "iana" + }, + "application/vnd.miele+json": { + source: "iana", + compressible: true + }, + "application/vnd.mif": { + source: "iana", + extensions: ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + source: "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + source: "iana" + }, + "application/vnd.mobius.daf": { + source: "iana", + extensions: ["daf"] + }, + "application/vnd.mobius.dis": { + source: "iana", + extensions: ["dis"] + }, + "application/vnd.mobius.mbk": { + source: "iana", + extensions: ["mbk"] + }, + "application/vnd.mobius.mqy": { + source: "iana", + extensions: ["mqy"] + }, + "application/vnd.mobius.msl": { + source: "iana", + extensions: ["msl"] + }, + "application/vnd.mobius.plc": { + source: "iana", + extensions: ["plc"] + }, + "application/vnd.mobius.txf": { + source: "iana", + extensions: ["txf"] + }, + "application/vnd.mophun.application": { + source: "iana", + extensions: ["mpn"] + }, + "application/vnd.mophun.certificate": { + source: "iana", + extensions: ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + source: "iana" + }, + "application/vnd.motorola.iprm": { + source: "iana" + }, + "application/vnd.mozilla.xul+xml": { + source: "iana", + compressible: true, + extensions: ["xul"] + }, + "application/vnd.ms-3mfdocument": { + source: "iana" + }, + "application/vnd.ms-artgalry": { + source: "iana", + extensions: ["cil"] + }, + "application/vnd.ms-asf": { + source: "iana" + }, + "application/vnd.ms-cab-compressed": { + source: "iana", + extensions: ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + source: "apache" + }, + "application/vnd.ms-excel": { + source: "iana", + compressible: false, + extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + source: "iana", + extensions: ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + source: "iana", + extensions: ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + source: "iana", + extensions: ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + source: "iana", + extensions: ["xltm"] + }, + "application/vnd.ms-fontobject": { + source: "iana", + compressible: true, + extensions: ["eot"] + }, + "application/vnd.ms-htmlhelp": { + source: "iana", + extensions: ["chm"] + }, + "application/vnd.ms-ims": { + source: "iana", + extensions: ["ims"] + }, + "application/vnd.ms-lrm": { + source: "iana", + extensions: ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-officetheme": { + source: "iana", + extensions: ["thmx"] + }, + "application/vnd.ms-opentype": { + source: "apache", + compressible: true + }, + "application/vnd.ms-outlook": { + compressible: false, + extensions: ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + source: "apache" + }, + "application/vnd.ms-pki.seccat": { + source: "apache", + extensions: ["cat"] + }, + "application/vnd.ms-pki.stl": { + source: "apache", + extensions: ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-powerpoint": { + source: "iana", + compressible: false, + extensions: ["ppt", "pps", "pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + source: "iana", + extensions: ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + source: "iana", + extensions: ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + source: "iana", + extensions: ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + source: "iana", + extensions: ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + source: "iana", + extensions: ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-printing.printticket+xml": { + source: "apache", + compressible: true + }, + "application/vnd.ms-printschematicket+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-project": { + source: "iana", + extensions: ["mpp", "mpt"] + }, + "application/vnd.ms-tnef": { + source: "iana" + }, + "application/vnd.ms-windows.devicepairing": { + source: "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + source: "iana" + }, + "application/vnd.ms-windows.printerpairing": { + source: "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + source: "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + source: "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + source: "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + source: "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + source: "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + source: "iana", + extensions: ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + source: "iana", + extensions: ["dotm"] + }, + "application/vnd.ms-works": { + source: "iana", + extensions: ["wps", "wks", "wcm", "wdb"] + }, + "application/vnd.ms-wpl": { + source: "iana", + extensions: ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + source: "iana", + compressible: false, + extensions: ["xps"] + }, + "application/vnd.msa-disk-image": { + source: "iana" + }, + "application/vnd.mseq": { + source: "iana", + extensions: ["mseq"] + }, + "application/vnd.msign": { + source: "iana" + }, + "application/vnd.multiad.creator": { + source: "iana" + }, + "application/vnd.multiad.creator.cif": { + source: "iana" + }, + "application/vnd.music-niff": { + source: "iana" + }, + "application/vnd.musician": { + source: "iana", + extensions: ["mus"] + }, + "application/vnd.muvee.style": { + source: "iana", + extensions: ["msty"] + }, + "application/vnd.mynfc": { + source: "iana", + extensions: ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + source: "iana", + compressible: true + }, + "application/vnd.ncd.control": { + source: "iana" + }, + "application/vnd.ncd.reference": { + source: "iana" + }, + "application/vnd.nearst.inv+json": { + source: "iana", + compressible: true + }, + "application/vnd.nebumind.line": { + source: "iana" + }, + "application/vnd.nervana": { + source: "iana" + }, + "application/vnd.netfpx": { + source: "iana" + }, + "application/vnd.neurolanguage.nlu": { + source: "iana", + extensions: ["nlu"] + }, + "application/vnd.nimn": { + source: "iana" + }, + "application/vnd.nintendo.nitro.rom": { + source: "iana" + }, + "application/vnd.nintendo.snes.rom": { + source: "iana" + }, + "application/vnd.nitf": { + source: "iana", + extensions: ["ntf", "nitf"] + }, + "application/vnd.noblenet-directory": { + source: "iana", + extensions: ["nnd"] + }, + "application/vnd.noblenet-sealer": { + source: "iana", + extensions: ["nns"] + }, + "application/vnd.noblenet-web": { + source: "iana", + extensions: ["nnw"] + }, + "application/vnd.nokia.catalogs": { + source: "iana" + }, + "application/vnd.nokia.conml+wbxml": { + source: "iana" + }, + "application/vnd.nokia.conml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.iptv.config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.isds-radio-presets": { + source: "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + source: "iana" + }, + "application/vnd.nokia.landmark+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.landmarkcollection+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.n-gage.ac+xml": { + source: "iana", + compressible: true, + extensions: ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + source: "iana", + extensions: ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + source: "iana", + extensions: ["n-gage"] + }, + "application/vnd.nokia.ncd": { + source: "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + source: "iana" + }, + "application/vnd.nokia.pcd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.radio-preset": { + source: "iana", + extensions: ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + source: "iana", + extensions: ["rpss"] + }, + "application/vnd.novadigm.edm": { + source: "iana", + extensions: ["edm"] + }, + "application/vnd.novadigm.edx": { + source: "iana", + extensions: ["edx"] + }, + "application/vnd.novadigm.ext": { + source: "iana", + extensions: ["ext"] + }, + "application/vnd.ntt-local.content-share": { + source: "iana" + }, + "application/vnd.ntt-local.file-transfer": { + source: "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + source: "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + source: "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + source: "iana" + }, + "application/vnd.oasis.opendocument.chart": { + source: "iana", + extensions: ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + source: "iana", + extensions: ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + source: "iana", + extensions: ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + source: "iana", + extensions: ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + source: "iana", + extensions: ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + source: "iana", + compressible: false, + extensions: ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + source: "iana", + extensions: ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + source: "iana", + extensions: ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + source: "iana", + extensions: ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + source: "iana", + compressible: false, + extensions: ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + source: "iana", + extensions: ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + source: "iana", + compressible: false, + extensions: ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + source: "iana", + extensions: ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + source: "iana", + compressible: false, + extensions: ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + source: "iana", + extensions: ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + source: "iana", + extensions: ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + source: "iana", + extensions: ["oth"] + }, + "application/vnd.obn": { + source: "iana" + }, + "application/vnd.ocf+cbor": { + source: "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + source: "iana", + compressible: true + }, + "application/vnd.oftn.l10n+json": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.cspg-hexbinary": { + source: "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.dae.xhtml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.pae.gem": { + source: "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.spdlist+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.ueprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.userprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.olpc-sugar": { + source: "iana", + extensions: ["xo"] + }, + "application/vnd.oma-scws-config": { + source: "iana" + }, + "application/vnd.oma-scws-http-request": { + source: "iana" + }, + "application/vnd.oma-scws-http-response": { + source: "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.imd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.ltkm": { + source: "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + source: "iana" + }, + "application/vnd.oma.bcast.sgboot": { + source: "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.sgdu": { + source: "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + source: "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.sprov+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.stkm": { + source: "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-feature-handler+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-pcc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-subs-invite+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-user-prefs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.dcd": { + source: "iana" + }, + "application/vnd.oma.dcdc": { + source: "iana" + }, + "application/vnd.oma.dd2+xml": { + source: "iana", + compressible: true, + extensions: ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.group-usage-list+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.lwm2m+cbor": { + source: "iana" + }, + "application/vnd.oma.lwm2m+json": { + source: "iana", + compressible: true + }, + "application/vnd.oma.lwm2m+tlv": { + source: "iana" + }, + "application/vnd.oma.pal+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.final-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.groups+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.push": { + source: "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.xcap-directory+xml": { + source: "iana", + compressible: true + }, + "application/vnd.omads-email+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omads-file+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omads-folder+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omaloc-supl-init": { + source: "iana" + }, + "application/vnd.onepager": { + source: "iana" + }, + "application/vnd.onepagertamp": { + source: "iana" + }, + "application/vnd.onepagertamx": { + source: "iana" + }, + "application/vnd.onepagertat": { + source: "iana" + }, + "application/vnd.onepagertatp": { + source: "iana" + }, + "application/vnd.onepagertatx": { + source: "iana" + }, + "application/vnd.openblox.game+xml": { + source: "iana", + compressible: true, + extensions: ["obgx"] + }, + "application/vnd.openblox.game-binary": { + source: "iana" + }, + "application/vnd.openeye.oeb": { + source: "iana" + }, + "application/vnd.openofficeorg.extension": { + source: "apache", + extensions: ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + source: "iana", + compressible: true, + extensions: ["osm"] + }, + "application/vnd.opentimestamps.ots": { + source: "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + source: "iana", + compressible: false, + extensions: ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + source: "iana", + extensions: ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + source: "iana", + extensions: ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + source: "iana", + extensions: ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + source: "iana", + compressible: false, + extensions: ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + source: "iana", + extensions: ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + source: "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + source: "iana", + compressible: false, + extensions: ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + source: "iana", + extensions: ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oracle.resource+json": { + source: "iana", + compressible: true + }, + "application/vnd.orange.indata": { + source: "iana" + }, + "application/vnd.osa.netdeploy": { + source: "iana" + }, + "application/vnd.osgeo.mapguide.package": { + source: "iana", + extensions: ["mgp"] + }, + "application/vnd.osgi.bundle": { + source: "iana" + }, + "application/vnd.osgi.dp": { + source: "iana", + extensions: ["dp"] + }, + "application/vnd.osgi.subsystem": { + source: "iana", + extensions: ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oxli.countgraph": { + source: "iana" + }, + "application/vnd.pagerduty+json": { + source: "iana", + compressible: true + }, + "application/vnd.palm": { + source: "iana", + extensions: ["pdb", "pqa", "oprc"] + }, + "application/vnd.panoply": { + source: "iana" + }, + "application/vnd.paos.xml": { + source: "iana" + }, + "application/vnd.patentdive": { + source: "iana" + }, + "application/vnd.patientecommsdoc": { + source: "iana" + }, + "application/vnd.pawaafile": { + source: "iana", + extensions: ["paw"] + }, + "application/vnd.pcos": { + source: "iana" + }, + "application/vnd.pg.format": { + source: "iana", + extensions: ["str"] + }, + "application/vnd.pg.osasli": { + source: "iana", + extensions: ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + source: "iana" + }, + "application/vnd.picsel": { + source: "iana", + extensions: ["efif"] + }, + "application/vnd.pmi.widget": { + source: "iana", + extensions: ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + source: "iana", + compressible: true + }, + "application/vnd.pocketlearn": { + source: "iana", + extensions: ["plf"] + }, + "application/vnd.powerbuilder6": { + source: "iana", + extensions: ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + source: "iana" + }, + "application/vnd.powerbuilder7": { + source: "iana" + }, + "application/vnd.powerbuilder7-s": { + source: "iana" + }, + "application/vnd.powerbuilder75": { + source: "iana" + }, + "application/vnd.powerbuilder75-s": { + source: "iana" + }, + "application/vnd.preminet": { + source: "iana" + }, + "application/vnd.previewsystems.box": { + source: "iana", + extensions: ["box"] + }, + "application/vnd.proteus.magazine": { + source: "iana", + extensions: ["mgz"] + }, + "application/vnd.psfs": { + source: "iana" + }, + "application/vnd.publishare-delta-tree": { + source: "iana", + extensions: ["qps"] + }, + "application/vnd.pvi.ptid1": { + source: "iana", + extensions: ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + source: "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + source: "iana", + compressible: true + }, + "application/vnd.qualcomm.brew-app-res": { + source: "iana" + }, + "application/vnd.quarantainenet": { + source: "iana" + }, + "application/vnd.quark.quarkxpress": { + source: "iana", + extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"] + }, + "application/vnd.quobject-quoxdocument": { + source: "iana" + }, + "application/vnd.radisys.moml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-conf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + source: "iana", + compressible: true + }, + "application/vnd.rainstor.data": { + source: "iana" + }, + "application/vnd.rapid": { + source: "iana" + }, + "application/vnd.rar": { + source: "iana", + extensions: ["rar"] + }, + "application/vnd.realvnc.bed": { + source: "iana", + extensions: ["bed"] + }, + "application/vnd.recordare.musicxml": { + source: "iana", + extensions: ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + source: "iana", + compressible: true, + extensions: ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + source: "iana" + }, + "application/vnd.resilient.logic": { + source: "iana" + }, + "application/vnd.restful+json": { + source: "iana", + compressible: true + }, + "application/vnd.rig.cryptonote": { + source: "iana", + extensions: ["cryptonote"] + }, + "application/vnd.rim.cod": { + source: "apache", + extensions: ["cod"] + }, + "application/vnd.rn-realmedia": { + source: "apache", + extensions: ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + source: "apache", + extensions: ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + source: "iana", + compressible: true, + extensions: ["link66"] + }, + "application/vnd.rs-274x": { + source: "iana" + }, + "application/vnd.ruckus.download": { + source: "iana" + }, + "application/vnd.s3sms": { + source: "iana" + }, + "application/vnd.sailingtracker.track": { + source: "iana", + extensions: ["st"] + }, + "application/vnd.sar": { + source: "iana" + }, + "application/vnd.sbm.cid": { + source: "iana" + }, + "application/vnd.sbm.mid2": { + source: "iana" + }, + "application/vnd.scribus": { + source: "iana" + }, + "application/vnd.sealed.3df": { + source: "iana" + }, + "application/vnd.sealed.csf": { + source: "iana" + }, + "application/vnd.sealed.doc": { + source: "iana" + }, + "application/vnd.sealed.eml": { + source: "iana" + }, + "application/vnd.sealed.mht": { + source: "iana" + }, + "application/vnd.sealed.net": { + source: "iana" + }, + "application/vnd.sealed.ppt": { + source: "iana" + }, + "application/vnd.sealed.tiff": { + source: "iana" + }, + "application/vnd.sealed.xls": { + source: "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + source: "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + source: "iana" + }, + "application/vnd.seemail": { + source: "iana", + extensions: ["see"] + }, + "application/vnd.seis+json": { + source: "iana", + compressible: true + }, + "application/vnd.sema": { + source: "iana", + extensions: ["sema"] + }, + "application/vnd.semd": { + source: "iana", + extensions: ["semd"] + }, + "application/vnd.semf": { + source: "iana", + extensions: ["semf"] + }, + "application/vnd.shade-save-file": { + source: "iana" + }, + "application/vnd.shana.informed.formdata": { + source: "iana", + extensions: ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + source: "iana", + extensions: ["itp"] + }, + "application/vnd.shana.informed.interchange": { + source: "iana", + extensions: ["iif"] + }, + "application/vnd.shana.informed.package": { + source: "iana", + extensions: ["ipk"] + }, + "application/vnd.shootproof+json": { + source: "iana", + compressible: true + }, + "application/vnd.shopkick+json": { + source: "iana", + compressible: true + }, + "application/vnd.shp": { + source: "iana" + }, + "application/vnd.shx": { + source: "iana" + }, + "application/vnd.sigrok.session": { + source: "iana" + }, + "application/vnd.simtech-mindmapper": { + source: "iana", + extensions: ["twd", "twds"] + }, + "application/vnd.siren+json": { + source: "iana", + compressible: true + }, + "application/vnd.smaf": { + source: "iana", + extensions: ["mmf"] + }, + "application/vnd.smart.notebook": { + source: "iana" + }, + "application/vnd.smart.teacher": { + source: "iana", + extensions: ["teacher"] + }, + "application/vnd.snesdev-page-table": { + source: "iana" + }, + "application/vnd.software602.filler.form+xml": { + source: "iana", + compressible: true, + extensions: ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + source: "iana" + }, + "application/vnd.solent.sdkm+xml": { + source: "iana", + compressible: true, + extensions: ["sdkm", "sdkd"] + }, + "application/vnd.spotfire.dxp": { + source: "iana", + extensions: ["dxp"] + }, + "application/vnd.spotfire.sfs": { + source: "iana", + extensions: ["sfs"] + }, + "application/vnd.sqlite3": { + source: "iana" + }, + "application/vnd.sss-cod": { + source: "iana" + }, + "application/vnd.sss-dtf": { + source: "iana" + }, + "application/vnd.sss-ntf": { + source: "iana" + }, + "application/vnd.stardivision.calc": { + source: "apache", + extensions: ["sdc"] + }, + "application/vnd.stardivision.draw": { + source: "apache", + extensions: ["sda"] + }, + "application/vnd.stardivision.impress": { + source: "apache", + extensions: ["sdd"] + }, + "application/vnd.stardivision.math": { + source: "apache", + extensions: ["smf"] + }, + "application/vnd.stardivision.writer": { + source: "apache", + extensions: ["sdw", "vor"] + }, + "application/vnd.stardivision.writer-global": { + source: "apache", + extensions: ["sgl"] + }, + "application/vnd.stepmania.package": { + source: "iana", + extensions: ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + source: "iana", + extensions: ["sm"] + }, + "application/vnd.street-stream": { + source: "iana" + }, + "application/vnd.sun.wadl+xml": { + source: "iana", + compressible: true, + extensions: ["wadl"] + }, + "application/vnd.sun.xml.calc": { + source: "apache", + extensions: ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + source: "apache", + extensions: ["stc"] + }, + "application/vnd.sun.xml.draw": { + source: "apache", + extensions: ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + source: "apache", + extensions: ["std"] + }, + "application/vnd.sun.xml.impress": { + source: "apache", + extensions: ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + source: "apache", + extensions: ["sti"] + }, + "application/vnd.sun.xml.math": { + source: "apache", + extensions: ["sxm"] + }, + "application/vnd.sun.xml.writer": { + source: "apache", + extensions: ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + source: "apache", + extensions: ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + source: "apache", + extensions: ["stw"] + }, + "application/vnd.sus-calendar": { + source: "iana", + extensions: ["sus", "susp"] + }, + "application/vnd.svd": { + source: "iana", + extensions: ["svd"] + }, + "application/vnd.swiftview-ics": { + source: "iana" + }, + "application/vnd.sycle+xml": { + source: "iana", + compressible: true + }, + "application/vnd.syft+json": { + source: "iana", + compressible: true + }, + "application/vnd.symbian.install": { + source: "apache", + extensions: ["sis", "sisx"] + }, + "application/vnd.syncml+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + source: "iana", + charset: "UTF-8", + extensions: ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + source: "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + source: "iana" + }, + "application/vnd.syncml.dmddf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + source: "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.syncml.ds.notification": { + source: "iana" + }, + "application/vnd.tableschema+json": { + source: "iana", + compressible: true + }, + "application/vnd.tao.intent-module-archive": { + source: "iana", + extensions: ["tao"] + }, + "application/vnd.tcpdump.pcap": { + source: "iana", + extensions: ["pcap", "cap", "dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + source: "iana", + compressible: true + }, + "application/vnd.tmd.mediaflex.api+xml": { + source: "iana", + compressible: true + }, + "application/vnd.tml": { + source: "iana" + }, + "application/vnd.tmobile-livetv": { + source: "iana", + extensions: ["tmo"] + }, + "application/vnd.tri.onesource": { + source: "iana" + }, + "application/vnd.trid.tpt": { + source: "iana", + extensions: ["tpt"] + }, + "application/vnd.triscape.mxs": { + source: "iana", + extensions: ["mxs"] + }, + "application/vnd.trueapp": { + source: "iana", + extensions: ["tra"] + }, + "application/vnd.truedoc": { + source: "iana" + }, + "application/vnd.ubisoft.webplayer": { + source: "iana" + }, + "application/vnd.ufdl": { + source: "iana", + extensions: ["ufd", "ufdl"] + }, + "application/vnd.uiq.theme": { + source: "iana", + extensions: ["utz"] + }, + "application/vnd.umajin": { + source: "iana", + extensions: ["umj"] + }, + "application/vnd.unity": { + source: "iana", + extensions: ["unityweb"] + }, + "application/vnd.uoml+xml": { + source: "iana", + compressible: true, + extensions: ["uoml"] + }, + "application/vnd.uplanet.alert": { + source: "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.bearer-choice": { + source: "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.cacheop": { + source: "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.channel": { + source: "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.list": { + source: "iana" + }, + "application/vnd.uplanet.list-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.listcmd": { + source: "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.signal": { + source: "iana" + }, + "application/vnd.uri-map": { + source: "iana" + }, + "application/vnd.valve.source.material": { + source: "iana" + }, + "application/vnd.vcx": { + source: "iana", + extensions: ["vcx"] + }, + "application/vnd.vd-study": { + source: "iana" + }, + "application/vnd.vectorworks": { + source: "iana" + }, + "application/vnd.vel+json": { + source: "iana", + compressible: true + }, + "application/vnd.verimatrix.vcas": { + source: "iana" + }, + "application/vnd.veritone.aion+json": { + source: "iana", + compressible: true + }, + "application/vnd.veryant.thin": { + source: "iana" + }, + "application/vnd.ves.encrypted": { + source: "iana" + }, + "application/vnd.vidsoft.vidconference": { + source: "iana" + }, + "application/vnd.visio": { + source: "iana", + extensions: ["vsd", "vst", "vss", "vsw"] + }, + "application/vnd.visionary": { + source: "iana", + extensions: ["vis"] + }, + "application/vnd.vividence.scriptfile": { + source: "iana" + }, + "application/vnd.vsf": { + source: "iana", + extensions: ["vsf"] + }, + "application/vnd.wap.sic": { + source: "iana" + }, + "application/vnd.wap.slc": { + source: "iana" + }, + "application/vnd.wap.wbxml": { + source: "iana", + charset: "UTF-8", + extensions: ["wbxml"] + }, + "application/vnd.wap.wmlc": { + source: "iana", + extensions: ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + source: "iana", + extensions: ["wmlsc"] + }, + "application/vnd.webturbo": { + source: "iana", + extensions: ["wtb"] + }, + "application/vnd.wfa.dpp": { + source: "iana" + }, + "application/vnd.wfa.p2p": { + source: "iana" + }, + "application/vnd.wfa.wsc": { + source: "iana" + }, + "application/vnd.windows.devicepairing": { + source: "iana" + }, + "application/vnd.wmc": { + source: "iana" + }, + "application/vnd.wmf.bootstrap": { + source: "iana" + }, + "application/vnd.wolfram.mathematica": { + source: "iana" + }, + "application/vnd.wolfram.mathematica.package": { + source: "iana" + }, + "application/vnd.wolfram.player": { + source: "iana", + extensions: ["nbp"] + }, + "application/vnd.wordperfect": { + source: "iana", + extensions: ["wpd"] + }, + "application/vnd.wqd": { + source: "iana", + extensions: ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + source: "iana" + }, + "application/vnd.wt.stf": { + source: "iana", + extensions: ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + source: "iana" + }, + "application/vnd.wv.csp+xml": { + source: "iana", + compressible: true + }, + "application/vnd.wv.ssp+xml": { + source: "iana", + compressible: true + }, + "application/vnd.xacml+json": { + source: "iana", + compressible: true + }, + "application/vnd.xara": { + source: "iana", + extensions: ["xar"] + }, + "application/vnd.xfdl": { + source: "iana", + extensions: ["xfdl"] + }, + "application/vnd.xfdl.webform": { + source: "iana" + }, + "application/vnd.xmi+xml": { + source: "iana", + compressible: true + }, + "application/vnd.xmpie.cpkg": { + source: "iana" + }, + "application/vnd.xmpie.dpkg": { + source: "iana" + }, + "application/vnd.xmpie.plan": { + source: "iana" + }, + "application/vnd.xmpie.ppkg": { + source: "iana" + }, + "application/vnd.xmpie.xlim": { + source: "iana" + }, + "application/vnd.yamaha.hv-dic": { + source: "iana", + extensions: ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + source: "iana", + extensions: ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + source: "iana", + extensions: ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + source: "iana", + extensions: ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + source: "iana", + compressible: true, + extensions: ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + source: "iana" + }, + "application/vnd.yamaha.smaf-audio": { + source: "iana", + extensions: ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + source: "iana", + extensions: ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + source: "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + source: "iana" + }, + "application/vnd.yaoweme": { + source: "iana" + }, + "application/vnd.yellowriver-custom-menu": { + source: "iana", + extensions: ["cmp"] + }, + "application/vnd.youtube.yt": { + source: "iana" + }, + "application/vnd.zul": { + source: "iana", + extensions: ["zir", "zirz"] + }, + "application/vnd.zzazz.deck+xml": { + source: "iana", + compressible: true, + extensions: ["zaz"] + }, + "application/voicexml+xml": { + source: "iana", + compressible: true, + extensions: ["vxml"] + }, + "application/voucher-cms+json": { + source: "iana", + compressible: true + }, + "application/vq-rtcpxr": { + source: "iana" + }, + "application/wasm": { + source: "iana", + compressible: true, + extensions: ["wasm"] + }, + "application/watcherinfo+xml": { + source: "iana", + compressible: true, + extensions: ["wif"] + }, + "application/webpush-options+json": { + source: "iana", + compressible: true + }, + "application/whoispp-query": { + source: "iana" + }, + "application/whoispp-response": { + source: "iana" + }, + "application/widget": { + source: "iana", + extensions: ["wgt"] + }, + "application/winhlp": { + source: "apache", + extensions: ["hlp"] + }, + "application/wita": { + source: "iana" + }, + "application/wordperfect5.1": { + source: "iana" + }, + "application/wsdl+xml": { + source: "iana", + compressible: true, + extensions: ["wsdl"] + }, + "application/wspolicy+xml": { + source: "iana", + compressible: true, + extensions: ["wspolicy"] + }, + "application/x-7z-compressed": { + source: "apache", + compressible: false, + extensions: ["7z"] + }, + "application/x-abiword": { + source: "apache", + extensions: ["abw"] + }, + "application/x-ace-compressed": { + source: "apache", + extensions: ["ace"] + }, + "application/x-amf": { + source: "apache" + }, + "application/x-apple-diskimage": { + source: "apache", + extensions: ["dmg"] + }, + "application/x-arj": { + compressible: false, + extensions: ["arj"] + }, + "application/x-authorware-bin": { + source: "apache", + extensions: ["aab", "x32", "u32", "vox"] + }, + "application/x-authorware-map": { + source: "apache", + extensions: ["aam"] + }, + "application/x-authorware-seg": { + source: "apache", + extensions: ["aas"] + }, + "application/x-bcpio": { + source: "apache", + extensions: ["bcpio"] + }, + "application/x-bdoc": { + compressible: false, + extensions: ["bdoc"] + }, + "application/x-bittorrent": { + source: "apache", + extensions: ["torrent"] + }, + "application/x-blorb": { + source: "apache", + extensions: ["blb", "blorb"] + }, + "application/x-bzip": { + source: "apache", + compressible: false, + extensions: ["bz"] + }, + "application/x-bzip2": { + source: "apache", + compressible: false, + extensions: ["bz2", "boz"] + }, + "application/x-cbr": { + source: "apache", + extensions: ["cbr", "cba", "cbt", "cbz", "cb7"] + }, + "application/x-cdlink": { + source: "apache", + extensions: ["vcd"] + }, + "application/x-cfs-compressed": { + source: "apache", + extensions: ["cfs"] + }, + "application/x-chat": { + source: "apache", + extensions: ["chat"] + }, + "application/x-chess-pgn": { + source: "apache", + extensions: ["pgn"] + }, + "application/x-chrome-extension": { + extensions: ["crx"] + }, + "application/x-cocoa": { + source: "nginx", + extensions: ["cco"] + }, + "application/x-compress": { + source: "apache" + }, + "application/x-conference": { + source: "apache", + extensions: ["nsc"] + }, + "application/x-cpio": { + source: "apache", + extensions: ["cpio"] + }, + "application/x-csh": { + source: "apache", + extensions: ["csh"] + }, + "application/x-deb": { + compressible: false + }, + "application/x-debian-package": { + source: "apache", + extensions: ["deb", "udeb"] + }, + "application/x-dgc-compressed": { + source: "apache", + extensions: ["dgc"] + }, + "application/x-director": { + source: "apache", + extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"] + }, + "application/x-doom": { + source: "apache", + extensions: ["wad"] + }, + "application/x-dtbncx+xml": { + source: "apache", + compressible: true, + extensions: ["ncx"] + }, + "application/x-dtbook+xml": { + source: "apache", + compressible: true, + extensions: ["dtb"] + }, + "application/x-dtbresource+xml": { + source: "apache", + compressible: true, + extensions: ["res"] + }, + "application/x-dvi": { + source: "apache", + compressible: false, + extensions: ["dvi"] + }, + "application/x-envoy": { + source: "apache", + extensions: ["evy"] + }, + "application/x-eva": { + source: "apache", + extensions: ["eva"] + }, + "application/x-font-bdf": { + source: "apache", + extensions: ["bdf"] + }, + "application/x-font-dos": { + source: "apache" + }, + "application/x-font-framemaker": { + source: "apache" + }, + "application/x-font-ghostscript": { + source: "apache", + extensions: ["gsf"] + }, + "application/x-font-libgrx": { + source: "apache" + }, + "application/x-font-linux-psf": { + source: "apache", + extensions: ["psf"] + }, + "application/x-font-pcf": { + source: "apache", + extensions: ["pcf"] + }, + "application/x-font-snf": { + source: "apache", + extensions: ["snf"] + }, + "application/x-font-speedo": { + source: "apache" + }, + "application/x-font-sunos-news": { + source: "apache" + }, + "application/x-font-type1": { + source: "apache", + extensions: ["pfa", "pfb", "pfm", "afm"] + }, + "application/x-font-vfont": { + source: "apache" + }, + "application/x-freearc": { + source: "apache", + extensions: ["arc"] + }, + "application/x-futuresplash": { + source: "apache", + extensions: ["spl"] + }, + "application/x-gca-compressed": { + source: "apache", + extensions: ["gca"] + }, + "application/x-glulx": { + source: "apache", + extensions: ["ulx"] + }, + "application/x-gnumeric": { + source: "apache", + extensions: ["gnumeric"] + }, + "application/x-gramps-xml": { + source: "apache", + extensions: ["gramps"] + }, + "application/x-gtar": { + source: "apache", + extensions: ["gtar"] + }, + "application/x-gzip": { + source: "apache" + }, + "application/x-hdf": { + source: "apache", + extensions: ["hdf"] + }, + "application/x-httpd-php": { + compressible: true, + extensions: ["php"] + }, + "application/x-install-instructions": { + source: "apache", + extensions: ["install"] + }, + "application/x-iso9660-image": { + source: "apache", + extensions: ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + extensions: ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + extensions: ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + extensions: ["pages"] + }, + "application/x-java-archive-diff": { + source: "nginx", + extensions: ["jardiff"] + }, + "application/x-java-jnlp-file": { + source: "apache", + compressible: false, + extensions: ["jnlp"] + }, + "application/x-javascript": { + compressible: true + }, + "application/x-keepass2": { + extensions: ["kdbx"] + }, + "application/x-latex": { + source: "apache", + compressible: false, + extensions: ["latex"] + }, + "application/x-lua-bytecode": { + extensions: ["luac"] + }, + "application/x-lzh-compressed": { + source: "apache", + extensions: ["lzh", "lha"] + }, + "application/x-makeself": { + source: "nginx", + extensions: ["run"] + }, + "application/x-mie": { + source: "apache", + extensions: ["mie"] + }, + "application/x-mobipocket-ebook": { + source: "apache", + extensions: ["prc", "mobi"] + }, + "application/x-mpegurl": { + compressible: false + }, + "application/x-ms-application": { + source: "apache", + extensions: ["application"] + }, + "application/x-ms-shortcut": { + source: "apache", + extensions: ["lnk"] + }, + "application/x-ms-wmd": { + source: "apache", + extensions: ["wmd"] + }, + "application/x-ms-wmz": { + source: "apache", + extensions: ["wmz"] + }, + "application/x-ms-xbap": { + source: "apache", + extensions: ["xbap"] + }, + "application/x-msaccess": { + source: "apache", + extensions: ["mdb"] + }, + "application/x-msbinder": { + source: "apache", + extensions: ["obd"] + }, + "application/x-mscardfile": { + source: "apache", + extensions: ["crd"] + }, + "application/x-msclip": { + source: "apache", + extensions: ["clp"] + }, + "application/x-msdos-program": { + extensions: ["exe"] + }, + "application/x-msdownload": { + source: "apache", + extensions: ["exe", "dll", "com", "bat", "msi"] + }, + "application/x-msmediaview": { + source: "apache", + extensions: ["mvb", "m13", "m14"] + }, + "application/x-msmetafile": { + source: "apache", + extensions: ["wmf", "wmz", "emf", "emz"] + }, + "application/x-msmoney": { + source: "apache", + extensions: ["mny"] + }, + "application/x-mspublisher": { + source: "apache", + extensions: ["pub"] + }, + "application/x-msschedule": { + source: "apache", + extensions: ["scd"] + }, + "application/x-msterminal": { + source: "apache", + extensions: ["trm"] + }, + "application/x-mswrite": { + source: "apache", + extensions: ["wri"] + }, + "application/x-netcdf": { + source: "apache", + extensions: ["nc", "cdf"] + }, + "application/x-ns-proxy-autoconfig": { + compressible: true, + extensions: ["pac"] + }, + "application/x-nzb": { + source: "apache", + extensions: ["nzb"] + }, + "application/x-perl": { + source: "nginx", + extensions: ["pl", "pm"] + }, + "application/x-pilot": { + source: "nginx", + extensions: ["prc", "pdb"] + }, + "application/x-pkcs12": { + source: "apache", + compressible: false, + extensions: ["p12", "pfx"] + }, + "application/x-pkcs7-certificates": { + source: "apache", + extensions: ["p7b", "spc"] + }, + "application/x-pkcs7-certreqresp": { + source: "apache", + extensions: ["p7r"] + }, + "application/x-pki-message": { + source: "iana" + }, + "application/x-rar-compressed": { + source: "apache", + compressible: false, + extensions: ["rar"] + }, + "application/x-redhat-package-manager": { + source: "nginx", + extensions: ["rpm"] + }, + "application/x-research-info-systems": { + source: "apache", + extensions: ["ris"] + }, + "application/x-sea": { + source: "nginx", + extensions: ["sea"] + }, + "application/x-sh": { + source: "apache", + compressible: true, + extensions: ["sh"] + }, + "application/x-shar": { + source: "apache", + extensions: ["shar"] + }, + "application/x-shockwave-flash": { + source: "apache", + compressible: false, + extensions: ["swf"] + }, + "application/x-silverlight-app": { + source: "apache", + extensions: ["xap"] + }, + "application/x-sql": { + source: "apache", + extensions: ["sql"] + }, + "application/x-stuffit": { + source: "apache", + compressible: false, + extensions: ["sit"] + }, + "application/x-stuffitx": { + source: "apache", + extensions: ["sitx"] + }, + "application/x-subrip": { + source: "apache", + extensions: ["srt"] + }, + "application/x-sv4cpio": { + source: "apache", + extensions: ["sv4cpio"] + }, + "application/x-sv4crc": { + source: "apache", + extensions: ["sv4crc"] + }, + "application/x-t3vm-image": { + source: "apache", + extensions: ["t3"] + }, + "application/x-tads": { + source: "apache", + extensions: ["gam"] + }, + "application/x-tar": { + source: "apache", + compressible: true, + extensions: ["tar"] + }, + "application/x-tcl": { + source: "apache", + extensions: ["tcl", "tk"] + }, + "application/x-tex": { + source: "apache", + extensions: ["tex"] + }, + "application/x-tex-tfm": { + source: "apache", + extensions: ["tfm"] + }, + "application/x-texinfo": { + source: "apache", + extensions: ["texinfo", "texi"] + }, + "application/x-tgif": { + source: "apache", + extensions: ["obj"] + }, + "application/x-ustar": { + source: "apache", + extensions: ["ustar"] + }, + "application/x-virtualbox-hdd": { + compressible: true, + extensions: ["hdd"] + }, + "application/x-virtualbox-ova": { + compressible: true, + extensions: ["ova"] + }, + "application/x-virtualbox-ovf": { + compressible: true, + extensions: ["ovf"] + }, + "application/x-virtualbox-vbox": { + compressible: true, + extensions: ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + compressible: false, + extensions: ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + compressible: true, + extensions: ["vdi"] + }, + "application/x-virtualbox-vhd": { + compressible: true, + extensions: ["vhd"] + }, + "application/x-virtualbox-vmdk": { + compressible: true, + extensions: ["vmdk"] + }, + "application/x-wais-source": { + source: "apache", + extensions: ["src"] + }, + "application/x-web-app-manifest+json": { + compressible: true, + extensions: ["webapp"] + }, + "application/x-www-form-urlencoded": { + source: "iana", + compressible: true + }, + "application/x-x509-ca-cert": { + source: "iana", + extensions: ["der", "crt", "pem"] + }, + "application/x-x509-ca-ra-cert": { + source: "iana" + }, + "application/x-x509-next-ca-cert": { + source: "iana" + }, + "application/x-xfig": { + source: "apache", + extensions: ["fig"] + }, + "application/x-xliff+xml": { + source: "apache", + compressible: true, + extensions: ["xlf"] + }, + "application/x-xpinstall": { + source: "apache", + compressible: false, + extensions: ["xpi"] + }, + "application/x-xz": { + source: "apache", + extensions: ["xz"] + }, + "application/x-zmachine": { + source: "apache", + extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"] + }, + "application/x400-bp": { + source: "iana" + }, + "application/xacml+xml": { + source: "iana", + compressible: true + }, + "application/xaml+xml": { + source: "apache", + compressible: true, + extensions: ["xaml"] + }, + "application/xcap-att+xml": { + source: "iana", + compressible: true, + extensions: ["xav"] + }, + "application/xcap-caps+xml": { + source: "iana", + compressible: true, + extensions: ["xca"] + }, + "application/xcap-diff+xml": { + source: "iana", + compressible: true, + extensions: ["xdf"] + }, + "application/xcap-el+xml": { + source: "iana", + compressible: true, + extensions: ["xel"] + }, + "application/xcap-error+xml": { + source: "iana", + compressible: true + }, + "application/xcap-ns+xml": { + source: "iana", + compressible: true, + extensions: ["xns"] + }, + "application/xcon-conference-info+xml": { + source: "iana", + compressible: true + }, + "application/xcon-conference-info-diff+xml": { + source: "iana", + compressible: true + }, + "application/xenc+xml": { + source: "iana", + compressible: true, + extensions: ["xenc"] + }, + "application/xhtml+xml": { + source: "iana", + compressible: true, + extensions: ["xhtml", "xht"] + }, + "application/xhtml-voice+xml": { + source: "apache", + compressible: true + }, + "application/xliff+xml": { + source: "iana", + compressible: true, + extensions: ["xlf"] + }, + "application/xml": { + source: "iana", + compressible: true, + extensions: ["xml", "xsl", "xsd", "rng"] + }, + "application/xml-dtd": { + source: "iana", + compressible: true, + extensions: ["dtd"] + }, + "application/xml-external-parsed-entity": { + source: "iana" + }, + "application/xml-patch+xml": { + source: "iana", + compressible: true + }, + "application/xmpp+xml": { + source: "iana", + compressible: true + }, + "application/xop+xml": { + source: "iana", + compressible: true, + extensions: ["xop"] + }, + "application/xproc+xml": { + source: "apache", + compressible: true, + extensions: ["xpl"] + }, + "application/xslt+xml": { + source: "iana", + compressible: true, + extensions: ["xsl", "xslt"] + }, + "application/xspf+xml": { + source: "apache", + compressible: true, + extensions: ["xspf"] + }, + "application/xv+xml": { + source: "iana", + compressible: true, + extensions: ["mxml", "xhvml", "xvml", "xvm"] + }, + "application/yang": { + source: "iana", + extensions: ["yang"] + }, + "application/yang-data+json": { + source: "iana", + compressible: true + }, + "application/yang-data+xml": { + source: "iana", + compressible: true + }, + "application/yang-patch+json": { + source: "iana", + compressible: true + }, + "application/yang-patch+xml": { + source: "iana", + compressible: true + }, + "application/yin+xml": { + source: "iana", + compressible: true, + extensions: ["yin"] + }, + "application/zip": { + source: "iana", + compressible: false, + extensions: ["zip"] + }, + "application/zlib": { + source: "iana" + }, + "application/zstd": { + source: "iana" + }, + "audio/1d-interleaved-parityfec": { + source: "iana" + }, + "audio/32kadpcm": { + source: "iana" + }, + "audio/3gpp": { + source: "iana", + compressible: false, + extensions: ["3gpp"] + }, + "audio/3gpp2": { + source: "iana" + }, + "audio/aac": { + source: "iana" + }, + "audio/ac3": { + source: "iana" + }, + "audio/adpcm": { + source: "apache", + extensions: ["adp"] + }, + "audio/amr": { + source: "iana", + extensions: ["amr"] + }, + "audio/amr-wb": { + source: "iana" + }, + "audio/amr-wb+": { + source: "iana" + }, + "audio/aptx": { + source: "iana" + }, + "audio/asc": { + source: "iana" + }, + "audio/atrac-advanced-lossless": { + source: "iana" + }, + "audio/atrac-x": { + source: "iana" + }, + "audio/atrac3": { + source: "iana" + }, + "audio/basic": { + source: "iana", + compressible: false, + extensions: ["au", "snd"] + }, + "audio/bv16": { + source: "iana" + }, + "audio/bv32": { + source: "iana" + }, + "audio/clearmode": { + source: "iana" + }, + "audio/cn": { + source: "iana" + }, + "audio/dat12": { + source: "iana" + }, + "audio/dls": { + source: "iana" + }, + "audio/dsr-es201108": { + source: "iana" + }, + "audio/dsr-es202050": { + source: "iana" + }, + "audio/dsr-es202211": { + source: "iana" + }, + "audio/dsr-es202212": { + source: "iana" + }, + "audio/dv": { + source: "iana" + }, + "audio/dvi4": { + source: "iana" + }, + "audio/eac3": { + source: "iana" + }, + "audio/encaprtp": { + source: "iana" + }, + "audio/evrc": { + source: "iana" + }, + "audio/evrc-qcp": { + source: "iana" + }, + "audio/evrc0": { + source: "iana" + }, + "audio/evrc1": { + source: "iana" + }, + "audio/evrcb": { + source: "iana" + }, + "audio/evrcb0": { + source: "iana" + }, + "audio/evrcb1": { + source: "iana" + }, + "audio/evrcnw": { + source: "iana" + }, + "audio/evrcnw0": { + source: "iana" + }, + "audio/evrcnw1": { + source: "iana" + }, + "audio/evrcwb": { + source: "iana" + }, + "audio/evrcwb0": { + source: "iana" + }, + "audio/evrcwb1": { + source: "iana" + }, + "audio/evs": { + source: "iana" + }, + "audio/flexfec": { + source: "iana" + }, + "audio/fwdred": { + source: "iana" + }, + "audio/g711-0": { + source: "iana" + }, + "audio/g719": { + source: "iana" + }, + "audio/g722": { + source: "iana" + }, + "audio/g7221": { + source: "iana" + }, + "audio/g723": { + source: "iana" + }, + "audio/g726-16": { + source: "iana" + }, + "audio/g726-24": { + source: "iana" + }, + "audio/g726-32": { + source: "iana" + }, + "audio/g726-40": { + source: "iana" + }, + "audio/g728": { + source: "iana" + }, + "audio/g729": { + source: "iana" + }, + "audio/g7291": { + source: "iana" + }, + "audio/g729d": { + source: "iana" + }, + "audio/g729e": { + source: "iana" + }, + "audio/gsm": { + source: "iana" + }, + "audio/gsm-efr": { + source: "iana" + }, + "audio/gsm-hr-08": { + source: "iana" + }, + "audio/ilbc": { + source: "iana" + }, + "audio/ip-mr_v2.5": { + source: "iana" + }, + "audio/isac": { + source: "apache" + }, + "audio/l16": { + source: "iana" + }, + "audio/l20": { + source: "iana" + }, + "audio/l24": { + source: "iana", + compressible: false + }, + "audio/l8": { + source: "iana" + }, + "audio/lpc": { + source: "iana" + }, + "audio/melp": { + source: "iana" + }, + "audio/melp1200": { + source: "iana" + }, + "audio/melp2400": { + source: "iana" + }, + "audio/melp600": { + source: "iana" + }, + "audio/mhas": { + source: "iana" + }, + "audio/midi": { + source: "apache", + extensions: ["mid", "midi", "kar", "rmi"] + }, + "audio/mobile-xmf": { + source: "iana", + extensions: ["mxmf"] + }, + "audio/mp3": { + compressible: false, + extensions: ["mp3"] + }, + "audio/mp4": { + source: "iana", + compressible: false, + extensions: ["m4a", "mp4a"] + }, + "audio/mp4a-latm": { + source: "iana" + }, + "audio/mpa": { + source: "iana" + }, + "audio/mpa-robust": { + source: "iana" + }, + "audio/mpeg": { + source: "iana", + compressible: false, + extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"] + }, + "audio/mpeg4-generic": { + source: "iana" + }, + "audio/musepack": { + source: "apache" + }, + "audio/ogg": { + source: "iana", + compressible: false, + extensions: ["oga", "ogg", "spx", "opus"] + }, + "audio/opus": { + source: "iana" + }, + "audio/parityfec": { + source: "iana" + }, + "audio/pcma": { + source: "iana" + }, + "audio/pcma-wb": { + source: "iana" + }, + "audio/pcmu": { + source: "iana" + }, + "audio/pcmu-wb": { + source: "iana" + }, + "audio/prs.sid": { + source: "iana" + }, + "audio/qcelp": { + source: "iana" + }, + "audio/raptorfec": { + source: "iana" + }, + "audio/red": { + source: "iana" + }, + "audio/rtp-enc-aescm128": { + source: "iana" + }, + "audio/rtp-midi": { + source: "iana" + }, + "audio/rtploopback": { + source: "iana" + }, + "audio/rtx": { + source: "iana" + }, + "audio/s3m": { + source: "apache", + extensions: ["s3m"] + }, + "audio/scip": { + source: "iana" + }, + "audio/silk": { + source: "apache", + extensions: ["sil"] + }, + "audio/smv": { + source: "iana" + }, + "audio/smv-qcp": { + source: "iana" + }, + "audio/smv0": { + source: "iana" + }, + "audio/sofa": { + source: "iana" + }, + "audio/sp-midi": { + source: "iana" + }, + "audio/speex": { + source: "iana" + }, + "audio/t140c": { + source: "iana" + }, + "audio/t38": { + source: "iana" + }, + "audio/telephone-event": { + source: "iana" + }, + "audio/tetra_acelp": { + source: "iana" + }, + "audio/tetra_acelp_bb": { + source: "iana" + }, + "audio/tone": { + source: "iana" + }, + "audio/tsvcis": { + source: "iana" + }, + "audio/uemclip": { + source: "iana" + }, + "audio/ulpfec": { + source: "iana" + }, + "audio/usac": { + source: "iana" + }, + "audio/vdvi": { + source: "iana" + }, + "audio/vmr-wb": { + source: "iana" + }, + "audio/vnd.3gpp.iufp": { + source: "iana" + }, + "audio/vnd.4sb": { + source: "iana" + }, + "audio/vnd.audiokoz": { + source: "iana" + }, + "audio/vnd.celp": { + source: "iana" + }, + "audio/vnd.cisco.nse": { + source: "iana" + }, + "audio/vnd.cmles.radio-events": { + source: "iana" + }, + "audio/vnd.cns.anp1": { + source: "iana" + }, + "audio/vnd.cns.inf1": { + source: "iana" + }, + "audio/vnd.dece.audio": { + source: "iana", + extensions: ["uva", "uvva"] + }, + "audio/vnd.digital-winds": { + source: "iana", + extensions: ["eol"] + }, + "audio/vnd.dlna.adts": { + source: "iana" + }, + "audio/vnd.dolby.heaac.1": { + source: "iana" + }, + "audio/vnd.dolby.heaac.2": { + source: "iana" + }, + "audio/vnd.dolby.mlp": { + source: "iana" + }, + "audio/vnd.dolby.mps": { + source: "iana" + }, + "audio/vnd.dolby.pl2": { + source: "iana" + }, + "audio/vnd.dolby.pl2x": { + source: "iana" + }, + "audio/vnd.dolby.pl2z": { + source: "iana" + }, + "audio/vnd.dolby.pulse.1": { + source: "iana" + }, + "audio/vnd.dra": { + source: "iana", + extensions: ["dra"] + }, + "audio/vnd.dts": { + source: "iana", + extensions: ["dts"] + }, + "audio/vnd.dts.hd": { + source: "iana", + extensions: ["dtshd"] + }, + "audio/vnd.dts.uhd": { + source: "iana" + }, + "audio/vnd.dvb.file": { + source: "iana" + }, + "audio/vnd.everad.plj": { + source: "iana" + }, + "audio/vnd.hns.audio": { + source: "iana" + }, + "audio/vnd.lucent.voice": { + source: "iana", + extensions: ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + source: "iana", + extensions: ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + source: "iana" + }, + "audio/vnd.nortel.vbk": { + source: "iana" + }, + "audio/vnd.nuera.ecelp4800": { + source: "iana", + extensions: ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + source: "iana", + extensions: ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + source: "iana", + extensions: ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + source: "iana" + }, + "audio/vnd.presonus.multitrack": { + source: "iana" + }, + "audio/vnd.qcelp": { + source: "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + source: "iana" + }, + "audio/vnd.rip": { + source: "iana", + extensions: ["rip"] + }, + "audio/vnd.rn-realaudio": { + compressible: false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + source: "iana" + }, + "audio/vnd.vmx.cvsd": { + source: "iana" + }, + "audio/vnd.wave": { + compressible: false + }, + "audio/vorbis": { + source: "iana", + compressible: false + }, + "audio/vorbis-config": { + source: "iana" + }, + "audio/wav": { + compressible: false, + extensions: ["wav"] + }, + "audio/wave": { + compressible: false, + extensions: ["wav"] + }, + "audio/webm": { + source: "apache", + compressible: false, + extensions: ["weba"] + }, + "audio/x-aac": { + source: "apache", + compressible: false, + extensions: ["aac"] + }, + "audio/x-aiff": { + source: "apache", + extensions: ["aif", "aiff", "aifc"] + }, + "audio/x-caf": { + source: "apache", + compressible: false, + extensions: ["caf"] + }, + "audio/x-flac": { + source: "apache", + extensions: ["flac"] + }, + "audio/x-m4a": { + source: "nginx", + extensions: ["m4a"] + }, + "audio/x-matroska": { + source: "apache", + extensions: ["mka"] + }, + "audio/x-mpegurl": { + source: "apache", + extensions: ["m3u"] + }, + "audio/x-ms-wax": { + source: "apache", + extensions: ["wax"] + }, + "audio/x-ms-wma": { + source: "apache", + extensions: ["wma"] + }, + "audio/x-pn-realaudio": { + source: "apache", + extensions: ["ram", "ra"] + }, + "audio/x-pn-realaudio-plugin": { + source: "apache", + extensions: ["rmp"] + }, + "audio/x-realaudio": { + source: "nginx", + extensions: ["ra"] + }, + "audio/x-tta": { + source: "apache" + }, + "audio/x-wav": { + source: "apache", + extensions: ["wav"] + }, + "audio/xm": { + source: "apache", + extensions: ["xm"] + }, + "chemical/x-cdx": { + source: "apache", + extensions: ["cdx"] + }, + "chemical/x-cif": { + source: "apache", + extensions: ["cif"] + }, + "chemical/x-cmdf": { + source: "apache", + extensions: ["cmdf"] + }, + "chemical/x-cml": { + source: "apache", + extensions: ["cml"] + }, + "chemical/x-csml": { + source: "apache", + extensions: ["csml"] + }, + "chemical/x-pdb": { + source: "apache" + }, + "chemical/x-xyz": { + source: "apache", + extensions: ["xyz"] + }, + "font/collection": { + source: "iana", + extensions: ["ttc"] + }, + "font/otf": { + source: "iana", + compressible: true, + extensions: ["otf"] + }, + "font/sfnt": { + source: "iana" + }, + "font/ttf": { + source: "iana", + compressible: true, + extensions: ["ttf"] + }, + "font/woff": { + source: "iana", + extensions: ["woff"] + }, + "font/woff2": { + source: "iana", + extensions: ["woff2"] + }, + "image/aces": { + source: "iana", + extensions: ["exr"] + }, + "image/apng": { + compressible: false, + extensions: ["apng"] + }, + "image/avci": { + source: "iana", + extensions: ["avci"] + }, + "image/avcs": { + source: "iana", + extensions: ["avcs"] + }, + "image/avif": { + source: "iana", + compressible: false, + extensions: ["avif"] + }, + "image/bmp": { + source: "iana", + compressible: true, + extensions: ["bmp"] + }, + "image/cgm": { + source: "iana", + extensions: ["cgm"] + }, + "image/dicom-rle": { + source: "iana", + extensions: ["drle"] + }, + "image/emf": { + source: "iana", + extensions: ["emf"] + }, + "image/fits": { + source: "iana", + extensions: ["fits"] + }, + "image/g3fax": { + source: "iana", + extensions: ["g3"] + }, + "image/gif": { + source: "iana", + compressible: false, + extensions: ["gif"] + }, + "image/heic": { + source: "iana", + extensions: ["heic"] + }, + "image/heic-sequence": { + source: "iana", + extensions: ["heics"] + }, + "image/heif": { + source: "iana", + extensions: ["heif"] + }, + "image/heif-sequence": { + source: "iana", + extensions: ["heifs"] + }, + "image/hej2k": { + source: "iana", + extensions: ["hej2"] + }, + "image/hsj2": { + source: "iana", + extensions: ["hsj2"] + }, + "image/ief": { + source: "iana", + extensions: ["ief"] + }, + "image/jls": { + source: "iana", + extensions: ["jls"] + }, + "image/jp2": { + source: "iana", + compressible: false, + extensions: ["jp2", "jpg2"] + }, + "image/jpeg": { + source: "iana", + compressible: false, + extensions: ["jpeg", "jpg", "jpe"] + }, + "image/jph": { + source: "iana", + extensions: ["jph"] + }, + "image/jphc": { + source: "iana", + extensions: ["jhc"] + }, + "image/jpm": { + source: "iana", + compressible: false, + extensions: ["jpm"] + }, + "image/jpx": { + source: "iana", + compressible: false, + extensions: ["jpx", "jpf"] + }, + "image/jxr": { + source: "iana", + extensions: ["jxr"] + }, + "image/jxra": { + source: "iana", + extensions: ["jxra"] + }, + "image/jxrs": { + source: "iana", + extensions: ["jxrs"] + }, + "image/jxs": { + source: "iana", + extensions: ["jxs"] + }, + "image/jxsc": { + source: "iana", + extensions: ["jxsc"] + }, + "image/jxsi": { + source: "iana", + extensions: ["jxsi"] + }, + "image/jxss": { + source: "iana", + extensions: ["jxss"] + }, + "image/ktx": { + source: "iana", + extensions: ["ktx"] + }, + "image/ktx2": { + source: "iana", + extensions: ["ktx2"] + }, + "image/naplps": { + source: "iana" + }, + "image/pjpeg": { + compressible: false + }, + "image/png": { + source: "iana", + compressible: false, + extensions: ["png"] + }, + "image/prs.btif": { + source: "iana", + extensions: ["btif"] + }, + "image/prs.pti": { + source: "iana", + extensions: ["pti"] + }, + "image/pwg-raster": { + source: "iana" + }, + "image/sgi": { + source: "apache", + extensions: ["sgi"] + }, + "image/svg+xml": { + source: "iana", + compressible: true, + extensions: ["svg", "svgz"] + }, + "image/t38": { + source: "iana", + extensions: ["t38"] + }, + "image/tiff": { + source: "iana", + compressible: false, + extensions: ["tif", "tiff"] + }, + "image/tiff-fx": { + source: "iana", + extensions: ["tfx"] + }, + "image/vnd.adobe.photoshop": { + source: "iana", + compressible: true, + extensions: ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + source: "iana", + extensions: ["azv"] + }, + "image/vnd.cns.inf2": { + source: "iana" + }, + "image/vnd.dece.graphic": { + source: "iana", + extensions: ["uvi", "uvvi", "uvg", "uvvg"] + }, + "image/vnd.djvu": { + source: "iana", + extensions: ["djvu", "djv"] + }, + "image/vnd.dvb.subtitle": { + source: "iana", + extensions: ["sub"] + }, + "image/vnd.dwg": { + source: "iana", + extensions: ["dwg"] + }, + "image/vnd.dxf": { + source: "iana", + extensions: ["dxf"] + }, + "image/vnd.fastbidsheet": { + source: "iana", + extensions: ["fbs"] + }, + "image/vnd.fpx": { + source: "iana", + extensions: ["fpx"] + }, + "image/vnd.fst": { + source: "iana", + extensions: ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + source: "iana", + extensions: ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + source: "iana", + extensions: ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + source: "iana" + }, + "image/vnd.microsoft.icon": { + source: "iana", + compressible: true, + extensions: ["ico"] + }, + "image/vnd.mix": { + source: "iana" + }, + "image/vnd.mozilla.apng": { + source: "iana" + }, + "image/vnd.ms-dds": { + compressible: true, + extensions: ["dds"] + }, + "image/vnd.ms-modi": { + source: "iana", + extensions: ["mdi"] + }, + "image/vnd.ms-photo": { + source: "apache", + extensions: ["wdp"] + }, + "image/vnd.net-fpx": { + source: "iana", + extensions: ["npx"] + }, + "image/vnd.pco.b16": { + source: "iana", + extensions: ["b16"] + }, + "image/vnd.radiance": { + source: "iana" + }, + "image/vnd.sealed.png": { + source: "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + source: "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + source: "iana" + }, + "image/vnd.svf": { + source: "iana" + }, + "image/vnd.tencent.tap": { + source: "iana", + extensions: ["tap"] + }, + "image/vnd.valve.source.texture": { + source: "iana", + extensions: ["vtf"] + }, + "image/vnd.wap.wbmp": { + source: "iana", + extensions: ["wbmp"] + }, + "image/vnd.xiff": { + source: "iana", + extensions: ["xif"] + }, + "image/vnd.zbrush.pcx": { + source: "iana", + extensions: ["pcx"] + }, + "image/webp": { + source: "apache", + extensions: ["webp"] + }, + "image/wmf": { + source: "iana", + extensions: ["wmf"] + }, + "image/x-3ds": { + source: "apache", + extensions: ["3ds"] + }, + "image/x-cmu-raster": { + source: "apache", + extensions: ["ras"] + }, + "image/x-cmx": { + source: "apache", + extensions: ["cmx"] + }, + "image/x-freehand": { + source: "apache", + extensions: ["fh", "fhc", "fh4", "fh5", "fh7"] + }, + "image/x-icon": { + source: "apache", + compressible: true, + extensions: ["ico"] + }, + "image/x-jng": { + source: "nginx", + extensions: ["jng"] + }, + "image/x-mrsid-image": { + source: "apache", + extensions: ["sid"] + }, + "image/x-ms-bmp": { + source: "nginx", + compressible: true, + extensions: ["bmp"] + }, + "image/x-pcx": { + source: "apache", + extensions: ["pcx"] + }, + "image/x-pict": { + source: "apache", + extensions: ["pic", "pct"] + }, + "image/x-portable-anymap": { + source: "apache", + extensions: ["pnm"] + }, + "image/x-portable-bitmap": { + source: "apache", + extensions: ["pbm"] + }, + "image/x-portable-graymap": { + source: "apache", + extensions: ["pgm"] + }, + "image/x-portable-pixmap": { + source: "apache", + extensions: ["ppm"] + }, + "image/x-rgb": { + source: "apache", + extensions: ["rgb"] + }, + "image/x-tga": { + source: "apache", + extensions: ["tga"] + }, + "image/x-xbitmap": { + source: "apache", + extensions: ["xbm"] + }, + "image/x-xcf": { + compressible: false + }, + "image/x-xpixmap": { + source: "apache", + extensions: ["xpm"] + }, + "image/x-xwindowdump": { + source: "apache", + extensions: ["xwd"] + }, + "message/cpim": { + source: "iana" + }, + "message/delivery-status": { + source: "iana" + }, + "message/disposition-notification": { + source: "iana", + extensions: [ + "disposition-notification" + ] + }, + "message/external-body": { + source: "iana" + }, + "message/feedback-report": { + source: "iana" + }, + "message/global": { + source: "iana", + extensions: ["u8msg"] + }, + "message/global-delivery-status": { + source: "iana", + extensions: ["u8dsn"] + }, + "message/global-disposition-notification": { + source: "iana", + extensions: ["u8mdn"] + }, + "message/global-headers": { + source: "iana", + extensions: ["u8hdr"] + }, + "message/http": { + source: "iana", + compressible: false + }, + "message/imdn+xml": { + source: "iana", + compressible: true + }, + "message/news": { + source: "iana" + }, + "message/partial": { + source: "iana", + compressible: false + }, + "message/rfc822": { + source: "iana", + compressible: true, + extensions: ["eml", "mime"] + }, + "message/s-http": { + source: "iana" + }, + "message/sip": { + source: "iana" + }, + "message/sipfrag": { + source: "iana" + }, + "message/tracking-status": { + source: "iana" + }, + "message/vnd.si.simp": { + source: "iana" + }, + "message/vnd.wfa.wsc": { + source: "iana", + extensions: ["wsc"] + }, + "model/3mf": { + source: "iana", + extensions: ["3mf"] + }, + "model/e57": { + source: "iana" + }, + "model/gltf+json": { + source: "iana", + compressible: true, + extensions: ["gltf"] + }, + "model/gltf-binary": { + source: "iana", + compressible: true, + extensions: ["glb"] + }, + "model/iges": { + source: "iana", + compressible: false, + extensions: ["igs", "iges"] + }, + "model/mesh": { + source: "iana", + compressible: false, + extensions: ["msh", "mesh", "silo"] + }, + "model/mtl": { + source: "iana", + extensions: ["mtl"] + }, + "model/obj": { + source: "iana", + extensions: ["obj"] + }, + "model/step": { + source: "iana" + }, + "model/step+xml": { + source: "iana", + compressible: true, + extensions: ["stpx"] + }, + "model/step+zip": { + source: "iana", + compressible: false, + extensions: ["stpz"] + }, + "model/step-xml+zip": { + source: "iana", + compressible: false, + extensions: ["stpxz"] + }, + "model/stl": { + source: "iana", + extensions: ["stl"] + }, + "model/vnd.collada+xml": { + source: "iana", + compressible: true, + extensions: ["dae"] + }, + "model/vnd.dwf": { + source: "iana", + extensions: ["dwf"] + }, + "model/vnd.flatland.3dml": { + source: "iana" + }, + "model/vnd.gdl": { + source: "iana", + extensions: ["gdl"] + }, + "model/vnd.gs-gdl": { + source: "apache" + }, + "model/vnd.gs.gdl": { + source: "iana" + }, + "model/vnd.gtw": { + source: "iana", + extensions: ["gtw"] + }, + "model/vnd.moml+xml": { + source: "iana", + compressible: true + }, + "model/vnd.mts": { + source: "iana", + extensions: ["mts"] + }, + "model/vnd.opengex": { + source: "iana", + extensions: ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + source: "iana", + extensions: ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + source: "iana", + extensions: ["x_t"] + }, + "model/vnd.pytha.pyox": { + source: "iana" + }, + "model/vnd.rosette.annotated-data-model": { + source: "iana" + }, + "model/vnd.sap.vds": { + source: "iana", + extensions: ["vds"] + }, + "model/vnd.usdz+zip": { + source: "iana", + compressible: false, + extensions: ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + source: "iana", + extensions: ["bsp"] + }, + "model/vnd.vtu": { + source: "iana", + extensions: ["vtu"] + }, + "model/vrml": { + source: "iana", + compressible: false, + extensions: ["wrl", "vrml"] + }, + "model/x3d+binary": { + source: "apache", + compressible: false, + extensions: ["x3db", "x3dbz"] + }, + "model/x3d+fastinfoset": { + source: "iana", + extensions: ["x3db"] + }, + "model/x3d+vrml": { + source: "apache", + compressible: false, + extensions: ["x3dv", "x3dvz"] + }, + "model/x3d+xml": { + source: "iana", + compressible: true, + extensions: ["x3d", "x3dz"] + }, + "model/x3d-vrml": { + source: "iana", + extensions: ["x3dv"] + }, + "multipart/alternative": { + source: "iana", + compressible: false + }, + "multipart/appledouble": { + source: "iana" + }, + "multipart/byteranges": { + source: "iana" + }, + "multipart/digest": { + source: "iana" + }, + "multipart/encrypted": { + source: "iana", + compressible: false + }, + "multipart/form-data": { + source: "iana", + compressible: false + }, + "multipart/header-set": { + source: "iana" + }, + "multipart/mixed": { + source: "iana" + }, + "multipart/multilingual": { + source: "iana" + }, + "multipart/parallel": { + source: "iana" + }, + "multipart/related": { + source: "iana", + compressible: false + }, + "multipart/report": { + source: "iana" + }, + "multipart/signed": { + source: "iana", + compressible: false + }, + "multipart/vnd.bint.med-plus": { + source: "iana" + }, + "multipart/voice-message": { + source: "iana" + }, + "multipart/x-mixed-replace": { + source: "iana" + }, + "text/1d-interleaved-parityfec": { + source: "iana" + }, + "text/cache-manifest": { + source: "iana", + compressible: true, + extensions: ["appcache", "manifest"] + }, + "text/calendar": { + source: "iana", + extensions: ["ics", "ifb"] + }, + "text/calender": { + compressible: true + }, + "text/cmd": { + compressible: true + }, + "text/coffeescript": { + extensions: ["coffee", "litcoffee"] + }, + "text/cql": { + source: "iana" + }, + "text/cql-expression": { + source: "iana" + }, + "text/cql-identifier": { + source: "iana" + }, + "text/css": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["css"] + }, + "text/csv": { + source: "iana", + compressible: true, + extensions: ["csv"] + }, + "text/csv-schema": { + source: "iana" + }, + "text/directory": { + source: "iana" + }, + "text/dns": { + source: "iana" + }, + "text/ecmascript": { + source: "iana" + }, + "text/encaprtp": { + source: "iana" + }, + "text/enriched": { + source: "iana" + }, + "text/fhirpath": { + source: "iana" + }, + "text/flexfec": { + source: "iana" + }, + "text/fwdred": { + source: "iana" + }, + "text/gff3": { + source: "iana" + }, + "text/grammar-ref-list": { + source: "iana" + }, + "text/html": { + source: "iana", + compressible: true, + extensions: ["html", "htm", "shtml"] + }, + "text/jade": { + extensions: ["jade"] + }, + "text/javascript": { + source: "iana", + compressible: true + }, + "text/jcr-cnd": { + source: "iana" + }, + "text/jsx": { + compressible: true, + extensions: ["jsx"] + }, + "text/less": { + compressible: true, + extensions: ["less"] + }, + "text/markdown": { + source: "iana", + compressible: true, + extensions: ["markdown", "md"] + }, + "text/mathml": { + source: "nginx", + extensions: ["mml"] + }, + "text/mdx": { + compressible: true, + extensions: ["mdx"] + }, + "text/mizar": { + source: "iana" + }, + "text/n3": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["n3"] + }, + "text/parameters": { + source: "iana", + charset: "UTF-8" + }, + "text/parityfec": { + source: "iana" + }, + "text/plain": { + source: "iana", + compressible: true, + extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"] + }, + "text/provenance-notation": { + source: "iana", + charset: "UTF-8" + }, + "text/prs.fallenstein.rst": { + source: "iana" + }, + "text/prs.lines.tag": { + source: "iana", + extensions: ["dsc"] + }, + "text/prs.prop.logic": { + source: "iana" + }, + "text/raptorfec": { + source: "iana" + }, + "text/red": { + source: "iana" + }, + "text/rfc822-headers": { + source: "iana" + }, + "text/richtext": { + source: "iana", + compressible: true, + extensions: ["rtx"] + }, + "text/rtf": { + source: "iana", + compressible: true, + extensions: ["rtf"] + }, + "text/rtp-enc-aescm128": { + source: "iana" + }, + "text/rtploopback": { + source: "iana" + }, + "text/rtx": { + source: "iana" + }, + "text/sgml": { + source: "iana", + extensions: ["sgml", "sgm"] + }, + "text/shaclc": { + source: "iana" + }, + "text/shex": { + source: "iana", + extensions: ["shex"] + }, + "text/slim": { + extensions: ["slim", "slm"] + }, + "text/spdx": { + source: "iana", + extensions: ["spdx"] + }, + "text/strings": { + source: "iana" + }, + "text/stylus": { + extensions: ["stylus", "styl"] + }, + "text/t140": { + source: "iana" + }, + "text/tab-separated-values": { + source: "iana", + compressible: true, + extensions: ["tsv"] + }, + "text/troff": { + source: "iana", + extensions: ["t", "tr", "roff", "man", "me", "ms"] + }, + "text/turtle": { + source: "iana", + charset: "UTF-8", + extensions: ["ttl"] + }, + "text/ulpfec": { + source: "iana" + }, + "text/uri-list": { + source: "iana", + compressible: true, + extensions: ["uri", "uris", "urls"] + }, + "text/vcard": { + source: "iana", + compressible: true, + extensions: ["vcard"] + }, + "text/vnd.a": { + source: "iana" + }, + "text/vnd.abc": { + source: "iana" + }, + "text/vnd.ascii-art": { + source: "iana" + }, + "text/vnd.curl": { + source: "iana", + extensions: ["curl"] + }, + "text/vnd.curl.dcurl": { + source: "apache", + extensions: ["dcurl"] + }, + "text/vnd.curl.mcurl": { + source: "apache", + extensions: ["mcurl"] + }, + "text/vnd.curl.scurl": { + source: "apache", + extensions: ["scurl"] + }, + "text/vnd.debian.copyright": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.dmclientscript": { + source: "iana" + }, + "text/vnd.dvb.subtitle": { + source: "iana", + extensions: ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.familysearch.gedcom": { + source: "iana", + extensions: ["ged"] + }, + "text/vnd.ficlab.flt": { + source: "iana" + }, + "text/vnd.fly": { + source: "iana", + extensions: ["fly"] + }, + "text/vnd.fmi.flexstor": { + source: "iana", + extensions: ["flx"] + }, + "text/vnd.gml": { + source: "iana" + }, + "text/vnd.graphviz": { + source: "iana", + extensions: ["gv"] + }, + "text/vnd.hans": { + source: "iana" + }, + "text/vnd.hgl": { + source: "iana" + }, + "text/vnd.in3d.3dml": { + source: "iana", + extensions: ["3dml"] + }, + "text/vnd.in3d.spot": { + source: "iana", + extensions: ["spot"] + }, + "text/vnd.iptc.newsml": { + source: "iana" + }, + "text/vnd.iptc.nitf": { + source: "iana" + }, + "text/vnd.latex-z": { + source: "iana" + }, + "text/vnd.motorola.reflex": { + source: "iana" + }, + "text/vnd.ms-mediapackage": { + source: "iana" + }, + "text/vnd.net2phone.commcenter.command": { + source: "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + source: "iana" + }, + "text/vnd.senx.warpscript": { + source: "iana" + }, + "text/vnd.si.uricatalogue": { + source: "iana" + }, + "text/vnd.sosi": { + source: "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + source: "iana", + charset: "UTF-8", + extensions: ["jad"] + }, + "text/vnd.trolltech.linguist": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.wap.si": { + source: "iana" + }, + "text/vnd.wap.sl": { + source: "iana" + }, + "text/vnd.wap.wml": { + source: "iana", + extensions: ["wml"] + }, + "text/vnd.wap.wmlscript": { + source: "iana", + extensions: ["wmls"] + }, + "text/vtt": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["vtt"] + }, + "text/x-asm": { + source: "apache", + extensions: ["s", "asm"] + }, + "text/x-c": { + source: "apache", + extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"] + }, + "text/x-component": { + source: "nginx", + extensions: ["htc"] + }, + "text/x-fortran": { + source: "apache", + extensions: ["f", "for", "f77", "f90"] + }, + "text/x-gwt-rpc": { + compressible: true + }, + "text/x-handlebars-template": { + extensions: ["hbs"] + }, + "text/x-java-source": { + source: "apache", + extensions: ["java"] + }, + "text/x-jquery-tmpl": { + compressible: true + }, + "text/x-lua": { + extensions: ["lua"] + }, + "text/x-markdown": { + compressible: true, + extensions: ["mkd"] + }, + "text/x-nfo": { + source: "apache", + extensions: ["nfo"] + }, + "text/x-opml": { + source: "apache", + extensions: ["opml"] + }, + "text/x-org": { + compressible: true, + extensions: ["org"] + }, + "text/x-pascal": { + source: "apache", + extensions: ["p", "pas"] + }, + "text/x-processing": { + compressible: true, + extensions: ["pde"] + }, + "text/x-sass": { + extensions: ["sass"] + }, + "text/x-scss": { + extensions: ["scss"] + }, + "text/x-setext": { + source: "apache", + extensions: ["etx"] + }, + "text/x-sfv": { + source: "apache", + extensions: ["sfv"] + }, + "text/x-suse-ymp": { + compressible: true, + extensions: ["ymp"] + }, + "text/x-uuencode": { + source: "apache", + extensions: ["uu"] + }, + "text/x-vcalendar": { + source: "apache", + extensions: ["vcs"] + }, + "text/x-vcard": { + source: "apache", + extensions: ["vcf"] + }, + "text/xml": { + source: "iana", + compressible: true, + extensions: ["xml"] + }, + "text/xml-external-parsed-entity": { + source: "iana" + }, + "text/yaml": { + compressible: true, + extensions: ["yaml", "yml"] + }, + "video/1d-interleaved-parityfec": { + source: "iana" + }, + "video/3gpp": { + source: "iana", + extensions: ["3gp", "3gpp"] + }, + "video/3gpp-tt": { + source: "iana" + }, + "video/3gpp2": { + source: "iana", + extensions: ["3g2"] + }, + "video/av1": { + source: "iana" + }, + "video/bmpeg": { + source: "iana" + }, + "video/bt656": { + source: "iana" + }, + "video/celb": { + source: "iana" + }, + "video/dv": { + source: "iana" + }, + "video/encaprtp": { + source: "iana" + }, + "video/ffv1": { + source: "iana" + }, + "video/flexfec": { + source: "iana" + }, + "video/h261": { + source: "iana", + extensions: ["h261"] + }, + "video/h263": { + source: "iana", + extensions: ["h263"] + }, + "video/h263-1998": { + source: "iana" + }, + "video/h263-2000": { + source: "iana" + }, + "video/h264": { + source: "iana", + extensions: ["h264"] + }, + "video/h264-rcdo": { + source: "iana" + }, + "video/h264-svc": { + source: "iana" + }, + "video/h265": { + source: "iana" + }, + "video/iso.segment": { + source: "iana", + extensions: ["m4s"] + }, + "video/jpeg": { + source: "iana", + extensions: ["jpgv"] + }, + "video/jpeg2000": { + source: "iana" + }, + "video/jpm": { + source: "apache", + extensions: ["jpm", "jpgm"] + }, + "video/jxsv": { + source: "iana" + }, + "video/mj2": { + source: "iana", + extensions: ["mj2", "mjp2"] + }, + "video/mp1s": { + source: "iana" + }, + "video/mp2p": { + source: "iana" + }, + "video/mp2t": { + source: "iana", + extensions: ["ts"] + }, + "video/mp4": { + source: "iana", + compressible: false, + extensions: ["mp4", "mp4v", "mpg4"] + }, + "video/mp4v-es": { + source: "iana" + }, + "video/mpeg": { + source: "iana", + compressible: false, + extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"] + }, + "video/mpeg4-generic": { + source: "iana" + }, + "video/mpv": { + source: "iana" + }, + "video/nv": { + source: "iana" + }, + "video/ogg": { + source: "iana", + compressible: false, + extensions: ["ogv"] + }, + "video/parityfec": { + source: "iana" + }, + "video/pointer": { + source: "iana" + }, + "video/quicktime": { + source: "iana", + compressible: false, + extensions: ["qt", "mov"] + }, + "video/raptorfec": { + source: "iana" + }, + "video/raw": { + source: "iana" + }, + "video/rtp-enc-aescm128": { + source: "iana" + }, + "video/rtploopback": { + source: "iana" + }, + "video/rtx": { + source: "iana" + }, + "video/scip": { + source: "iana" + }, + "video/smpte291": { + source: "iana" + }, + "video/smpte292m": { + source: "iana" + }, + "video/ulpfec": { + source: "iana" + }, + "video/vc1": { + source: "iana" + }, + "video/vc2": { + source: "iana" + }, + "video/vnd.cctv": { + source: "iana" + }, + "video/vnd.dece.hd": { + source: "iana", + extensions: ["uvh", "uvvh"] + }, + "video/vnd.dece.mobile": { + source: "iana", + extensions: ["uvm", "uvvm"] + }, + "video/vnd.dece.mp4": { + source: "iana" + }, + "video/vnd.dece.pd": { + source: "iana", + extensions: ["uvp", "uvvp"] + }, + "video/vnd.dece.sd": { + source: "iana", + extensions: ["uvs", "uvvs"] + }, + "video/vnd.dece.video": { + source: "iana", + extensions: ["uvv", "uvvv"] + }, + "video/vnd.directv.mpeg": { + source: "iana" + }, + "video/vnd.directv.mpeg-tts": { + source: "iana" + }, + "video/vnd.dlna.mpeg-tts": { + source: "iana" + }, + "video/vnd.dvb.file": { + source: "iana", + extensions: ["dvb"] + }, + "video/vnd.fvt": { + source: "iana", + extensions: ["fvt"] + }, + "video/vnd.hns.video": { + source: "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + source: "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + source: "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + source: "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + source: "iana" + }, + "video/vnd.iptvforum.ttsavc": { + source: "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + source: "iana" + }, + "video/vnd.motorola.video": { + source: "iana" + }, + "video/vnd.motorola.videop": { + source: "iana" + }, + "video/vnd.mpegurl": { + source: "iana", + extensions: ["mxu", "m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + source: "iana", + extensions: ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + source: "iana" + }, + "video/vnd.nokia.mp4vr": { + source: "iana" + }, + "video/vnd.nokia.videovoip": { + source: "iana" + }, + "video/vnd.objectvideo": { + source: "iana" + }, + "video/vnd.radgamettools.bink": { + source: "iana" + }, + "video/vnd.radgamettools.smacker": { + source: "iana" + }, + "video/vnd.sealed.mpeg1": { + source: "iana" + }, + "video/vnd.sealed.mpeg4": { + source: "iana" + }, + "video/vnd.sealed.swf": { + source: "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + source: "iana" + }, + "video/vnd.uvvu.mp4": { + source: "iana", + extensions: ["uvu", "uvvu"] + }, + "video/vnd.vivo": { + source: "iana", + extensions: ["viv"] + }, + "video/vnd.youtube.yt": { + source: "iana" + }, + "video/vp8": { + source: "iana" + }, + "video/vp9": { + source: "iana" + }, + "video/webm": { + source: "apache", + compressible: false, + extensions: ["webm"] + }, + "video/x-f4v": { + source: "apache", + extensions: ["f4v"] + }, + "video/x-fli": { + source: "apache", + extensions: ["fli"] + }, + "video/x-flv": { + source: "apache", + compressible: false, + extensions: ["flv"] + }, + "video/x-m4v": { + source: "apache", + extensions: ["m4v"] + }, + "video/x-matroska": { + source: "apache", + compressible: false, + extensions: ["mkv", "mk3d", "mks"] + }, + "video/x-mng": { + source: "apache", + extensions: ["mng"] + }, + "video/x-ms-asf": { + source: "apache", + extensions: ["asf", "asx"] + }, + "video/x-ms-vob": { + source: "apache", + extensions: ["vob"] + }, + "video/x-ms-wm": { + source: "apache", + extensions: ["wm"] + }, + "video/x-ms-wmv": { + source: "apache", + compressible: false, + extensions: ["wmv"] + }, + "video/x-ms-wmx": { + source: "apache", + extensions: ["wmx"] + }, + "video/x-ms-wvx": { + source: "apache", + extensions: ["wvx"] + }, + "video/x-msvideo": { + source: "apache", + extensions: ["avi"] + }, + "video/x-sgi-movie": { + source: "apache", + extensions: ["movie"] + }, + "video/x-smv": { + source: "apache", + extensions: ["smv"] + }, + "x-conference/x-cooltalk": { + source: "apache", + extensions: ["ice"] }, - adapters: knownAdapters2 + "x-shader/x-fragment": { + compressible: true + }, + "x-shader/x-vertex": { + compressible: true + } }; - function throwIfCancellationRequested2(config3) { - if (config3.cancelToken) { - config3.cancelToken.throwIfRequested(); + } +}); + +// node_modules/mime-db/index.js +var require_mime_db = __commonJS({ + "node_modules/mime-db/index.js"(exports2, module2) { + module2.exports = require_db(); + } +}); + +// node_modules/mime-types/index.js +var require_mime_types = __commonJS({ + "node_modules/mime-types/index.js"(exports2) { + "use strict"; + var db = require_mime_db(); + var extname = __require("path").extname; + var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; + var TEXT_TYPE_REGEXP = /^text\//i; + exports2.charset = charset; + exports2.charsets = { lookup: charset }; + exports2.contentType = contentType; + exports2.extension = extension; + exports2.extensions = /* @__PURE__ */ Object.create(null); + exports2.lookup = lookup; + exports2.types = /* @__PURE__ */ Object.create(null); + populateMaps(exports2.extensions, exports2.types); + function charset(type) { + if (!type || typeof type !== "string") { + return false; } - if (config3.signal && config3.signal.aborted) { - throw new CanceledError3(null, config3); + var match = EXTRACT_TYPE_REGEXP.exec(type); + var mime = match && db[match[1].toLowerCase()]; + if (mime && mime.charset) { + return mime.charset; } - } - function dispatchRequest2(config3) { - throwIfCancellationRequested2(config3); - config3.headers = AxiosHeaders$1.from(config3.headers); - config3.data = transformData2.call( - config3, - config3.transformRequest - ); - if (["post", "put", "patch"].indexOf(config3.method) !== -1) { - config3.headers.setContentType("application/x-www-form-urlencoded", false); + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return "UTF-8"; } - const adapter = adapters.getAdapter(config3.adapter || defaults$1.adapter); - return adapter(config3).then(function onAdapterResolution(response) { - throwIfCancellationRequested2(config3); - response.data = transformData2.call( - config3, - config3.transformResponse, - response - ); - response.headers = AxiosHeaders$1.from(response.headers); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel3(reason)) { - throwIfCancellationRequested2(config3); - if (reason && reason.response) { - reason.response.data = transformData2.call( - config3, - config3.transformResponse, - reason.response - ); - reason.response.headers = AxiosHeaders$1.from(reason.response.headers); - } - } - return Promise.reject(reason); - }); + return false; } - var validators$1 = {}; - ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => { - validators$1[type] = function validator2(thing) { - return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type; - }; - }); - var deprecatedWarnings2 = {}; - validators$1.transitional = function transitional2(validator2, version4, message) { - function formatMessage(opt, desc) { - return "[Axios v" + VERSION3 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); + function contentType(str) { + if (!str || typeof str !== "string") { + return false; } - return (value, opt, opts) => { - if (validator2 === false) { - throw new AxiosError3( - formatMessage(opt, " has been removed" + (version4 ? " in " + version4 : "")), - AxiosError3.ERR_DEPRECATED - ); - } - if (version4 && !deprecatedWarnings2[opt]) { - deprecatedWarnings2[opt] = true; - console.warn( - formatMessage( - opt, - " has been deprecated since v" + version4 + " and will be removed in the near future" - ) - ); - } - return validator2 ? validator2(value, opt, opts) : true; - }; - }; - validators$1.spelling = function spelling2(correctSpelling) { - return (value, opt) => { - console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); - return true; - }; - }; - function assertOptions2(options, schema, allowUnknown) { - if (typeof options !== "object") { - throw new AxiosError3("options must be an object", AxiosError3.ERR_BAD_OPTION_VALUE); + var mime = str.indexOf("/") === -1 ? exports2.lookup(str) : str; + if (!mime) { + return false; } - const keys = Object.keys(options); - let i = keys.length; - while (i-- > 0) { - const opt = keys[i]; - const validator2 = schema[opt]; - if (validator2) { - const value = options[opt]; - const result = value === void 0 || validator2(value, opt, options); - if (result !== true) { - throw new AxiosError3("option " + opt + " must be " + result, AxiosError3.ERR_BAD_OPTION_VALUE); - } - continue; - } - if (allowUnknown !== true) { - throw new AxiosError3("Unknown option " + opt, AxiosError3.ERR_BAD_OPTION); - } + if (mime.indexOf("charset") === -1) { + var charset2 = exports2.charset(mime); + if (charset2) mime += "; charset=" + charset2.toLowerCase(); } + return mime; } - var validator = { - assertOptions: assertOptions2, - validators: validators$1 - }; - var validators3 = validator.validators; - var Axios3 = class { - constructor(instanceConfig) { - this.defaults = instanceConfig || {}; - this.interceptors = { - request: new InterceptorManager$1(), - response: new InterceptorManager$1() - }; - } - /** - * Dispatch a request - * - * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) - * @param {?Object} config - * - * @returns {Promise} The Promise to be fulfilled - */ - async request(configOrUrl, config3) { - try { - return await this._request(configOrUrl, config3); - } catch (err) { - if (err instanceof Error) { - let dummy = {}; - Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error(); - const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; - try { - if (!err.stack) { - err.stack = stack; - } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { - err.stack += "\n" + stack; - } - } catch (e) { - } - } - throw err; - } - } - _request(configOrUrl, config3) { - if (typeof configOrUrl === "string") { - config3 = config3 || {}; - config3.url = configOrUrl; - } else { - config3 = configOrUrl || {}; - } - config3 = mergeConfig3(this.defaults, config3); - const { transitional: transitional2, paramsSerializer, headers } = config3; - if (transitional2 !== void 0) { - validator.assertOptions(transitional2, { - silentJSONParsing: validators3.transitional(validators3.boolean), - forcedJSONParsing: validators3.transitional(validators3.boolean), - clarifyTimeoutError: validators3.transitional(validators3.boolean) - }, false); - } - if (paramsSerializer != null) { - if (utils$1.isFunction(paramsSerializer)) { - config3.paramsSerializer = { - serialize: paramsSerializer - }; - } else { - validator.assertOptions(paramsSerializer, { - encode: validators3.function, - serialize: validators3.function - }, true); - } - } - if (config3.allowAbsoluteUrls !== void 0) ; - else if (this.defaults.allowAbsoluteUrls !== void 0) { - config3.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; - } else { - config3.allowAbsoluteUrls = true; - } - validator.assertOptions(config3, { - baseUrl: validators3.spelling("baseURL"), - withXsrfToken: validators3.spelling("withXSRFToken") - }, true); - config3.method = (config3.method || this.defaults.method || "get").toLowerCase(); - let contextHeaders = headers && utils$1.merge( - headers.common, - headers[config3.method] - ); - headers && utils$1.forEach( - ["delete", "get", "head", "post", "put", "patch", "common"], - (method) => { - delete headers[method]; - } - ); - config3.headers = AxiosHeaders$1.concat(contextHeaders, headers); - const requestInterceptorChain = []; - let synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config3) === false) { - return; - } - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - const responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - let promise; - let i = 0; - let len; - if (!synchronousRequestInterceptors) { - const chain = [dispatchRequest2.bind(this), void 0]; - chain.unshift.apply(chain, requestInterceptorChain); - chain.push.apply(chain, responseInterceptorChain); - len = chain.length; - promise = Promise.resolve(config3); - while (i < len) { - promise = promise.then(chain[i++], chain[i++]); - } - return promise; - } - len = requestInterceptorChain.length; - let newConfig = config3; - i = 0; - while (i < len) { - const onFulfilled = requestInterceptorChain[i++]; - const onRejected = requestInterceptorChain[i++]; - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected.call(this, error); - break; - } - } - try { - promise = dispatchRequest2.call(this, newConfig); - } catch (error) { - return Promise.reject(error); - } - i = 0; - len = responseInterceptorChain.length; - while (i < len) { - promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); - } - return promise; - } - getUri(config3) { - config3 = mergeConfig3(this.defaults, config3); - const fullPath = buildFullPath2(config3.baseURL, config3.url, config3.allowAbsoluteUrls); - return buildURL2(fullPath, config3.params, config3.paramsSerializer); - } - }; - utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData2(method) { - Axios3.prototype[method] = function(url3, config3) { - return this.request(mergeConfig3(config3 || {}, { - method, - url: url3, - data: (config3 || {}).data - })); - }; - }); - utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData2(method) { - function generateHTTPMethod(isForm) { - return function httpMethod(url3, data, config3) { - return this.request(mergeConfig3(config3 || {}, { - method, - headers: isForm ? { - "Content-Type": "multipart/form-data" - } : {}, - url: url3, - data - })); - }; - } - Axios3.prototype[method] = generateHTTPMethod(); - Axios3.prototype[method + "Form"] = generateHTTPMethod(true); - }); - var Axios$1 = Axios3; - var CancelToken3 = class _CancelToken { - constructor(executor) { - if (typeof executor !== "function") { - throw new TypeError("executor must be a function."); - } - let resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - const token = this; - this.promise.then((cancel) => { - if (!token._listeners) return; - let i = token._listeners.length; - while (i-- > 0) { - token._listeners[i](cancel); - } - token._listeners = null; - }); - this.promise.then = (onfulfilled) => { - let _resolve; - const promise = new Promise((resolve) => { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - return promise; - }; - executor(function cancel(message, config3, request) { - if (token.reason) { - return; - } - token.reason = new CanceledError3(message, config3, request); - resolvePromise(token.reason); - }); - } - /** - * Throws a `CanceledError` if cancellation has been requested. - */ - throwIfRequested() { - if (this.reason) { - throw this.reason; - } - } - /** - * Subscribe to the cancel signal - */ - subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } - } - /** - * Unsubscribe from the cancel signal - */ - unsubscribe(listener) { - if (!this._listeners) { - return; - } - const index2 = this._listeners.indexOf(listener); - if (index2 !== -1) { - this._listeners.splice(index2, 1); - } - } - toAbortSignal() { - const controller = new AbortController(); - const abort = (err) => { - controller.abort(err); - }; - this.subscribe(abort); - controller.signal.unsubscribe = () => this.unsubscribe(abort); - return controller.signal; + function extension(type) { + if (!type || typeof type !== "string") { + return false; } - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - static source() { - let cancel; - const token = new _CancelToken(function executor(c) { - cancel = c; - }); - return { - token, - cancel - }; + var match = EXTRACT_TYPE_REGEXP.exec(type); + var exts = match && exports2.extensions[match[1].toLowerCase()]; + if (!exts || !exts.length) { + return false; } - }; - var CancelToken$1 = CancelToken3; - function spread3(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; - } - function isAxiosError3(payload) { - return utils$1.isObject(payload) && payload.isAxiosError === true; + return exts[0]; } - var HttpStatusCode3 = { - Continue: 100, - SwitchingProtocols: 101, - Processing: 102, - EarlyHints: 103, - Ok: 200, - Created: 201, - Accepted: 202, - NonAuthoritativeInformation: 203, - NoContent: 204, - ResetContent: 205, - PartialContent: 206, - MultiStatus: 207, - AlreadyReported: 208, - ImUsed: 226, - MultipleChoices: 300, - MovedPermanently: 301, - Found: 302, - SeeOther: 303, - NotModified: 304, - UseProxy: 305, - Unused: 306, - TemporaryRedirect: 307, - PermanentRedirect: 308, - BadRequest: 400, - Unauthorized: 401, - PaymentRequired: 402, - Forbidden: 403, - NotFound: 404, - MethodNotAllowed: 405, - NotAcceptable: 406, - ProxyAuthenticationRequired: 407, - RequestTimeout: 408, - Conflict: 409, - Gone: 410, - LengthRequired: 411, - PreconditionFailed: 412, - PayloadTooLarge: 413, - UriTooLong: 414, - UnsupportedMediaType: 415, - RangeNotSatisfiable: 416, - ExpectationFailed: 417, - ImATeapot: 418, - MisdirectedRequest: 421, - UnprocessableEntity: 422, - Locked: 423, - FailedDependency: 424, - TooEarly: 425, - UpgradeRequired: 426, - PreconditionRequired: 428, - TooManyRequests: 429, - RequestHeaderFieldsTooLarge: 431, - UnavailableForLegalReasons: 451, - InternalServerError: 500, - NotImplemented: 501, - BadGateway: 502, - ServiceUnavailable: 503, - GatewayTimeout: 504, - HttpVersionNotSupported: 505, - VariantAlsoNegotiates: 506, - InsufficientStorage: 507, - LoopDetected: 508, - NotExtended: 510, - NetworkAuthenticationRequired: 511 - }; - Object.entries(HttpStatusCode3).forEach(([key, value]) => { - HttpStatusCode3[value] = key; - }); - var HttpStatusCode$1 = HttpStatusCode3; - function createInstance2(defaultConfig) { - const context = new Axios$1(defaultConfig); - const instance = bind2(Axios$1.prototype.request, context); - utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true }); - utils$1.extend(instance, context, null, { allOwnKeys: true }); - instance.create = function create(instanceConfig) { - return createInstance2(mergeConfig3(defaultConfig, instanceConfig)); - }; - return instance; + function lookup(path) { + if (!path || typeof path !== "string") { + return false; + } + var extension2 = extname("x." + path).toLowerCase().substr(1); + if (!extension2) { + return false; + } + return exports2.types[extension2] || false; + } + function populateMaps(extensions, types) { + var preference = ["nginx", "apache", void 0, "iana"]; + Object.keys(db).forEach(function forEachMimeType(type) { + var mime = db[type]; + var exts = mime.extensions; + if (!exts || !exts.length) { + return; + } + extensions[type] = exts; + for (var i = 0; i < exts.length; i++) { + var extension2 = exts[i]; + if (types[extension2]) { + var from5 = preference.indexOf(db[types[extension2]].source); + var to2 = preference.indexOf(mime.source); + if (types[extension2] !== "application/octet-stream" && (from5 > to2 || from5 === to2 && types[extension2].substr(0, 12) === "application/")) { + continue; + } + } + types[extension2] = type; + } + }); } - var axios2 = createInstance2(defaults$1); - axios2.Axios = Axios$1; - axios2.CanceledError = CanceledError3; - axios2.CancelToken = CancelToken$1; - axios2.isCancel = isCancel3; - axios2.VERSION = VERSION3; - axios2.toFormData = toFormData3; - axios2.AxiosError = AxiosError3; - axios2.Cancel = axios2.CanceledError; - axios2.all = function all3(promises) { - return Promise.all(promises); - }; - axios2.spread = spread3; - axios2.isAxiosError = isAxiosError3; - axios2.mergeConfig = mergeConfig3; - axios2.AxiosHeaders = AxiosHeaders$1; - axios2.formToJSON = (thing) => formDataToJSON2(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); - axios2.getAdapter = adapters.getAdapter; - axios2.HttpStatusCode = HttpStatusCode$1; - axios2.default = axios2; - module2.exports = axios2; } }); -// node_modules/is-electron/index.js -var require_is_electron = __commonJS({ - "node_modules/is-electron/index.js"(exports2, module2) { - function isElectron() { - if (typeof window !== "undefined" && typeof window.process === "object" && window.process.type === "renderer") { - return true; - } - if (typeof process !== "undefined" && typeof process.versions === "object" && !!process.versions.electron) { - return true; - } - if (typeof navigator === "object" && typeof navigator.userAgent === "string" && navigator.userAgent.indexOf("Electron") >= 0) { - return true; +// node_modules/asynckit/lib/defer.js +var require_defer = __commonJS({ + "node_modules/asynckit/lib/defer.js"(exports2, module2) { + module2.exports = defer; + function defer(fn2) { + var nextTick = typeof setImmediate == "function" ? setImmediate : typeof process == "object" && typeof process.nextTick == "function" ? process.nextTick : null; + if (nextTick) { + nextTick(fn2); + } else { + setTimeout(fn2, 0); } - return false; } - module2.exports = isElectron; } }); -// node_modules/p-queue/node_modules/eventemitter3/index.js -var require_eventemitter3 = __commonJS({ - "node_modules/p-queue/node_modules/eventemitter3/index.js"(exports2, module2) { - "use strict"; - var has = Object.prototype.hasOwnProperty; - var prefix = "~"; - function Events() { - } - if (Object.create) { - Events.prototype = /* @__PURE__ */ Object.create(null); - if (!new Events().__proto__) prefix = false; +// node_modules/asynckit/lib/async.js +var require_async = __commonJS({ + "node_modules/asynckit/lib/async.js"(exports2, module2) { + var defer = require_defer(); + module2.exports = async; + function async(callback) { + var isAsync = false; + defer(function() { + isAsync = true; + }); + return function async_callback(err, result) { + if (isAsync) { + callback(err, result); + } else { + defer(function nextTick_callback() { + callback(err, result); + }); + } + }; } - function EE(fn2, context, once) { - this.fn = fn2; - this.context = context; - this.once = once || false; + } +}); + +// node_modules/asynckit/lib/abort.js +var require_abort = __commonJS({ + "node_modules/asynckit/lib/abort.js"(exports2, module2) { + module2.exports = abort; + function abort(state) { + Object.keys(state.jobs).forEach(clean.bind(state)); + state.jobs = {}; } - function addListener(emitter, event, fn2, context, once) { - if (typeof fn2 !== "function") { - throw new TypeError("The listener must be a function"); + function clean(key) { + if (typeof this.jobs[key] == "function") { + this.jobs[key](); } - var listener = new EE(fn2, context || emitter, once), evt = prefix ? prefix + event : event; - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; - return emitter; - } - function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; } - function EventEmitter3() { - this._events = new Events(); - this._eventsCount = 0; + } +}); + +// node_modules/asynckit/lib/iterate.js +var require_iterate = __commonJS({ + "node_modules/asynckit/lib/iterate.js"(exports2, module2) { + var async = require_async(); + var abort = require_abort(); + module2.exports = iterate; + function iterate(list, iterator2, state, callback) { + var key = state["keyedList"] ? state["keyedList"][state.index] : state.index; + state.jobs[key] = runJob(iterator2, key, list[key], function(error, output) { + if (!(key in state.jobs)) { + return; + } + delete state.jobs[key]; + if (error) { + abort(state); + } else { + state.results[key] = output; + } + callback(error, state.results); + }); } - EventEmitter3.prototype.eventNames = function eventNames() { - var names = [], events, name; - if (this._eventsCount === 0) return names; - for (name in events = this._events) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + function runJob(iterator2, key, item, callback) { + var aborter; + if (iterator2.length == 2) { + aborter = iterator2(item, async(callback)); + } else { + aborter = iterator2(item, key, async(callback)); } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); + return aborter; + } + } +}); + +// node_modules/asynckit/lib/state.js +var require_state2 = __commonJS({ + "node_modules/asynckit/lib/state.js"(exports2, module2) { + module2.exports = state; + function state(list, sortMethod) { + var isNamedList = !Array.isArray(list), initState = { + index: 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs: {}, + results: isNamedList ? {} : [], + size: isNamedList ? Object.keys(list).length : list.length + }; + if (sortMethod) { + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b2) { + return sortMethod(list[a], list[b2]); + }); } - return names; - }; - EventEmitter3.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event, handlers = this._events[evt]; - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; - for (var i = 0, l = handlers.length, ee2 = new Array(l); i < l; i++) { - ee2[i] = handlers[i].fn; + return initState; + } + } +}); + +// node_modules/asynckit/lib/terminator.js +var require_terminator = __commonJS({ + "node_modules/asynckit/lib/terminator.js"(exports2, module2) { + var abort = require_abort(); + var async = require_async(); + module2.exports = terminator; + function terminator(callback) { + if (!Object.keys(this.jobs).length) { + return; } - return ee2; - }; - EventEmitter3.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event, listeners = this._events[evt]; - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; - }; - EventEmitter3.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) return false; - var listeners = this._events[evt], len = arguments.length, args, i; - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); - switch (len) { - case 1: - return listeners.fn.call(listeners.context), true; - case 2: - return listeners.fn.call(listeners.context, a1), true; - case 3: - return listeners.fn.call(listeners.context, a1, a2), true; - case 4: - return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: - return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: - return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } - for (i = 1, args = new Array(len - 1); i < len; i++) { - args[i - 1] = arguments[i]; - } - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length, j2; - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); - switch (len) { - case 1: - listeners[i].fn.call(listeners[i].context); - break; - case 2: - listeners[i].fn.call(listeners[i].context, a1); - break; - case 3: - listeners[i].fn.call(listeners[i].context, a1, a2); - break; - case 4: - listeners[i].fn.call(listeners[i].context, a1, a2, a3); - break; - default: - if (!args) for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) { - args[j2 - 1] = arguments[j2]; - } - listeners[i].fn.apply(listeners[i].context, args); + this.index = this.size; + abort(this); + async(callback)(null, this.results); + } + } +}); + +// node_modules/asynckit/parallel.js +var require_parallel2 = __commonJS({ + "node_modules/asynckit/parallel.js"(exports2, module2) { + var iterate = require_iterate(); + var initState = require_state2(); + var terminator = require_terminator(); + module2.exports = parallel; + function parallel(list, iterator2, callback) { + var state = initState(list); + while (state.index < (state["keyedList"] || list).length) { + iterate(list, iterator2, state, function(error, result) { + if (error) { + callback(error, result); + return; } - } - } - return true; - }; - EventEmitter3.prototype.on = function on2(event, fn2, context) { - return addListener(this, event, fn2, context, false); - }; - EventEmitter3.prototype.once = function once(event, fn2, context) { - return addListener(this, event, fn2, context, true); - }; - EventEmitter3.prototype.removeListener = function removeListener(event, fn2, context, once) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) return this; - if (!fn2) { - clearEvent(this, evt); - return this; + if (Object.keys(state.jobs).length === 0) { + callback(null, state.results); + return; + } + }); + state.index++; } - var listeners = this._events[evt]; - if (listeners.fn) { - if (listeners.fn === fn2 && (!once || listeners.once) && (!context || listeners.context === context)) { - clearEvent(this, evt); + return terminator.bind(state, callback); + } + } +}); + +// node_modules/asynckit/serialOrdered.js +var require_serialOrdered = __commonJS({ + "node_modules/asynckit/serialOrdered.js"(exports2, module2) { + var iterate = require_iterate(); + var initState = require_state2(); + var terminator = require_terminator(); + module2.exports = serialOrdered; + module2.exports.ascending = ascending; + module2.exports.descending = descending; + function serialOrdered(list, iterator2, sortMethod, callback) { + var state = initState(list, sortMethod); + iterate(list, iterator2, state, function iteratorHandler(error, result) { + if (error) { + callback(error, result); + return; } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if (listeners[i].fn !== fn2 || once && !listeners[i].once || context && listeners[i].context !== context) { - events.push(listeners[i]); - } + state.index++; + if (state.index < (state["keyedList"] || list).length) { + iterate(list, iterator2, state, iteratorHandler); + return; } - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } - return this; - }; - EventEmitter3.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } - return this; - }; - EventEmitter3.prototype.off = EventEmitter3.prototype.removeListener; - EventEmitter3.prototype.addListener = EventEmitter3.prototype.on; - EventEmitter3.prefixed = prefix; - EventEmitter3.EventEmitter = EventEmitter3; - if ("undefined" !== typeof module2) { - module2.exports = EventEmitter3; + callback(null, state.results); + }); + return terminator.bind(state, callback); + } + function ascending(a, b2) { + return a < b2 ? -1 : a > b2 ? 1 : 0; + } + function descending(a, b2) { + return -1 * ascending(a, b2); + } + } +}); + +// node_modules/asynckit/serial.js +var require_serial = __commonJS({ + "node_modules/asynckit/serial.js"(exports2, module2) { + var serialOrdered = require_serialOrdered(); + module2.exports = serial; + function serial(list, iterator2, callback) { + return serialOrdered(list, iterator2, null, callback); } } }); -// node_modules/p-finally/index.js -var require_p_finally = __commonJS({ - "node_modules/p-finally/index.js"(exports2, module2) { +// node_modules/asynckit/index.js +var require_asynckit = __commonJS({ + "node_modules/asynckit/index.js"(exports2, module2) { + module2.exports = { + parallel: require_parallel2(), + serial: require_serial(), + serialOrdered: require_serialOrdered() + }; + } +}); + +// node_modules/es-object-atoms/index.js +var require_es_object_atoms = __commonJS({ + "node_modules/es-object-atoms/index.js"(exports2, module2) { + "use strict"; + module2.exports = Object; + } +}); + +// node_modules/es-errors/index.js +var require_es_errors = __commonJS({ + "node_modules/es-errors/index.js"(exports2, module2) { + "use strict"; + module2.exports = Error; + } +}); + +// node_modules/es-errors/eval.js +var require_eval = __commonJS({ + "node_modules/es-errors/eval.js"(exports2, module2) { + "use strict"; + module2.exports = EvalError; + } +}); + +// node_modules/es-errors/range.js +var require_range = __commonJS({ + "node_modules/es-errors/range.js"(exports2, module2) { + "use strict"; + module2.exports = RangeError; + } +}); + +// node_modules/es-errors/ref.js +var require_ref = __commonJS({ + "node_modules/es-errors/ref.js"(exports2, module2) { + "use strict"; + module2.exports = ReferenceError; + } +}); + +// node_modules/es-errors/syntax.js +var require_syntax = __commonJS({ + "node_modules/es-errors/syntax.js"(exports2, module2) { + "use strict"; + module2.exports = SyntaxError; + } +}); + +// node_modules/es-errors/type.js +var require_type = __commonJS({ + "node_modules/es-errors/type.js"(exports2, module2) { + "use strict"; + module2.exports = TypeError; + } +}); + +// node_modules/es-errors/uri.js +var require_uri = __commonJS({ + "node_modules/es-errors/uri.js"(exports2, module2) { + "use strict"; + module2.exports = URIError; + } +}); + +// node_modules/math-intrinsics/abs.js +var require_abs = __commonJS({ + "node_modules/math-intrinsics/abs.js"(exports2, module2) { + "use strict"; + module2.exports = Math.abs; + } +}); + +// node_modules/math-intrinsics/floor.js +var require_floor = __commonJS({ + "node_modules/math-intrinsics/floor.js"(exports2, module2) { + "use strict"; + module2.exports = Math.floor; + } +}); + +// node_modules/math-intrinsics/max.js +var require_max = __commonJS({ + "node_modules/math-intrinsics/max.js"(exports2, module2) { + "use strict"; + module2.exports = Math.max; + } +}); + +// node_modules/math-intrinsics/min.js +var require_min = __commonJS({ + "node_modules/math-intrinsics/min.js"(exports2, module2) { + "use strict"; + module2.exports = Math.min; + } +}); + +// node_modules/math-intrinsics/pow.js +var require_pow = __commonJS({ + "node_modules/math-intrinsics/pow.js"(exports2, module2) { + "use strict"; + module2.exports = Math.pow; + } +}); + +// node_modules/math-intrinsics/round.js +var require_round = __commonJS({ + "node_modules/math-intrinsics/round.js"(exports2, module2) { + "use strict"; + module2.exports = Math.round; + } +}); + +// node_modules/math-intrinsics/isNaN.js +var require_isNaN = __commonJS({ + "node_modules/math-intrinsics/isNaN.js"(exports2, module2) { + "use strict"; + module2.exports = Number.isNaN || function isNaN2(a) { + return a !== a; + }; + } +}); + +// node_modules/math-intrinsics/sign.js +var require_sign = __commonJS({ + "node_modules/math-intrinsics/sign.js"(exports2, module2) { "use strict"; - module2.exports = (promise, onFinally) => { - onFinally = onFinally || (() => { - }); - return promise.then( - (val) => new Promise((resolve) => { - resolve(onFinally()); - }).then(() => val), - (err) => new Promise((resolve) => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); + var $isNaN = require_isNaN(); + module2.exports = function sign2(number) { + if ($isNaN(number) || number === 0) { + return number; + } + return number < 0 ? -1 : 1; }; } }); -// node_modules/p-timeout/index.js -var require_p_timeout = __commonJS({ - "node_modules/p-timeout/index.js"(exports2, module2) { +// node_modules/gopd/gOPD.js +var require_gOPD = __commonJS({ + "node_modules/gopd/gOPD.js"(exports2, module2) { "use strict"; - var pFinally = require_p_finally(); - var TimeoutError2 = class extends Error { - constructor(message) { - super(message); - this.name = "TimeoutError"; - } - }; - var pTimeout = (promise, milliseconds, fallback2) => new Promise((resolve, reject) => { - if (typeof milliseconds !== "number" || milliseconds < 0) { - throw new TypeError("Expected `milliseconds` to be a positive number"); - } - if (milliseconds === Infinity) { - resolve(promise); - return; - } - const timer = setTimeout(() => { - if (typeof fallback2 === "function") { - try { - resolve(fallback2()); - } catch (error) { - reject(error); - } - return; - } - const message = typeof fallback2 === "string" ? fallback2 : `Promise timed out after ${milliseconds} milliseconds`; - const timeoutError = fallback2 instanceof Error ? fallback2 : new TimeoutError2(message); - if (typeof promise.cancel === "function") { - promise.cancel(); - } - reject(timeoutError); - }, milliseconds); - pFinally( - // eslint-disable-next-line promise/prefer-await-to-then - promise.then(resolve, reject), - () => { - clearTimeout(timer); - } - ); - }); - module2.exports = pTimeout; - module2.exports.default = pTimeout; - module2.exports.TimeoutError = TimeoutError2; + module2.exports = Object.getOwnPropertyDescriptor; } }); -// node_modules/p-queue/dist/lower-bound.js -var require_lower_bound = __commonJS({ - "node_modules/p-queue/dist/lower-bound.js"(exports2) { +// node_modules/gopd/index.js +var require_gopd = __commonJS({ + "node_modules/gopd/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - function lowerBound(array, value, comparator) { - let first = 0; - let count = array.length; - while (count > 0) { - const step = count / 2 | 0; - let it2 = first + step; - if (comparator(array[it2], value) <= 0) { - first = ++it2; - count -= step + 1; - } else { - count = step; - } + var $gOPD = require_gOPD(); + if ($gOPD) { + try { + $gOPD([], "length"); + } catch (e) { + $gOPD = null; } - return first; } - exports2.default = lowerBound; + module2.exports = $gOPD; } }); -// node_modules/p-queue/dist/priority-queue.js -var require_priority_queue = __commonJS({ - "node_modules/p-queue/dist/priority-queue.js"(exports2) { +// node_modules/es-define-property/index.js +var require_es_define_property = __commonJS({ + "node_modules/es-define-property/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var lower_bound_1 = require_lower_bound(); - var PriorityQueue = class { - constructor() { - this._queue = []; - } - enqueue(run, options) { - options = Object.assign({ priority: 0 }, options); - const element = { - priority: options.priority, - run - }; - if (this.size && this._queue[this.size - 1].priority >= options.priority) { - this._queue.push(element); - return; - } - const index2 = lower_bound_1.default(this._queue, element, (a, b2) => b2.priority - a.priority); - this._queue.splice(index2, 0, element); - } - dequeue() { - const item = this._queue.shift(); - return item === null || item === void 0 ? void 0 : item.run; - } - filter(options) { - return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); - } - get size() { - return this._queue.length; + var $defineProperty = Object.defineProperty || false; + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e) { + $defineProperty = false; } - }; - exports2.default = PriorityQueue; + } + module2.exports = $defineProperty; } }); -// node_modules/p-queue/dist/index.js -var require_dist = __commonJS({ - "node_modules/p-queue/dist/index.js"(exports2) { +// node_modules/has-symbols/shams.js +var require_shams = __commonJS({ + "node_modules/has-symbols/shams.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var EventEmitter3 = require_eventemitter3(); - var p_timeout_1 = require_p_timeout(); - var priority_queue_1 = require_priority_queue(); - var empty2 = () => { - }; - var timeoutError = new p_timeout_1.TimeoutError(); - var PQueue = class extends EventEmitter3 { - constructor(options) { - var _a2, _b, _c2, _d2; - super(); - this._intervalCount = 0; - this._intervalEnd = 0; - this._pendingCount = 0; - this._resolveEmpty = empty2; - this._resolveIdle = empty2; - options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); - if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { - throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a2 = options.intervalCap) === null || _a2 === void 0 ? void 0 : _a2.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`); - } - if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) { - throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d2 = (_c2 = options.interval) === null || _c2 === void 0 ? void 0 : _c2.toString()) !== null && _d2 !== void 0 ? _d2 : ""}\` (${typeof options.interval})`); - } - this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; - this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; - this._intervalCap = options.intervalCap; - this._interval = options.interval; - this._queue = new options.queueClass(); - this._queueClass = options.queueClass; - this.concurrency = options.concurrency; - this._timeout = options.timeout; - this._throwOnTimeout = options.throwOnTimeout === true; - this._isPaused = options.autoStart === false; + module2.exports = function hasSymbols() { + if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { + return false; } - get _doesIntervalAllowAnother() { - return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + if (typeof Symbol.iterator === "symbol") { + return true; } - get _doesConcurrentAllowAnother() { - return this._pendingCount < this._concurrency; + var obj = {}; + var sym = Symbol("test"); + var symObj = Object(sym); + if (typeof sym === "string") { + return false; } - _next() { - this._pendingCount--; - this._tryToStartAnother(); - this.emit("next"); + if (Object.prototype.toString.call(sym) !== "[object Symbol]") { + return false; } - _resolvePromises() { - this._resolveEmpty(); - this._resolveEmpty = empty2; - if (this._pendingCount === 0) { - this._resolveIdle(); - this._resolveIdle = empty2; - this.emit("idle"); - } + if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { + return false; } - _onResumeInterval() { - this._onInterval(); - this._initializeIntervalIfNeeded(); - this._timeoutId = void 0; + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { + return false; } - _isIntervalPaused() { - const now = Date.now(); - if (this._intervalId === void 0) { - const delay = this._intervalEnd - now; - if (delay < 0) { - this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; - } else { - if (this._timeoutId === void 0) { - this._timeoutId = setTimeout(() => { - this._onResumeInterval(); - }, delay); - } - return true; - } - } + if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { return false; } - _tryToStartAnother() { - if (this._queue.size === 0) { - if (this._intervalId) { - clearInterval(this._intervalId); - } - this._intervalId = void 0; - this._resolvePromises(); - return false; - } - if (!this._isPaused) { - const canInitializeInterval = !this._isIntervalPaused(); - if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { - const job = this._queue.dequeue(); - if (!job) { - return false; - } - this.emit("active"); - job(); - if (canInitializeInterval) { - this._initializeIntervalIfNeeded(); - } - return true; - } - } + if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - _initializeIntervalIfNeeded() { - if (this._isIntervalIgnored || this._intervalId !== void 0) { - return; - } - this._intervalId = setInterval(() => { - this._onInterval(); - }, this._interval); - this._intervalEnd = Date.now() + this._interval; + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { + return false; } - _onInterval() { - if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { - clearInterval(this._intervalId); - this._intervalId = void 0; - } - this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; - this._processQueue(); + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { + return false; } - /** - Executes all queued functions until it reaches the limit. - */ - _processQueue() { - while (this._tryToStartAnother()) { + if (typeof Object.getOwnPropertyDescriptor === "function") { + var descriptor = ( + /** @type {PropertyDescriptor} */ + Object.getOwnPropertyDescriptor(obj, sym) + ); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { + return false; } } - get concurrency() { - return this._concurrency; - } - set concurrency(newConcurrency) { - if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); - } - this._concurrency = newConcurrency; - this._processQueue(); + return true; + }; + } +}); + +// node_modules/has-symbols/index.js +var require_has_symbols = __commonJS({ + "node_modules/has-symbols/index.js"(exports2, module2) { + "use strict"; + var origSymbol = typeof Symbol !== "undefined" && Symbol; + var hasSymbolSham = require_shams(); + module2.exports = function hasNativeSymbols() { + if (typeof origSymbol !== "function") { + return false; } - /** - Adds a sync or async task to the queue. Always returns a promise. - */ - async add(fn2, options = {}) { - return new Promise((resolve, reject) => { - const run = async () => { - this._pendingCount++; - this._intervalCount++; - try { - const operation = this._timeout === void 0 && options.timeout === void 0 ? fn2() : p_timeout_1.default(Promise.resolve(fn2()), options.timeout === void 0 ? this._timeout : options.timeout, () => { - if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) { - reject(timeoutError); - } - return void 0; - }); - resolve(await operation); - } catch (error) { - reject(error); - } - this._next(); - }; - this._queue.enqueue(run, options); - this._tryToStartAnother(); - this.emit("add"); - }); + if (typeof Symbol !== "function") { + return false; } - /** - Same as `.add()`, but accepts an array of sync or async functions. - - @returns A promise that resolves when all functions are resolved. - */ - async addAll(functions, options) { - return Promise.all(functions.map(async (function_) => this.add(function_, options))); + if (typeof origSymbol("foo") !== "symbol") { + return false; } - /** - Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) - */ - start() { - if (!this._isPaused) { - return this; - } - this._isPaused = false; - this._processQueue(); - return this; + if (typeof Symbol("bar") !== "symbol") { + return false; } - /** - Put queue execution on hold. - */ - pause() { - this._isPaused = true; + return hasSymbolSham(); + }; + } +}); + +// node_modules/get-proto/Reflect.getPrototypeOf.js +var require_Reflect_getPrototypeOf = __commonJS({ + "node_modules/get-proto/Reflect.getPrototypeOf.js"(exports2, module2) { + "use strict"; + module2.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null; + } +}); + +// node_modules/get-proto/Object.getPrototypeOf.js +var require_Object_getPrototypeOf = __commonJS({ + "node_modules/get-proto/Object.getPrototypeOf.js"(exports2, module2) { + "use strict"; + var $Object = require_es_object_atoms(); + module2.exports = $Object.getPrototypeOf || null; + } +}); + +// node_modules/function-bind/implementation.js +var require_implementation = __commonJS({ + "node_modules/function-bind/implementation.js"(exports2, module2) { + "use strict"; + var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; + var toStr = Object.prototype.toString; + var max = Math.max; + var funcType = "[object Function]"; + var concatty = function concatty2(a, b2) { + var arr = []; + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; } - /** - Clear the queue. - */ - clear() { - this._queue = new this._queueClass(); + for (var j2 = 0; j2 < b2.length; j2 += 1) { + arr[j2 + a.length] = b2[j2]; } - /** - Can be called multiple times. Useful if you for example add additional items at a later time. - - @returns A promise that settles when the queue becomes empty. - */ - async onEmpty() { - if (this._queue.size === 0) { - return; - } - return new Promise((resolve) => { - const existingResolve = this._resolveEmpty; - this._resolveEmpty = () => { - existingResolve(); - resolve(); - }; - }); + return arr; + }; + var slicy = function slicy2(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j2 = 0; i < arrLike.length; i += 1, j2 += 1) { + arr[j2] = arrLike[i]; } - /** - The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. - - @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. - */ - async onIdle() { - if (this._pendingCount === 0 && this._queue.size === 0) { - return; + return arr; + }; + var joiny = function(arr, joiner) { + var str = ""; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; } - return new Promise((resolve) => { - const existingResolve = this._resolveIdle; - this._resolveIdle = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - Size of the queue. - */ - get size() { - return this._queue.size; - } - /** - Size of the queue, filtered by the given options. - - For example, this can be used to find the number of items remaining in the queue with a specific priority level. - */ - sizeBy(options) { - return this._queue.filter(options).length; - } - /** - Number of pending promises. - */ - get pending() { - return this._pendingCount; } - /** - Whether the queue is currently paused. - */ - get isPaused() { - return this._isPaused; + return str; + }; + module2.exports = function bind2(that) { + var target = this; + if (typeof target !== "function" || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); } - get timeout() { - return this._timeout; + var args = slicy(arguments, 1); + var bound; + var binder = function() { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + }; + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = "$" + i; } - /** - Set the timeout for future operations. - */ - set timeout(milliseconds) { - this._timeout = milliseconds; + bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); + if (target.prototype) { + var Empty = function Empty2() { + }; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; } + return bound; }; - exports2.default = PQueue; } }); -// node_modules/retry/lib/retry_operation.js -var require_retry_operation = __commonJS({ - "node_modules/retry/lib/retry_operation.js"(exports2, module2) { - function RetryOperation(timeouts, options) { - if (typeof options === "boolean") { - options = { forever: options }; - } - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; - this._timer = null; - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } - } - module2.exports = RetryOperation; - RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts.slice(0); - }; - RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (this._timer) { - clearTimeout(this._timer); +// node_modules/function-bind/index.js +var require_function_bind = __commonJS({ + "node_modules/function-bind/index.js"(exports2, module2) { + "use strict"; + var implementation = require_implementation(); + module2.exports = Function.prototype.bind || implementation; + } +}); + +// node_modules/call-bind-apply-helpers/functionCall.js +var require_functionCall = __commonJS({ + "node_modules/call-bind-apply-helpers/functionCall.js"(exports2, module2) { + "use strict"; + module2.exports = Function.prototype.call; + } +}); + +// node_modules/call-bind-apply-helpers/functionApply.js +var require_functionApply = __commonJS({ + "node_modules/call-bind-apply-helpers/functionApply.js"(exports2, module2) { + "use strict"; + module2.exports = Function.prototype.apply; + } +}); + +// node_modules/call-bind-apply-helpers/reflectApply.js +var require_reflectApply = __commonJS({ + "node_modules/call-bind-apply-helpers/reflectApply.js"(exports2, module2) { + "use strict"; + module2.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply; + } +}); + +// node_modules/call-bind-apply-helpers/actualApply.js +var require_actualApply = __commonJS({ + "node_modules/call-bind-apply-helpers/actualApply.js"(exports2, module2) { + "use strict"; + var bind2 = require_function_bind(); + var $apply = require_functionApply(); + var $call = require_functionCall(); + var $reflectApply = require_reflectApply(); + module2.exports = $reflectApply || bind2.call($call, $apply); + } +}); + +// node_modules/call-bind-apply-helpers/index.js +var require_call_bind_apply_helpers = __commonJS({ + "node_modules/call-bind-apply-helpers/index.js"(exports2, module2) { + "use strict"; + var bind2 = require_function_bind(); + var $TypeError = require_type(); + var $call = require_functionCall(); + var $actualApply = require_actualApply(); + module2.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== "function") { + throw new $TypeError("a function is required"); } - this._timeouts = []; - this._cachedTimeouts = null; + return $actualApply(bind2, $call, args); }; - RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (!err) { - return false; + } +}); + +// node_modules/dunder-proto/get.js +var require_get = __commonJS({ + "node_modules/dunder-proto/get.js"(exports2, module2) { + "use strict"; + var callBind = require_call_bind_apply_helpers(); + var gOPD = require_gopd(); + var hasProtoAccessor; + try { + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ + [].__proto__ === Array.prototype; + } catch (e) { + if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") { + throw e; } - var currentTime = (/* @__PURE__ */ new Date()).getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.push(err); - this._errors.unshift(new Error("RetryOperation timeout occurred")); - return false; + } + var desc = !!hasProtoAccessor && gOPD && gOPD( + Object.prototype, + /** @type {keyof typeof Object.prototype} */ + "__proto__" + ); + var $Object = Object; + var $getPrototypeOf = $Object.getPrototypeOf; + module2.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? ( + /** @type {import('./get')} */ + function getDunder(value) { + return $getPrototypeOf(value == null ? value : $Object(value)); } - this._errors.push(err); - var timeout = this._timeouts.shift(); - if (timeout === void 0) { - if (this._cachedTimeouts) { - this._errors.splice(0, this._errors.length - 1); - timeout = this._cachedTimeouts.slice(-1); - } else { - return false; - } + ) : false; + } +}); + +// node_modules/get-proto/index.js +var require_get_proto = __commonJS({ + "node_modules/get-proto/index.js"(exports2, module2) { + "use strict"; + var reflectGetProto = require_Reflect_getPrototypeOf(); + var originalGetProto = require_Object_getPrototypeOf(); + var getDunderProto = require_get(); + module2.exports = reflectGetProto ? function getProto(O) { + return reflectGetProto(O); + } : originalGetProto ? function getProto(O) { + if (!O || typeof O !== "object" && typeof O !== "function") { + throw new TypeError("getProto: not an object"); } - var self2 = this; - this._timer = setTimeout(function() { - self2._attempts++; - if (self2._operationTimeoutCb) { - self2._timeout = setTimeout(function() { - self2._operationTimeoutCb(self2._attempts); - }, self2._operationTimeout); - if (self2._options.unref) { - self2._timeout.unref(); - } - } - self2._fn(self2._attempts); - }, timeout); - if (this._options.unref) { - this._timer.unref(); + return originalGetProto(O); + } : getDunderProto ? function getProto(O) { + return getDunderProto(O); + } : null; + } +}); + +// node_modules/hasown/index.js +var require_hasown = __commonJS({ + "node_modules/hasown/index.js"(exports2, module2) { + "use strict"; + var call2 = Function.prototype.call; + var $hasOwn = Object.prototype.hasOwnProperty; + var bind2 = require_function_bind(); + module2.exports = bind2.call(call2, $hasOwn); + } +}); + +// node_modules/get-intrinsic/index.js +var require_get_intrinsic = __commonJS({ + "node_modules/get-intrinsic/index.js"(exports2, module2) { + "use strict"; + var undefined2; + var $Object = require_es_object_atoms(); + var $Error = require_es_errors(); + var $EvalError = require_eval(); + var $RangeError = require_range(); + var $ReferenceError = require_ref(); + var $SyntaxError = require_syntax(); + var $TypeError = require_type(); + var $URIError = require_uri(); + var abs = require_abs(); + var floor = require_floor(); + var max = require_max(); + var min = require_min(); + var pow3 = require_pow(); + var round = require_round(); + var sign2 = require_sign(); + var $Function = Function; + var getEvalledConstructor = function(expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); + } catch (e) { } - return true; }; - RetryOperation.prototype.attempt = function(fn2, timeoutOps) { - this._fn = fn2; - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; + var $gOPD = require_gopd(); + var $defineProperty = require_es_define_property(); + var throwTypeError = function() { + throw new $TypeError(); + }; + var ThrowTypeError = $gOPD ? function() { + try { + arguments.callee; + return throwTypeError; + } catch (calleeThrows) { + try { + return $gOPD(arguments, "callee").get; + } catch (gOPDthrows) { + return throwTypeError; } } - var self2 = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self2._operationTimeoutCb(); - }, self2._operationTimeout); - } - this._operationStart = (/* @__PURE__ */ new Date()).getTime(); - this._fn(this._attempts); - }; - RetryOperation.prototype.try = function(fn2) { - console.log("Using RetryOperation.try() is deprecated"); - this.attempt(fn2); - }; - RetryOperation.prototype.start = function(fn2) { - console.log("Using RetryOperation.start() is deprecated"); - this.attempt(fn2); - }; - RetryOperation.prototype.start = RetryOperation.prototype.try; - RetryOperation.prototype.errors = function() { - return this._errors; - }; - RetryOperation.prototype.attempts = function() { - return this._attempts; + }() : throwTypeError; + var hasSymbols = require_has_symbols()(); + var getProto = require_get_proto(); + var $ObjectGPO = require_Object_getPrototypeOf(); + var $ReflectGPO = require_Reflect_getPrototypeOf(); + var $apply = require_functionApply(); + var $call = require_functionCall(); + var needsEval = {}; + var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array); + var INTRINSICS = { + __proto__: null, + "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError, + "%Array%": Array, + "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer, + "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, + "%AsyncFromSyncIteratorPrototype%": undefined2, + "%AsyncFunction%": needsEval, + "%AsyncGenerator%": needsEval, + "%AsyncGeneratorFunction%": needsEval, + "%AsyncIteratorPrototype%": needsEval, + "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics, + "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt, + "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array, + "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array, + "%Boolean%": Boolean, + "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView, + "%Date%": Date, + "%decodeURI%": decodeURI, + "%decodeURIComponent%": decodeURIComponent, + "%encodeURI%": encodeURI, + "%encodeURIComponent%": encodeURIComponent, + "%Error%": $Error, + "%eval%": eval, + // eslint-disable-line no-eval + "%EvalError%": $EvalError, + "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array, + "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array, + "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array, + "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry, + "%Function%": $Function, + "%GeneratorFunction%": needsEval, + "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array, + "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array, + "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array, + "%isFinite%": isFinite, + "%isNaN%": isNaN, + "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, + "%JSON%": typeof JSON === "object" ? JSON : undefined2, + "%Map%": typeof Map === "undefined" ? undefined2 : Map, + "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()), + "%Math%": Math, + "%Number%": Number, + "%Object%": $Object, + "%Object.getOwnPropertyDescriptor%": $gOPD, + "%parseFloat%": parseFloat, + "%parseInt%": parseInt, + "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise, + "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy, + "%RangeError%": $RangeError, + "%ReferenceError%": $ReferenceError, + "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect, + "%RegExp%": RegExp, + "%Set%": typeof Set === "undefined" ? undefined2 : Set, + "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()), + "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer, + "%String%": String, + "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, + "%Symbol%": hasSymbols ? Symbol : undefined2, + "%SyntaxError%": $SyntaxError, + "%ThrowTypeError%": ThrowTypeError, + "%TypedArray%": TypedArray, + "%TypeError%": $TypeError, + "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array, + "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray, + "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array, + "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array, + "%URIError%": $URIError, + "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap, + "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef, + "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet, + "%Function.prototype.call%": $call, + "%Function.prototype.apply%": $apply, + "%Object.defineProperty%": $defineProperty, + "%Object.getPrototypeOf%": $ObjectGPO, + "%Math.abs%": abs, + "%Math.floor%": floor, + "%Math.max%": max, + "%Math.min%": min, + "%Math.pow%": pow3, + "%Math.round%": round, + "%Math.sign%": sign2, + "%Reflect.getPrototypeOf%": $ReflectGPO }; - RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; + if (getProto) { + try { + null.error; + } catch (e) { + errorProto = getProto(getProto(e)); + INTRINSICS["%Error.prototype%"] = errorProto; } - var counts = {}; - var mainError = null; - var mainErrorCount = 0; - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count = (counts[message] || 0) + 1; - counts[message] = count; - if (count >= mainErrorCount) { - mainError = error; - mainErrorCount = count; + } + var errorProto; + var doEval = function doEval2(name) { + var value; + if (name === "%AsyncFunction%") { + value = getEvalledConstructor("async function () {}"); + } else if (name === "%GeneratorFunction%") { + value = getEvalledConstructor("function* () {}"); + } else if (name === "%AsyncGeneratorFunction%") { + value = getEvalledConstructor("async function* () {}"); + } else if (name === "%AsyncGenerator%") { + var fn2 = doEval2("%AsyncGeneratorFunction%"); + if (fn2) { + value = fn2.prototype; + } + } else if (name === "%AsyncIteratorPrototype%") { + var gen3 = doEval2("%AsyncGenerator%"); + if (gen3 && getProto) { + value = getProto(gen3.prototype); } } - return mainError; + INTRINSICS[name] = value; + return value; }; - } -}); - -// node_modules/retry/lib/retry.js -var require_retry = __commonJS({ - "node_modules/retry/lib/retry.js"(exports2) { - var RetryOperation = require_retry_operation(); - exports2.operation = function(options) { - var timeouts = exports2.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && (options.forever || options.retries === Infinity), - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); + var LEGACY_ALIASES = { + __proto__: null, + "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], + "%ArrayPrototype%": ["Array", "prototype"], + "%ArrayProto_entries%": ["Array", "prototype", "entries"], + "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], + "%ArrayProto_keys%": ["Array", "prototype", "keys"], + "%ArrayProto_values%": ["Array", "prototype", "values"], + "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], + "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], + "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], + "%BooleanPrototype%": ["Boolean", "prototype"], + "%DataViewPrototype%": ["DataView", "prototype"], + "%DatePrototype%": ["Date", "prototype"], + "%ErrorPrototype%": ["Error", "prototype"], + "%EvalErrorPrototype%": ["EvalError", "prototype"], + "%Float32ArrayPrototype%": ["Float32Array", "prototype"], + "%Float64ArrayPrototype%": ["Float64Array", "prototype"], + "%FunctionPrototype%": ["Function", "prototype"], + "%Generator%": ["GeneratorFunction", "prototype"], + "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], + "%Int8ArrayPrototype%": ["Int8Array", "prototype"], + "%Int16ArrayPrototype%": ["Int16Array", "prototype"], + "%Int32ArrayPrototype%": ["Int32Array", "prototype"], + "%JSONParse%": ["JSON", "parse"], + "%JSONStringify%": ["JSON", "stringify"], + "%MapPrototype%": ["Map", "prototype"], + "%NumberPrototype%": ["Number", "prototype"], + "%ObjectPrototype%": ["Object", "prototype"], + "%ObjProto_toString%": ["Object", "prototype", "toString"], + "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], + "%PromisePrototype%": ["Promise", "prototype"], + "%PromiseProto_then%": ["Promise", "prototype", "then"], + "%Promise_all%": ["Promise", "all"], + "%Promise_reject%": ["Promise", "reject"], + "%Promise_resolve%": ["Promise", "resolve"], + "%RangeErrorPrototype%": ["RangeError", "prototype"], + "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], + "%RegExpPrototype%": ["RegExp", "prototype"], + "%SetPrototype%": ["Set", "prototype"], + "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], + "%StringPrototype%": ["String", "prototype"], + "%SymbolPrototype%": ["Symbol", "prototype"], + "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], + "%TypedArrayPrototype%": ["TypedArray", "prototype"], + "%TypeErrorPrototype%": ["TypeError", "prototype"], + "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], + "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], + "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], + "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], + "%URIErrorPrototype%": ["URIError", "prototype"], + "%WeakMapPrototype%": ["WeakMap", "prototype"], + "%WeakSetPrototype%": ["WeakSet", "prototype"] }; - exports2.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); - } - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1e3, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; - } - if (opts.minTimeout > opts.maxTimeout) { - throw new Error("minTimeout is greater than maxTimeout"); - } - var timeouts = []; - for (var i = 0; i < opts.retries; i++) { - timeouts.push(this.createTimeout(i, opts)); - } - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i, opts)); + var bind2 = require_function_bind(); + var hasOwn = require_hasown(); + var $concat = bind2.call($call, Array.prototype.concat); + var $spliceApply = bind2.call($apply, Array.prototype.splice); + var $replace = bind2.call($call, String.prototype.replace); + var $strSlice = bind2.call($call, String.prototype.slice); + var $exec = bind2.call($call, RegExp.prototype.exec); + var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; + var reEscapeChar = /\\(\\)?/g; + var stringToPath = function stringToPath2(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === "%" && last !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); + } else if (last === "%" && first !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); } - timeouts.sort(function(a, b2) { - return a - b2; + var result = []; + $replace(string, rePropName, function(match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match; }); - return timeouts; - }; - exports2.createTimeout = function(attempt, opts) { - var random = opts.randomize ? Math.random() + 1 : 1; - var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); - return timeout; + return result; }; - exports2.wrap = function(obj, options, methods) { - if (options instanceof Array) { - methods = options; - options = null; + var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = "%" + alias[0] + "%"; } - if (!methods) { - methods = []; - for (var key in obj) { - if (typeof obj[key] === "function") { - methods.push(key); - } + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); } - } - for (var i = 0; i < methods.length; i++) { - var method = methods[i]; - var original = obj[method]; - obj[method] = function retryWrapper(original2) { - var op2 = exports2.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); - args.push(function(err) { - if (op2.retry(err)) { - return; - } - if (err) { - arguments[0] = op2.mainError(); - } - callback.apply(this, arguments); - }); - op2.attempt(function() { - original2.apply(obj, args); - }); - }.bind(obj, original); - obj[method].options = options; - } - }; - } -}); - -// node_modules/retry/index.js -var require_retry2 = __commonJS({ - "node_modules/retry/index.js"(exports2, module2) { - module2.exports = require_retry(); - } -}); - -// node_modules/p-retry/index.js -var require_p_retry = __commonJS({ - "node_modules/p-retry/index.js"(exports2, module2) { - "use strict"; - var retry = require_retry2(); - var networkErrorMsgs = [ - "Failed to fetch", - // Chrome - "NetworkError when attempting to fetch resource.", - // Firefox - "The Internet connection appears to be offline.", - // Safari - "Network request failed" - // `cross-fetch` - ]; - var AbortError = class extends Error { - constructor(message) { - super(); - if (message instanceof Error) { - this.originalError = message; - ({ message } = message); - } else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; + if (typeof value === "undefined" && !allowMissing) { + throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!"); } - this.name = "AbortError"; - this.message = message; + return { + alias, + name: intrinsicName, + value + }; } + throw new $SyntaxError("intrinsic " + name + " does not exist!"); }; - var decorateErrorWithCounts = (error, attemptNumber, options) => { - const retriesLeft = options.retries - (attemptNumber - 1); - error.attemptNumber = attemptNumber; - error.retriesLeft = retriesLeft; - return error; - }; - var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage); - var pRetry = (input, options) => new Promise((resolve, reject) => { - options = { - onFailedAttempt: () => { - }, - retries: 10, - ...options - }; - const operation = retry.operation(options); - operation.attempt(async (attemptNumber) => { - try { - resolve(await input(attemptNumber)); - } catch (error) { - if (!(error instanceof Error)) { - reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); - return; - } - if (error instanceof AbortError) { - operation.stop(); - reject(error.originalError); - } else if (error instanceof TypeError && !isNetworkError(error.message)) { - operation.stop(); - reject(error); - } else { - decorateErrorWithCounts(error, attemptNumber, options); - try { - await options.onFailedAttempt(error); - } catch (error2) { - reject(error2); - return; - } - if (!operation.retry(error)) { - reject(operation.mainError()); - } - } - } - }); - }); - module2.exports = pRetry; - module2.exports.default = pRetry; - module2.exports.AbortError = AbortError; - } -}); - -// node_modules/@slack/web-api/dist/errors.js -var require_errors3 = __commonJS({ - "node_modules/@slack/web-api/dist/errors.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ErrorCode = void 0; - exports2.errorWithCode = errorWithCode; - exports2.requestErrorWithOriginal = requestErrorWithOriginal; - exports2.httpErrorFromResponse = httpErrorFromResponse; - exports2.platformErrorFromResult = platformErrorFromResult; - exports2.rateLimitedErrorWithDelay = rateLimitedErrorWithDelay; - var ErrorCode; - (function(ErrorCode2) { - ErrorCode2["RequestError"] = "slack_webapi_request_error"; - ErrorCode2["HTTPError"] = "slack_webapi_http_error"; - ErrorCode2["PlatformError"] = "slack_webapi_platform_error"; - ErrorCode2["RateLimitedError"] = "slack_webapi_rate_limited_error"; - ErrorCode2["FileUploadInvalidArgumentsError"] = "slack_webapi_file_upload_invalid_args_error"; - ErrorCode2["FileUploadReadFileDataError"] = "slack_webapi_file_upload_read_file_data_error"; - })(ErrorCode || (exports2.ErrorCode = ErrorCode = {})); - function errorWithCode(error, code) { - const codedError = error; - codedError.code = code; - return codedError; - } - function requestErrorWithOriginal(original, attachOriginal) { - const error = errorWithCode(new Error(`A request error occurred: ${original.message}`), ErrorCode.RequestError); - if (attachOriginal) { - error.original = original; + module2.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== "string" || name.length === 0) { + throw new $TypeError("intrinsic name must be a non-empty string"); } - return error; - } - function httpErrorFromResponse(response) { - const error = errorWithCode(new Error(`An HTTP protocol error occurred: statusCode = ${response.status}`), ErrorCode.HTTPError); - error.statusCode = response.status; - error.statusMessage = response.statusText; - const nonNullHeaders = {}; - for (const k2 of Object.keys(response.headers)) { - if (k2 && response.headers[k2]) { - nonNullHeaders[k2] = response.headers[k2]; - } + if (arguments.length > 1 && typeof allowMissing !== "boolean") { + throw new $TypeError('"allowMissing" argument must be a boolean'); } - error.headers = nonNullHeaders; - error.body = response.data; - return error; - } - function platformErrorFromResult(result) { - const error = errorWithCode(new Error(`An API error occurred: ${result.error}`), ErrorCode.PlatformError); - error.data = result; - return error; - } - function rateLimitedErrorWithDelay(retrySec) { - const error = errorWithCode(new Error(`A rate-limit has been reached, you may retry this request in ${retrySec} seconds`), ErrorCode.RateLimitedError); - error.retryAfter = retrySec; - return error; - } - } -}); - -// node_modules/@slack/web-api/dist/file-upload.js -var require_file_upload = __commonJS({ - "node_modules/@slack/web-api/dist/file-upload.js"(exports2) { - "use strict"; - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.getFileUploadJob = getFileUploadJob; - exports2.getMultipleFileUploadJobs = getMultipleFileUploadJobs; - exports2.getFileData = getFileData; - exports2.getFileDataLength = getFileDataLength; - exports2.getFileDataAsStream = getFileDataAsStream; - exports2.getAllFileUploadsToComplete = getAllFileUploadsToComplete; - exports2.warnIfNotUsingFilesUploadV2 = warnIfNotUsingFilesUploadV2; - exports2.warnIfChannels = warnIfChannels; - exports2.errorIfChannelsCsv = errorIfChannelsCsv; - exports2.errorIfInvalidOrMissingFileData = errorIfInvalidOrMissingFileData; - exports2.warnIfMissingOrInvalidFileNameAndDefault = warnIfMissingOrInvalidFileNameAndDefault; - exports2.warnIfLegacyFileType = warnIfLegacyFileType; - exports2.buildMissingFileIdError = buildMissingFileIdError; - exports2.buildFileSizeErrorMsg = buildFileSizeErrorMsg; - exports2.buildLegacyFileTypeWarning = buildLegacyFileTypeWarning; - exports2.buildMissingFileNameWarning = buildMissingFileNameWarning; - exports2.buildMissingExtensionWarning = buildMissingExtensionWarning; - exports2.buildLegacyMethodWarning = buildLegacyMethodWarning; - exports2.buildGeneralFilesUploadWarning = buildGeneralFilesUploadWarning; - exports2.buildFilesUploadMissingMessage = buildFilesUploadMissingMessage; - exports2.buildChannelsWarning = buildChannelsWarning; - exports2.buildMultipleChannelsErrorMsg = buildMultipleChannelsErrorMsg; - exports2.buildInvalidFilesUploadParamError = buildInvalidFilesUploadParamError; - var node_fs_1 = __require("node:fs"); - var node_stream_1 = __require("node:stream"); - var errors_1 = require_errors3(); - function getFileUploadJob(options, logger) { - return __awaiter(this, void 0, void 0, function* () { - var _a2, _b, _c2, _d2; - warnIfLegacyFileType(options, logger); - warnIfChannels(options, logger); - errorIfChannelsCsv(options); - const fileName = warnIfMissingOrInvalidFileNameAndDefault(options, logger); - const fileData = yield getFileData(options); - const fileDataBytesLength = getFileDataLength(fileData); - const fileUploadJob = { - // supplied by user - alt_text: options.alt_text, - channel_id: (_a2 = options.channels) !== null && _a2 !== void 0 ? _a2 : options.channel_id, - filename: (_b = options.filename) !== null && _b !== void 0 ? _b : fileName, - initial_comment: options.initial_comment, - snippet_type: options.snippet_type, - title: (_d2 = (_c2 = options.title) !== null && _c2 !== void 0 ? _c2 : options.filename) !== null && _d2 !== void 0 ? _d2 : fileName, - // default title to filename unless otherwise specified - // calculated - data: fileData, - length: fileDataBytesLength - }; - if ("thread_ts" in options) { - fileUploadJob.thread_ts = options.thread_ts; - } - if ("token" in options) { - fileUploadJob.token = options.token; - } - if ("content" in options) { - return Object.assign({ content: options.content }, fileUploadJob); - } - if ("file" in options) { - return Object.assign({ file: options.file }, fileUploadJob); + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; + var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { + throw new $SyntaxError("property names with quotes must have matching quotes"); } - throw (0, errors_1.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - }); - } - function getMultipleFileUploadJobs(options, logger) { - return __awaiter(this, void 0, void 0, function* () { - if ("file_uploads" in options) { - return Promise.all(options.file_uploads.map((upload) => { - const { channel_id, channels, initial_comment, thread_ts } = upload; - if (channel_id || channels || initial_comment || thread_ts) { - throw (0, errors_1.errorWithCode)(new Error(buildInvalidFilesUploadParamError()), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - } - const uploadJobArgs = Object.assign(Object.assign({}, upload), { channels: options.channels, channel_id: options.channel_id, initial_comment: options.initial_comment }); - if ("thread_ts" in options) { - uploadJobArgs.thread_ts = options.thread_ts; - } - if ("token" in options) { - uploadJobArgs.token = options.token; - } - if ("content" in upload) { - return getFileUploadJob(Object.assign({ content: upload.content }, uploadJobArgs), logger); - } - if ("file" in upload) { - return getFileUploadJob(Object.assign({ file: upload.file }, uploadJobArgs), logger); - } - throw (0, errors_1.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - })); + if (part === "constructor" || !isOwn) { + skipFurtherCaching = true; } - throw new Error(buildFilesUploadMissingMessage()); - }); - } - function getFileData(options) { - return __awaiter(this, void 0, void 0, function* () { - errorIfInvalidOrMissingFileData(options); - if ("file" in options) { - const { file } = options; - if (Buffer.isBuffer(file)) - return file; - if (typeof file === "string") { - try { - const dataBuffer = (0, node_fs_1.readFileSync)(file); - return dataBuffer; - } catch (error) { - throw (0, errors_1.errorWithCode)(new Error(`Unable to resolve file data for ${file}. Please supply a filepath string, or binary data Buffer or String directly.`), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + intrinsicBaseName += "." + part; + intrinsicRealName = "%" + intrinsicBaseName + "%"; + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available."); } + return void undefined2; } - const data = yield getFileDataAsStream(file); - if (data) - return data; - } - if ("content" in options) - return Buffer.from(options.content); - throw (0, errors_1.errorWithCode)(new Error("There was an issue getting the file data for the file or content supplied"), errors_1.ErrorCode.FileUploadReadFileDataError); - }); - } - function getFileDataLength(data) { - if (data) { - return Buffer.byteLength(data, "utf8"); - } - throw (0, errors_1.errorWithCode)(new Error(buildFileSizeErrorMsg()), errors_1.ErrorCode.FileUploadReadFileDataError); - } - function getFileDataAsStream(readable) { - return __awaiter(this, void 0, void 0, function* () { - const chunks = []; - return new Promise((resolve, reject) => { - readable.on("readable", () => { - let chunk = readable.read(); - while (chunk !== null) { - chunks.push(chunk); - chunk = readable.read(); - } - }); - readable.on("end", () => { - if (chunks.length > 0) { - const content = Buffer.concat(chunks); - resolve(content); + if ($gOPD && i + 1 >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + if (isOwn && "get" in desc && !("originalValue" in desc.get)) { + value = desc.get; } else { - reject(Error("No data in supplied file")); - } - }); - }); - }); - } - function getAllFileUploadsToComplete(fileUploads) { - const toComplete = {}; - for (const upload of fileUploads) { - const { channel_id, thread_ts, initial_comment, file_id, title } = upload; - if (file_id) { - const compareString = `:::${channel_id}:::${thread_ts}:::${initial_comment}`; - if (!Object.prototype.hasOwnProperty.call(toComplete, compareString)) { - toComplete[compareString] = { - files: [{ id: file_id, title }], - channel_id, - initial_comment - }; - if (thread_ts && channel_id) { - const fileThreadDestinationArgument = { - channel_id, - thread_ts - }; - toComplete[compareString] = Object.assign(Object.assign({}, toComplete[compareString]), fileThreadDestinationArgument); - } - if ("token" in upload) { - toComplete[compareString].token = upload.token; + value = value[part]; } } else { - toComplete[compareString].files.push({ - id: file_id, - title - }); + isOwn = hasOwn(value, part); + value = value[part]; } - } else { - throw new Error(buildMissingFileIdError()); - } - } - return toComplete; - } - function warnIfNotUsingFilesUploadV2(method, logger) { - const targetMethods = ["files.upload"]; - const isTargetMethod = targetMethods.includes(method); - if (method === "files.upload") - logger.warn(buildLegacyMethodWarning(method)); - if (isTargetMethod) - logger.info(buildGeneralFilesUploadWarning()); - } - function warnIfChannels(options, logger) { - if (options.channels) - logger.warn(buildChannelsWarning()); - } - function errorIfChannelsCsv(options) { - const channels = options.channels ? options.channels.split(",") : []; - if (channels.length > 1) { - throw (0, errors_1.errorWithCode)(new Error(buildMultipleChannelsErrorMsg()), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - } - } - function errorIfInvalidOrMissingFileData(options) { - const hasFile = "file" in options; - const hasContent = "content" in options; - if (!(hasFile || hasContent) || hasFile && hasContent) { - throw (0, errors_1.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You cannot supply both"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - } - if ("file" in options) { - const { file } = options; - if (file && !(typeof file === "string" || Buffer.isBuffer(file) || file instanceof node_stream_1.Readable)) { - throw (0, errors_1.errorWithCode)(new Error("file must be a valid string path, buffer or Readable"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - } - } - if ("content" in options && options.content && typeof options.content !== "string") { - throw (0, errors_1.errorWithCode)(new Error("content must be a string"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); - } - } - function warnIfMissingOrInvalidFileNameAndDefault(options, logger) { - var _a2; - const DEFAULT_FILETYPE = "txt"; - const DEFAULT_FILENAME = `file.${(_a2 = options.filetype) !== null && _a2 !== void 0 ? _a2 : DEFAULT_FILETYPE}`; - const { filename } = options; - if (!filename) { - logger.warn(buildMissingFileNameWarning()); - return DEFAULT_FILENAME; - } - if (filename.split(".").length < 2) { - logger.warn(buildMissingExtensionWarning(filename)); - } - return filename; - } - function warnIfLegacyFileType(options, logger) { - if (options.filetype) { - logger.warn(buildLegacyFileTypeWarning()); + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } } - } - function buildMissingFileIdError() { - return "Missing required file id for file upload completion"; - } - function buildFileSizeErrorMsg() { - return "There was an issue calculating the size of your file"; - } - function buildLegacyFileTypeWarning() { - return "filetype is no longer a supported field in files.uploadV2. \nPlease remove this field. To indicate file type, please do so via the required filename property using the appropriate file extension, e.g. image.png, text.txt"; - } - function buildMissingFileNameWarning() { - return "filename is a required field for files.uploadV2. \n For backwards compatibility and ease of migration, defaulting the filename. For best experience and consistent unfurl behavior, you should set the filename property with correct file extension, e.g. image.png, text.txt"; - } - function buildMissingExtensionWarning(filename) { - return `filename supplied '${filename}' may be missing a proper extension. Missing extenions may result in unexpected unfurl behavior when shared`; - } - function buildLegacyMethodWarning(method) { - return `${method} may cause some issues like timeouts for relatively large files.`; - } - function buildGeneralFilesUploadWarning() { - return "Our latest recommendation is to use client.files.uploadV2() method, which is mostly compatible and much stabler, instead."; - } - function buildFilesUploadMissingMessage() { - return "Something went wrong with processing file_uploads"; - } - function buildChannelsWarning() { - return "Although the 'channels' parameter is still supported for smoother migration from legacy files.upload, we recommend using the new channel_id parameter with a single str value instead (e.g. 'C12345')."; - } - function buildMultipleChannelsErrorMsg() { - return "Sharing files with multiple channels is no longer supported in v2. Share files in each channel separately instead."; - } - function buildInvalidFilesUploadParamError() { - return "You may supply file_uploads only for a single channel, comment, thread respectively. Therefore, please supply any channel_id, initial_comment, thread_ts in the top-layer."; - } + return value; + }; } }); -// node_modules/@slack/web-api/dist/helpers.js -var require_helpers = __commonJS({ - "node_modules/@slack/web-api/dist/helpers.js"(exports2) { +// node_modules/has-tostringtag/shams.js +var require_shams2 = __commonJS({ + "node_modules/has-tostringtag/shams.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.default = delay; - function delay(ms) { - return new Promise((resolve) => { - setTimeout(resolve, ms); - }); - } + var hasSymbols = require_shams(); + module2.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; + }; } }); -// node_modules/@slack/web-api/package.json -var require_package3 = __commonJS({ - "node_modules/@slack/web-api/package.json"(exports2, module2) { - module2.exports = { - name: "@slack/web-api", - version: "7.9.2", - description: "Official library for using the Slack Platform's Web API", - author: "Slack Technologies, LLC", - license: "MIT", - keywords: ["slack", "web-api", "bot", "client", "http", "api", "proxy", "rate-limiting", "pagination"], - main: "dist/index.js", - types: "./dist/index.d.ts", - files: ["dist/**/*"], - engines: { - node: ">= 18", - npm: ">= 8.6.0" - }, - repository: "slackapi/node-slack-sdk", - homepage: "https://tools.slack.dev/node-slack-sdk/web-api", - publishConfig: { - access: "public" - }, - bugs: { - url: "https://github.com/slackapi/node-slack-sdk/issues" - }, - scripts: { - prepare: "npm run build", - build: "npm run build:clean && tsc", - "build:clean": "shx rm -rf ./dist ./coverage", - lint: "npx @biomejs/biome check .", - "lint:fix": "npx @biomejs/biome check --write .", - mocha: 'mocha --config ./test/.mocharc.json "./src/**/*.spec.ts"', - test: "npm run lint && npm run test:types && npm run test:integration && npm run test:unit", - "test:integration": "npm run build && node test/integration/commonjs-project/index.js && node test/integration/esm-project/index.mjs && npm run test:integration:ts", - "test:integration:ts": "cd test/integration/ts-4.7-project && npm i && npm run build", - "test:unit": "npm run build && c8 --config ./test/.c8rc.json npm run mocha", - "test:types": "tsd", - watch: "npx nodemon --watch 'src' --ext 'ts' --exec npm run build" - }, - dependencies: { - "@slack/logger": "^4.0.0", - "@slack/types": "^2.9.0", - "@types/node": ">=18.0.0", - "@types/retry": "0.12.0", - axios: "^1.8.3", - eventemitter3: "^5.0.1", - "form-data": "^4.0.0", - "is-electron": "2.2.2", - "is-stream": "^2", - "p-queue": "^6", - "p-retry": "^4", - retry: "^0.13.1" - }, - devDependencies: { - "@biomejs/biome": "^1.8.3", - "@tsconfig/recommended": "^1", - "@types/busboy": "^1.5.4", - "@types/chai": "^4", - "@types/mocha": "^10", - "@types/sinon": "^17", - busboy: "^1", - c8: "^10.1.2", - chai: "^4", - mocha: "^11", - "mocha-junit-reporter": "^2.2.1", - "mocha-multi-reporters": "^1.5.1", - nock: "^14", - shx: "^0.4.0", - sinon: "^20", - "source-map-support": "^0.5.21", - "ts-node": "^10", - tsd: "^0.32.0", - typescript: "5.8.3" - }, - tsd: { - directory: "test/types" +// node_modules/es-set-tostringtag/index.js +var require_es_set_tostringtag = __commonJS({ + "node_modules/es-set-tostringtag/index.js"(exports2, module2) { + "use strict"; + var GetIntrinsic = require_get_intrinsic(); + var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); + var hasToStringTag = require_shams2()(); + var hasOwn = require_hasown(); + var $TypeError = require_type(); + var toStringTag2 = hasToStringTag ? Symbol.toStringTag : null; + module2.exports = function setToStringTag(object, value) { + var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; + var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; + if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") { + throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans"); + } + if (toStringTag2 && (overrideIfSet || !hasOwn(object, toStringTag2))) { + if ($defineProperty) { + $defineProperty(object, toStringTag2, { + configurable: !nonConfigurable, + enumerable: false, + value, + writable: false + }); + } else { + object[toStringTag2] = value; + } } }; } }); -// node_modules/@slack/web-api/dist/instrument.js -var require_instrument = __commonJS({ - "node_modules/@slack/web-api/dist/instrument.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m2, k2); - if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m2[k2]; - } }; - } - Object.defineProperty(o, k22, desc); - } : function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - o[k22] = m2[k2]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - } : function(o, v) { - o["default"] = v; - }); - var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar2 = []; - for (var k2 in o2) if (Object.prototype.hasOwnProperty.call(o2, k2)) ar2[ar2.length] = k2; - return ar2; - }; - return ownKeys(o); - }; - return function(mod2) { - if (mod2 && mod2.__esModule) return mod2; - var result = {}; - if (mod2 != null) { - for (var k2 = ownKeys(mod2), i = 0; i < k2.length; i++) if (k2[i] !== "default") __createBinding(result, mod2, k2[i]); - } - __setModuleDefault(result, mod2); - return result; - }; - }(); - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.addAppMetadata = addAppMetadata; - exports2.getUserAgent = getUserAgent; - var os2 = __importStar(__require("node:os")); - var node_path_1 = __require("node:path"); - var packageJson = require_package3(); - function replaceSlashes(s) { - return s.replace("/", ":"); - } - var baseUserAgent = `${replaceSlashes(packageJson.name)}/${packageJson.version} ${(0, node_path_1.basename)(process.title)}/${process.version.replace("v", "")} ${os2.platform()}/${os2.release()}`; - var appMetadata = {}; - function addAppMetadata({ name, version: version4 }) { - appMetadata[replaceSlashes(name)] = version4; - } - function getUserAgent() { - const appIdentifier = Object.entries(appMetadata).map(([name, version4]) => `${name}/${version4}`).join(" "); - return (appIdentifier.length > 0 ? `${appIdentifier} ` : "") + baseUserAgent; - } +// node_modules/form-data/lib/populate.js +var require_populate = __commonJS({ + "node_modules/form-data/lib/populate.js"(exports2, module2) { + module2.exports = function(dst, src) { + Object.keys(src).forEach(function(prop) { + dst[prop] = dst[prop] || src[prop]; + }); + return dst; + }; } }); -// node_modules/@slack/logger/dist/index.js -var require_dist2 = __commonJS({ - "node_modules/@slack/logger/dist/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.ConsoleLogger = exports2.LogLevel = void 0; - var LogLevel; - (function(LogLevel2) { - LogLevel2["ERROR"] = "error"; - LogLevel2["WARN"] = "warn"; - LogLevel2["INFO"] = "info"; - LogLevel2["DEBUG"] = "debug"; - })(LogLevel = exports2.LogLevel || (exports2.LogLevel = {})); - var ConsoleLogger = class _ConsoleLogger { - constructor() { - this.level = LogLevel.INFO; - this.name = ""; +// node_modules/form-data/lib/form_data.js +var require_form_data = __commonJS({ + "node_modules/form-data/lib/form_data.js"(exports2, module2) { + var CombinedStream = require_combined_stream(); + var util3 = __require("util"); + var path = __require("path"); + var http3 = __require("http"); + var https2 = __require("https"); + var parseUrl = __require("url").parse; + var fs2 = __require("fs"); + var Stream = __require("stream").Stream; + var mime = require_mime_types(); + var asynckit = require_asynckit(); + var setToStringTag = require_es_set_tostringtag(); + var populate = require_populate(); + module2.exports = FormData3; + util3.inherits(FormData3, CombinedStream); + function FormData3(options) { + if (!(this instanceof FormData3)) { + return new FormData3(options); } - getLevel() { - return this.level; + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + CombinedStream.call(this); + options = options || {}; + for (var option in options) { + this[option] = options[option]; } - /** - * Sets the instance's log level so that only messages which are equal or more severe are output to the console. - */ - setLevel(level) { - this.level = level; + } + FormData3.LINE_BREAK = "\r\n"; + FormData3.DEFAULT_CONTENT_TYPE = "application/octet-stream"; + FormData3.prototype.append = function(field, value, options) { + options = options || {}; + if (typeof options == "string") { + options = { filename: options }; } - /** - * Set the instance's name, which will appear on each log line before the message. - */ - setName(name) { - this.name = name; + var append2 = CombinedStream.prototype.append.bind(this); + if (typeof value == "number") { + value = "" + value; } - /** - * Log a debug message - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - debug(...msg) { - if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.DEBUG, this.level)) { - console.debug(_ConsoleLogger.labels.get(LogLevel.DEBUG), this.name, ...msg); - } + if (Array.isArray(value)) { + this._error(new Error("Arrays are not supported.")); + return; } - /** - * Log an info message - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - info(...msg) { - if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.INFO, this.level)) { - console.info(_ConsoleLogger.labels.get(LogLevel.INFO), this.name, ...msg); - } + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + append2(header); + append2(value); + append2(footer); + this._trackLength(header, value, options); + }; + FormData3.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === "string") { + valueLength = Buffer.byteLength(value); } - /** - * Log a warning message - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - warn(...msg) { - if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.WARN, this.level)) { - console.warn(_ConsoleLogger.labels.get(LogLevel.WARN), this.name, ...msg); - } + this._valueLength += valueLength; + this._overheadLength += Buffer.byteLength(header) + FormData3.LINE_BREAK.length; + if (!value || !value.path && !(value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) && !(value instanceof Stream)) { + return; } - /** - * Log an error message - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error(...msg) { - if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.ERROR, this.level)) { - console.error(_ConsoleLogger.labels.get(LogLevel.ERROR), this.name, ...msg); + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } + }; + FormData3.prototype._lengthRetriever = function(value, callback) { + if (Object.prototype.hasOwnProperty.call(value, "fd")) { + if (value.end != void 0 && value.end != Infinity && value.start != void 0) { + callback(null, value.end + 1 - (value.start ? value.start : 0)); + } else { + fs2.stat(value.path, function(err, stat) { + var fileSize; + if (err) { + callback(err); + return; + } + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); } + } else if (Object.prototype.hasOwnProperty.call(value, "httpVersion")) { + callback(null, +value.headers["content-length"]); + } else if (Object.prototype.hasOwnProperty.call(value, "httpModule")) { + value.on("response", function(response) { + value.pause(); + callback(null, +response.headers["content-length"]); + }); + value.resume(); + } else { + callback("Unknown stream"); } - /** - * Helper to compare two log levels and determine if a is equal or more severe than b - */ - static isMoreOrEqualSevere(a, b2) { - return _ConsoleLogger.severity[a] >= _ConsoleLogger.severity[b2]; + }; + FormData3.prototype._multiPartHeader = function(field, value, options) { + if (typeof options.header == "string") { + return options.header; + } + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + var contents = ""; + var headers = { + // add custom disposition as third element or keep it two elements if not + "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + "Content-Type": [].concat(contentType || []) + }; + if (typeof options.header == "object") { + populate(headers, options.header); + } + var header; + for (var prop in headers) { + if (Object.prototype.hasOwnProperty.call(headers, prop)) { + header = headers[prop]; + if (header == null) { + continue; + } + if (!Array.isArray(header)) { + header = [header]; + } + if (header.length) { + contents += prop + ": " + header.join("; ") + FormData3.LINE_BREAK; + } + } } + return "--" + this.getBoundary() + FormData3.LINE_BREAK + contents + FormData3.LINE_BREAK; }; - exports2.ConsoleLogger = ConsoleLogger; - ConsoleLogger.labels = (() => { - const entries = Object.entries(LogLevel); - const map = entries.map(([key, value]) => [value, `[${key}] `]); - return new Map(map); - })(); - ConsoleLogger.severity = { - [LogLevel.ERROR]: 400, - [LogLevel.WARN]: 300, - [LogLevel.INFO]: 200, - [LogLevel.DEBUG]: 100 + FormData3.prototype._getContentDisposition = function(value, options) { + var filename, contentDisposition; + if (typeof options.filepath === "string") { + filename = path.normalize(options.filepath).replace(/\\/g, "/"); + } else if (options.filename || value.name || value.path) { + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) { + filename = path.basename(value.client._httpMessage.path || ""); + } + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } + return contentDisposition; }; - } -}); - -// node_modules/@slack/web-api/dist/logger.js -var require_logger2 = __commonJS({ - "node_modules/@slack/web-api/dist/logger.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.LogLevel = void 0; - exports2.getLogger = getLogger; - var logger_1 = require_dist2(); - var logger_2 = require_dist2(); - Object.defineProperty(exports2, "LogLevel", { enumerable: true, get: function() { - return logger_2.LogLevel; - } }); - var instanceCount = 0; - function getLogger(name, level, existingLogger) { - const instanceId = instanceCount; - instanceCount += 1; - const logger = (() => { - if (existingLogger !== void 0) { - return existingLogger; - } - return new logger_1.ConsoleLogger(); - })(); - logger.setName(`web-api:${name}:${instanceId}`); - if (level !== void 0) { - logger.setLevel(level); + FormData3.prototype._getContentType = function(value, options) { + var contentType = options.contentType; + if (!contentType && value.name) { + contentType = mime.lookup(value.name); } - return logger; - } - } -}); - -// node_modules/eventemitter3/index.js -var require_eventemitter32 = __commonJS({ - "node_modules/eventemitter3/index.js"(exports2, module2) { - "use strict"; - var has = Object.prototype.hasOwnProperty; - var prefix = "~"; - function Events() { - } - if (Object.create) { - Events.prototype = /* @__PURE__ */ Object.create(null); - if (!new Events().__proto__) prefix = false; - } - function EE(fn2, context, once) { - this.fn = fn2; - this.context = context; - this.once = once || false; - } - function addListener(emitter, event, fn2, context, once) { - if (typeof fn2 !== "function") { - throw new TypeError("The listener must be a function"); + if (!contentType && value.path) { + contentType = mime.lookup(value.path); } - var listener = new EE(fn2, context || emitter, once), evt = prefix ? prefix + event : event; - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; - return emitter; - } - function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; - } - function EventEmitter3() { - this._events = new Events(); - this._eventsCount = 0; - } - EventEmitter3.prototype.eventNames = function eventNames() { - var names = [], events, name; - if (this._eventsCount === 0) return names; - for (name in events = this._events) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + if (!contentType && value.readable && Object.prototype.hasOwnProperty.call(value, "httpVersion")) { + contentType = value.headers["content-type"]; } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); } - return names; - }; - EventEmitter3.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event, handlers = this._events[evt]; - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; - for (var i = 0, l = handlers.length, ee2 = new Array(l); i < l; i++) { - ee2[i] = handlers[i].fn; + if (!contentType && typeof value == "object") { + contentType = FormData3.DEFAULT_CONTENT_TYPE; } - return ee2; - }; - EventEmitter3.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event, listeners = this._events[evt]; - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; + return contentType; }; - EventEmitter3.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) return false; - var listeners = this._events[evt], len = arguments.length, args, i; - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); - switch (len) { - case 1: - return listeners.fn.call(listeners.context), true; - case 2: - return listeners.fn.call(listeners.context, a1), true; - case 3: - return listeners.fn.call(listeners.context, a1, a2), true; - case 4: - return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: - return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: - return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } - for (i = 1, args = new Array(len - 1); i < len; i++) { - args[i - 1] = arguments[i]; + FormData3.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData3.LINE_BREAK; + var lastPart = this._streams.length === 0; + if (lastPart) { + footer += this._lastBoundary(); } - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length, j2; - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); - switch (len) { - case 1: - listeners[i].fn.call(listeners[i].context); - break; - case 2: - listeners[i].fn.call(listeners[i].context, a1); - break; - case 3: - listeners[i].fn.call(listeners[i].context, a1, a2); - break; - case 4: - listeners[i].fn.call(listeners[i].context, a1, a2, a3); - break; - default: - if (!args) for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) { - args[j2 - 1] = arguments[j2]; - } - listeners[i].fn.apply(listeners[i].context, args); - } + next(footer); + }.bind(this); + }; + FormData3.prototype._lastBoundary = function() { + return "--" + this.getBoundary() + "--" + FormData3.LINE_BREAK; + }; + FormData3.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + "content-type": "multipart/form-data; boundary=" + this.getBoundary() + }; + for (header in userHeaders) { + if (Object.prototype.hasOwnProperty.call(userHeaders, header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; } } - return true; - }; - EventEmitter3.prototype.on = function on2(event, fn2, context) { - return addListener(this, event, fn2, context, false); + return formHeaders; }; - EventEmitter3.prototype.once = function once(event, fn2, context) { - return addListener(this, event, fn2, context, true); + FormData3.prototype.setBoundary = function(boundary) { + this._boundary = boundary; }; - EventEmitter3.prototype.removeListener = function removeListener(event, fn2, context, once) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) return this; - if (!fn2) { - clearEvent(this, evt); - return this; + FormData3.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); } - var listeners = this._events[evt]; - if (listeners.fn) { - if (listeners.fn === fn2 && (!once || listeners.once) && (!context || listeners.context === context)) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if (listeners[i].fn !== fn2 || once && !listeners[i].once || context && listeners[i].context !== context) { - events.push(listeners[i]); + return this._boundary; + }; + FormData3.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc(0); + var boundary = this.getBoundary(); + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== "function") { + if (Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); + } else { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); + } + if (typeof this._streams[i] !== "string" || this._streams[i].substring(2, boundary.length + 2) !== boundary) { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData3.LINE_BREAK)]); } } - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); } - return this; + return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); }; - EventEmitter3.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; + FormData3.prototype._generateBoundary = function() { + var boundary = "--------------------------"; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); } - return this; + this._boundary = boundary; }; - EventEmitter3.prototype.off = EventEmitter3.prototype.removeListener; - EventEmitter3.prototype.addListener = EventEmitter3.prototype.on; - EventEmitter3.prefixed = prefix; - EventEmitter3.EventEmitter = EventEmitter3; - if ("undefined" !== typeof module2) { - module2.exports = EventEmitter3; - } - } -}); - -// node_modules/@slack/types/dist/calls.js -var require_calls = __commonJS({ - "node_modules/@slack/types/dist/calls.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/dialog.js -var require_dialog = __commonJS({ - "node_modules/@slack/types/dist/dialog.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/app.js -var require_app = __commonJS({ - "node_modules/@slack/types/dist/events/app.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/assistant.js -var require_assistant = __commonJS({ - "node_modules/@slack/types/dist/events/assistant.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/call.js -var require_call = __commonJS({ - "node_modules/@slack/types/dist/events/call.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/channel.js -var require_channel = __commonJS({ - "node_modules/@slack/types/dist/events/channel.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/dnd.js -var require_dnd = __commonJS({ - "node_modules/@slack/types/dist/events/dnd.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/email.js -var require_email = __commonJS({ - "node_modules/@slack/types/dist/events/email.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/emoji.js -var require_emoji = __commonJS({ - "node_modules/@slack/types/dist/events/emoji.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/file.js -var require_file2 = __commonJS({ - "node_modules/@slack/types/dist/events/file.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/function.js -var require_function = __commonJS({ - "node_modules/@slack/types/dist/events/function.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/grid-migration.js -var require_grid_migration = __commonJS({ - "node_modules/@slack/types/dist/events/grid-migration.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/group.js -var require_group = __commonJS({ - "node_modules/@slack/types/dist/events/group.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/im.js -var require_im = __commonJS({ - "node_modules/@slack/types/dist/events/im.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/invite.js -var require_invite = __commonJS({ - "node_modules/@slack/types/dist/events/invite.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/link-shared.js -var require_link_shared = __commonJS({ - "node_modules/@slack/types/dist/events/link-shared.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/member.js -var require_member = __commonJS({ - "node_modules/@slack/types/dist/events/member.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/message.js -var require_message = __commonJS({ - "node_modules/@slack/types/dist/events/message.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/message-metadata.js -var require_message_metadata = __commonJS({ - "node_modules/@slack/types/dist/events/message-metadata.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/pin.js -var require_pin = __commonJS({ - "node_modules/@slack/types/dist/events/pin.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/reaction.js -var require_reaction = __commonJS({ - "node_modules/@slack/types/dist/events/reaction.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/shared-channel.js -var require_shared_channel = __commonJS({ - "node_modules/@slack/types/dist/events/shared-channel.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/star.js -var require_star = __commonJS({ - "node_modules/@slack/types/dist/events/star.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/subteam.js -var require_subteam = __commonJS({ - "node_modules/@slack/types/dist/events/subteam.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/team.js -var require_team = __commonJS({ - "node_modules/@slack/types/dist/events/team.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/token.js -var require_token = __commonJS({ - "node_modules/@slack/types/dist/events/token.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/user.js -var require_user = __commonJS({ - "node_modules/@slack/types/dist/events/user.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/steps-from-apps.js -var require_steps_from_apps = __commonJS({ - "node_modules/@slack/types/dist/events/steps-from-apps.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/events/index.js -var require_events = __commonJS({ - "node_modules/@slack/types/dist/events/index.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m2, k2); - if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m2[k2]; - } }; + FormData3.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; + if (this._streams.length) { + knownLength += this._lastBoundary().length; } - Object.defineProperty(o, k22, desc); - } : function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - o[k22] = m2[k2]; - }); - var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { - for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); + if (!this.hasKnownLength()) { + this._error(new Error("Cannot calculate proper length in synchronous way.")); + } + return knownLength; }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar(require_app(), exports2); - __exportStar(require_assistant(), exports2); - __exportStar(require_call(), exports2); - __exportStar(require_channel(), exports2); - __exportStar(require_dnd(), exports2); - __exportStar(require_email(), exports2); - __exportStar(require_emoji(), exports2); - __exportStar(require_file2(), exports2); - __exportStar(require_function(), exports2); - __exportStar(require_grid_migration(), exports2); - __exportStar(require_group(), exports2); - __exportStar(require_im(), exports2); - __exportStar(require_invite(), exports2); - __exportStar(require_link_shared(), exports2); - __exportStar(require_member(), exports2); - __exportStar(require_message(), exports2); - __exportStar(require_message_metadata(), exports2); - __exportStar(require_pin(), exports2); - __exportStar(require_reaction(), exports2); - __exportStar(require_shared_channel(), exports2); - __exportStar(require_star(), exports2); - __exportStar(require_subteam(), exports2); - __exportStar(require_team(), exports2); - __exportStar(require_token(), exports2); - __exportStar(require_user(), exports2); - __exportStar(require_steps_from_apps(), exports2); - } -}); - -// node_modules/@slack/types/dist/message-metadata.js -var require_message_metadata2 = __commonJS({ - "node_modules/@slack/types/dist/message-metadata.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/message-attachments.js -var require_message_attachments = __commonJS({ - "node_modules/@slack/types/dist/message-attachments.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/views.js -var require_views = __commonJS({ - "node_modules/@slack/types/dist/views.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/block-kit/blocks.js -var require_blocks = __commonJS({ - "node_modules/@slack/types/dist/block-kit/blocks.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/block-kit/composition-objects.js -var require_composition_objects = __commonJS({ - "node_modules/@slack/types/dist/block-kit/composition-objects.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/block-kit/block-elements.js -var require_block_elements = __commonJS({ - "node_modules/@slack/types/dist/block-kit/block-elements.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/block-kit/extensions.js -var require_extensions = __commonJS({ - "node_modules/@slack/types/dist/block-kit/extensions.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - } -}); - -// node_modules/@slack/types/dist/index.js -var require_dist3 = __commonJS({ - "node_modules/@slack/types/dist/index.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m2, k2); - if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m2[k2]; - } }; + FormData3.prototype.hasKnownLength = function() { + var hasKnownLength = true; + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } + return hasKnownLength; + }; + FormData3.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; + if (this._streams.length) { + knownLength += this._lastBoundary().length; } - Object.defineProperty(o, k22, desc); - } : function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - o[k22] = m2[k2]; - }); - var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { - for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } + values.forEach(function(length) { + knownLength += length; + }); + cb(null, knownLength); + }); }; - Object.defineProperty(exports2, "__esModule", { value: true }); - __exportStar(require_calls(), exports2); - __exportStar(require_dialog(), exports2); - __exportStar(require_events(), exports2); - __exportStar(require_message_metadata2(), exports2); - __exportStar(require_message_attachments(), exports2); - __exportStar(require_views(), exports2); - __exportStar(require_blocks(), exports2); - __exportStar(require_composition_objects(), exports2); - __exportStar(require_block_elements(), exports2); - __exportStar(require_extensions(), exports2); + FormData3.prototype.submit = function(params, cb) { + var request, options, defaults2 = { method: "post" }; + if (typeof params == "string") { + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults2); + } else { + options = populate(params, defaults2); + if (!options.port) { + options.port = options.protocol == "https:" ? 443 : 80; + } + } + options.headers = this.getHeaders(params.headers); + if (options.protocol == "https:") { + request = https2.request(options); + } else { + request = http3.request(options); + } + this.getLength(function(err, length) { + if (err && err !== "Unknown stream") { + this._error(err); + return; + } + if (length) { + request.setHeader("Content-Length", length); + } + this.pipe(request); + if (cb) { + var onResponse; + var callback = function(error, responce) { + request.removeListener("error", callback); + request.removeListener("response", onResponse); + return cb.call(this, error, responce); + }; + onResponse = callback.bind(this, null); + request.on("error", callback); + request.on("response", onResponse); + } + }.bind(this)); + return request; + }; + FormData3.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit("error", err); + } + }; + FormData3.prototype.toString = function() { + return "[object FormData]"; + }; + setToStringTag(FormData3, "FormData"); } }); -// node_modules/@slack/web-api/dist/methods.js -var require_methods = __commonJS({ - "node_modules/@slack/web-api/dist/methods.js"(exports2) { +// node_modules/proxy-from-env/index.js +var require_proxy_from_env = __commonJS({ + "node_modules/proxy-from-env/index.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m2, k2); - if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m2[k2]; - } }; - } - Object.defineProperty(o, k22, desc); - } : function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - o[k22] = m2[k2]; - }); - var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { - for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); + var parseUrl = __require("url").parse; + var DEFAULT_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.Methods = void 0; - var eventemitter3_1 = require_eventemitter32(); - var WebClient_1 = require_WebClient(); - function bindApiCall(self2, method) { - const apiMethod = self2.apiCall.bind(self2, method); - return apiMethod; + var stringEndsWith = String.prototype.endsWith || function(s) { + return s.length <= this.length && this.indexOf(s, this.length - s.length) !== -1; + }; + function getProxyForUrl(url2) { + var parsedUrl = typeof url2 === "string" ? parseUrl(url2) : url2 || {}; + var proto = parsedUrl.protocol; + var hostname = parsedUrl.host; + var port = parsedUrl.port; + if (typeof hostname !== "string" || !hostname || typeof proto !== "string") { + return ""; + } + proto = proto.split(":", 1)[0]; + hostname = hostname.replace(/:\d*$/, ""); + port = parseInt(port) || DEFAULT_PORTS[proto] || 0; + if (!shouldProxy(hostname, port)) { + return ""; + } + var proxy = getEnv("npm_config_" + proto + "_proxy") || getEnv(proto + "_proxy") || getEnv("npm_config_proxy") || getEnv("all_proxy"); + if (proxy && proxy.indexOf("://") === -1) { + proxy = proto + "://" + proxy; + } + return proxy; } - function bindApiCallWithOptionalArgument(self2, method) { - const apiMethod = self2.apiCall.bind(self2, method); - return apiMethod; + function shouldProxy(hostname, port) { + var NO_PROXY = (getEnv("npm_config_no_proxy") || getEnv("no_proxy")).toLowerCase(); + if (!NO_PROXY) { + return true; + } + if (NO_PROXY === "*") { + return false; + } + return NO_PROXY.split(/[,\s]/).every(function(proxy) { + if (!proxy) { + return true; + } + var parsedProxy = proxy.match(/^(.+):(\d+)$/); + var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; + var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; + if (parsedProxyPort && parsedProxyPort !== port) { + return true; + } + if (!/^[.*]/.test(parsedProxyHostname)) { + return hostname !== parsedProxyHostname; + } + if (parsedProxyHostname.charAt(0) === "*") { + parsedProxyHostname = parsedProxyHostname.slice(1); + } + return !stringEndsWith.call(hostname, parsedProxyHostname); + }); } - function bindFilesUploadV2(self2) { - return self2.filesUploadV2.bind(self2); + function getEnv(key) { + return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ""; } - var Methods = class extends eventemitter3_1.EventEmitter { - constructor() { - super(); - this.admin = { - analytics: { - /** - * @description Retrieve analytics data for a given date, presented as a compressed JSON file. - * @see {@link https://api.slack.com/methods/api.test `api.test` API reference}. - */ - getFile: bindApiCall(this, "admin.analytics.getFile") - }, - apps: { - activities: { - /** - * @description Get logs for a specified team/org. - * @see {@link https://api.slack.com/methods/admin.apps.activities.list `admin.apps.activities.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "admin.apps.activities.list") - }, - /** - * @description Approve an app for installation on a workspace. - * @see {@link https://api.slack.com/methods/admin.apps.approve `admin.apps.approve` API reference}. - */ - approve: bindApiCall(this, "admin.apps.approve"), - approved: { - /** - * @description List approved apps for an org or workspace. - * @see {@link https://api.slack.com/methods/admin.apps.approved.list `admin.apps.approved.list` API reference}. - */ - list: bindApiCall(this, "admin.apps.approved.list") - }, - /** - * @description Clear an app resolution. - * @see {@link https://api.slack.com/methods/admin.apps.clearResolution `admin.apps.clearResolution` API reference}. - */ - clearResolution: bindApiCall(this, "admin.apps.clearResolution"), - config: { - /** - * @description Look up the app config for connectors by their IDs. - * @see {@link https://api.slack.com/methods/admin.apps.config.lookup `admin.apps.config.lookup` API reference}. - */ - lookup: bindApiCall(this, "admin.apps.config.lookup"), - /** - * @description Set the app config for a connector. - * @see {@link https://api.slack.com/methods/admin.apps.config.set `admin.apps.config.set` API reference}. - */ - set: bindApiCall(this, "admin.apps.config.set") - }, - requests: { - /** - * @description Cancel app request for team. - * @see {@link https://api.slack.com/methods/admin.apps.requests.cancel `admin.apps.requests.cancel` API reference}. - */ - cancel: bindApiCall(this, "admin.apps.requests.cancel"), - /** - * @description List app requests for a team/workspace. - * @see {@link https://api.slack.com/methods/admin.apps.requests.list `admin.apps.requests.list` API reference}. - */ - list: bindApiCall(this, "admin.apps.requests.list") - }, - /** - * @description Restrict an app for installation on a workspace. - * @see {@link https://api.slack.com/methods/admin.apps.restrict `admin.apps.restrict` API reference}. - */ - restrict: bindApiCall(this, "admin.apps.restrict"), - restricted: { - /** - * @description List restricted apps for an org or workspace. - * @see {@link https://api.slack.com/methods/admin.apps.restricted.list `admin.apps.restricted.list` API reference}. - */ - list: bindApiCall(this, "admin.apps.restricted.list") - }, - /** - * @description Uninstall an app from one or many workspaces, or an entire enterprise organization. - * @see {@link https://api.slack.com/methods/admin.apps.uninstall `admin.apps.uninstall` API reference}. - */ - uninstall: bindApiCall(this, "admin.apps.uninstall") - }, - auth: { - policy: { - /** - * @description Assign entities to a particular authentication policy. - * @see {@link https://api.slack.com/methods/admin.auth.policy.assignEntities `admin.auth.policy.assignEntities` API reference}. - */ - assignEntities: bindApiCall(this, "admin.auth.policy.assignEntities"), - /** - * @description Fetch all the entities assigned to a particular authentication policy by name. - * @see {@link https://api.slack.com/methods/admin.auth.policy.getEntities `admin.auth.policy.getEntities` API reference}. - */ - getEntities: bindApiCall(this, "admin.auth.policy.getEntities"), - /** - * @description Remove specified entities from a specified authentication policy. - * @see {@link https://api.slack.com/methods/admin.auth.policy.removeEntities `admin.auth.policy.removeEntities` API reference}. - */ - removeEntities: bindApiCall(this, "admin.auth.policy.removeEntities") - } - }, - barriers: { - /** - * @description Create an Information Barrier. - * @see {@link https://api.slack.com/methods/admin.barriers.create `admin.barriers.create` API reference}. - */ - create: bindApiCall(this, "admin.barriers.create"), - /** - * @description Delete an existing Information Barrier. - * @see {@link https://api.slack.com/methods/admin.barriers.delete `admin.barriers.delete` API reference}. - */ - delete: bindApiCall(this, "admin.barriers.delete"), - /** - * @description Get all Information Barriers for your organization. - * @see {@link https://api.slack.com/methods/admin.barriers.list `admin.barriers.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "admin.barriers.list"), - /** - * @description Update an existing Information Barrier. - * @see {@link https://api.slack.com/methods/admin.barriers.update `admin.barriers.update` API reference}. - */ - update: bindApiCall(this, "admin.barriers.update") - }, - conversations: { - /** - * @description Archive a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.archive `admin.conversations.archive` API reference}. - */ - archive: bindApiCall(this, "admin.conversations.archive"), - /** - * @description Archive public or private channels in bulk. - * @see {@link https://api.slack.com/methods/admin.conversations.bulkArchive `admin.conversations.bulkArchive` API reference}. - */ - bulkArchive: bindApiCall(this, "admin.conversations.bulkArchive"), - /** - * @description Delete public or private channels in bulk. - * @see {@link https://api.slack.com/methods/admin.conversations.bulkDelet `admin.conversations.bulkDelete` API reference}. - */ - bulkDelete: bindApiCall(this, "admin.conversations.bulkDelete"), - /** - * @description Move public or private channels in bulk. - * @see {@link https://api.slack.com/methods/admin.conversations.bulkMove `admin.conversations.bulkMove` API reference}. - */ - bulkMove: bindApiCall(this, "admin.conversations.bulkMove"), - /** - * @description Convert a public channel to a private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.convertToPrivate `admin.conversations.convertToPrivate` API reference}. - */ - convertToPrivate: bindApiCall(this, "admin.conversations.convertToPrivate"), - /** - * @description Convert a private channel to a public channel. - * @see {@link https://api.slack.com/methods/admin.conversations.convertToPublic `admin.conversations.convertToPublic` API reference}. - */ - convertToPublic: bindApiCall(this, "admin.conversations.convertToPublic"), - /** - * @description Create a public or private channel-based conversation. - * @see {@link https://api.slack.com/methods/admin.conversations.create `admin.conversations.create` API reference}. - */ - create: bindApiCall(this, "admin.conversations.create"), - /** - * @description Delete a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.delete `admin.conversations.delete` API reference}. - */ - delete: bindApiCall(this, "admin.conversations.delete"), - /** - * @description Disconnect a connected channel from one or more workspaces. - * @see {@link https://api.slack.com/methods/admin.conversations.disconnectShared `admin.conversations.disconnectShared` API reference}. - */ - disconnectShared: bindApiCall(this, "admin.conversations.disconnectShared"), - ekm: { - /** - * @description List all disconnected channels — i.e., channels that were once connected to other workspaces - * and then disconnected — and the corresponding original channel IDs for key revocation with EKM. - * @see {@link https://api.slack.com/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo `admin.conversations.ekm.listOriginalConnectedChannelInfo` API reference}. - */ - listOriginalConnectedChannelInfo: bindApiCallWithOptionalArgument(this, "admin.conversations.ekm.listOriginalConnectedChannelInfo") - }, - /** - * @description Get conversation preferences for a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.getConversationPrefs `admin.conversations.getConversationPrefs` API reference}. - */ - getConversationPrefs: bindApiCall(this, "admin.conversations.getConversationPrefs"), - /** - * @description Get a conversation's retention policy. - * @see {@link https://api.slack.com/methods/admin.conversations.getCustomRetention `admin.conversations.getCustomRetention` API reference}. - */ - getCustomRetention: bindApiCall(this, "admin.conversations.getCustomRetention"), - /** - * @description Get all the workspaces a given public or private channel is connected to within - * this Enterprise org. - * @see {@link https://api.slack.com/methods/admin.conversations.getTeams `admin.conversations.getTeams` API reference}. - */ - getTeams: bindApiCall(this, "admin.conversations.getTeams"), - /** - * @description Invite a user to a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.invite `admin.conversations.invite` API reference}. - */ - invite: bindApiCall(this, "admin.conversations.invite"), - /** - * @description Returns channels on the given team using the filters. - * @see {@link https://api.slack.com/methods/admin.conversations.lookup `admin.conversations.lookup` API reference}. - */ - lookup: bindApiCall(this, "admin.conversations.lookup"), - /** - * @description Remove a conversation's retention policy. - * @see {@link https://api.slack.com/methods/admin.conversations.removeCustomRetention `admin.conversations.removeCustomRetention` API reference}. - */ - removeCustomRetention: bindApiCall(this, "admin.conversations.removeCustomRetention"), - /** - * @description Rename a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.rename `admin.conversations.rename` API reference}. - */ - rename: bindApiCall(this, "admin.conversations.rename"), - restrictAccess: { - /** - * @description Add an allowlist of IDP groups for accessing a channel. - * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.addGroup `admin.conversations.restrictAccess.addGroup` API reference}. - */ - addGroup: bindApiCall(this, "admin.conversations.restrictAccess.addGroup"), - /** - * @description List all IDP Groups linked to a channel. - * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.listGroups `admin.conversations.restrictAccess.listGroups` API reference}. - */ - listGroups: bindApiCall(this, "admin.conversations.restrictAccess.listGroups"), - /** - * @description Remove a linked IDP group linked from a private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.removeGroup `admin.conversations.restrictAccess.removeGroup` API reference}. - */ - removeGroup: bindApiCall(this, "admin.conversations.restrictAccess.removeGroup") - }, - /** - * @description Search for public or private channels in an Enterprise organization. - * @see {@link https://api.slack.com/methods/admin.conversations.search `admin.conversations.search` API reference}. - */ - search: bindApiCallWithOptionalArgument(this, "admin.conversations.search"), - /** - * @description Set the posting permissions for a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.setConversationPrefs `admin.conversations.setConversationPrefs` API reference}. - */ - setConversationPrefs: bindApiCall(this, "admin.conversations.setConversationPrefs"), - /** - * @description Set a conversation's retention policy. - * @see {@link https://api.slack.com/methods/admin.conversations.setCustomRetention `admin.conversations.setCustomRetention` API reference}. - */ - setCustomRetention: bindApiCall(this, "admin.conversations.setCustomRetention"), - /** - * @description Set the workspaces in an Enterprise grid org that connect to a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.setTeams `admin.conversations.setTeams` API reference}. - */ - setTeams: bindApiCall(this, "admin.conversations.setTeams"), - /** - * @description Unarchive a public or private channel. - * @see {@link https://api.slack.com/methods/admin.conversations.unarchive `admin.conversations.unarchive` API reference}. - */ - unarchive: bindApiCall(this, "admin.conversations.unarchive") - }, - emoji: { - /** - * @description Add an emoji. - * @see {@link https://api.slack.com/methods/admin.emoji.add `admin.emoji.add` API reference}. - */ - add: bindApiCall(this, "admin.emoji.add"), - /** - * @description Add an emoji alias. - * @see {@link https://api.slack.com/methods/admin.emoji.addAlias `admin.emoji.addAlias` API reference}. - */ - addAlias: bindApiCall(this, "admin.emoji.addAlias"), - /** - * @description List emoji for an Enterprise Grid organization. - * @see {@link https://api.slack.com/methods/admin.emoji.list `admin.emoji.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "admin.emoji.list"), - /** - * @description Remove an emoji across an Enterprise Grid organization. - * @see {@link https://api.slack.com/methods/admin.emoji.remove `admin.emoji.remove` API reference}. - */ - remove: bindApiCall(this, "admin.emoji.remove"), - /** - * @description Rename an emoji. - * @see {@link https://api.slack.com/methods/admin.emoji.rename `admin.emoji.rename` API reference}. - */ - rename: bindApiCall(this, "admin.emoji.rename") - }, - functions: { - /** - * @description Look up functions by a set of apps. - * @see {@link https://api.slack.com/methods/admin.functions.list `admin.functions.list` API reference}. - */ - list: bindApiCall(this, "admin.functions.list"), - permissions: { - /** - * @description Lookup the visibility of multiple Slack functions and include the users if - * it is limited to particular named entities. - * @see {@link https://api.slack.com/methods/admin.functions.permissions.lookup `admin.functions.permissions.lookup` API reference}. - */ - lookup: bindApiCall(this, "admin.functions.permissions.lookup"), - /** - * @description Set the visibility of a Slack function and define the users or workspaces if - * it is set to named_entities. - * @see {@link https://api.slack.com/methods/admin.functions.permissions.set `admin.functions.permissions.set` API reference}. - */ - set: bindApiCall(this, "admin.functions.permissions.set") + exports2.getProxyForUrl = getProxyForUrl; + } +}); + +// node_modules/debug/src/common.js +var require_common2 = __commonJS({ + "node_modules/debug/src/common.js"(exports2, module2) { + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash2 = 0; + for (let i = 0; i < namespace.length; i++) { + hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); + hash2 |= 0; + } + return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug(...args) { + if (!debug.enabled) { + return; + } + const self2 = debug; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index2 = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; } - }, - inviteRequests: { - /** - * @description Approve a workspace invite request. - * @see {@link https://api.slack.com/methods/admin.inviteRequests.approve `admin.inviteRequests.approve` API reference}. - */ - approve: bindApiCall(this, "admin.inviteRequests.approve"), - approved: { - /** - * @description List all approved workspace invite requests. - * @see {@link https://api.slack.com/methods/admin.inviteRequests.approved.list `admin.inviteRequests.approved.list` API reference}. - */ - list: bindApiCall(this, "admin.inviteRequests.approved.list") - }, - denied: { - /** - * @description List all denied workspace invite requests. - * @see {@link https://api.slack.com/methods/admin.inviteRequests.denied.list `admin.inviteRequests.denied.list` API reference}. - */ - list: bindApiCall(this, "admin.inviteRequests.denied.list") - }, - /** - * @description Deny a workspace invite request. - * @see {@link https://api.slack.com/methods/admin.inviteRequests.deny `admin.inviteRequests.deny` API reference}. - */ - deny: bindApiCall(this, "admin.inviteRequests.deny"), - /** - * @description List all pending workspace invite requests. - * @see {@link https://api.slack.com/methods/admin.inviteRequests.list `admin.inviteRequests.list` API reference}. - */ - list: bindApiCall(this, "admin.inviteRequests.list") - }, - roles: { - /** - * @description Adds members to the specified role with the specified scopes. - * @see {@link https://api.slack.com/methods/admin.roles.addAssignments `admin.roles.addAssignments` API reference}. - */ - addAssignments: bindApiCall(this, "admin.roles.addAssignments"), - /** - * @description Lists assignments for all roles across entities. - * Options to scope results by any combination of roles or entities. - * @see {@link https://api.slack.com/methods/admin.roles.listAssignments `admin.roles.listAssignments` API reference}. - */ - listAssignments: bindApiCallWithOptionalArgument(this, "admin.roles.listAssignments"), - /** - * @description Removes a set of users from a role for the given scopes and entities. - * @see {@link https://api.slack.com/methods/admin.roles.removeAssignments `admin.roles.removeAssignments` API reference}. - */ - removeAssignments: bindApiCall(this, "admin.roles.removeAssignments") - }, - teams: { - admins: { - /** - * @description List all of the admins on a given workspace. - * @see {@link https://api.slack.com/methods/admin.teams.admins.list `admin.teams.admins.list` API reference}. - */ - list: bindApiCall(this, "admin.teams.admins.list") - }, - /** - * @description Create an Enterprise team. - * @see {@link https://api.slack.com/methods/admin.teams.create `admin.teams.create` API reference}. - */ - create: bindApiCall(this, "admin.teams.create"), - /** - * @description List all teams on an Enterprise organization. - * @see {@link https://api.slack.com/methods/admin.teams.list `admin.teams.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "admin.teams.list"), - owners: { - /** - * @description List all of the owners on a given workspace. - * @see {@link https://api.slack.com/methods/admin.teams.owners.list `admin.teams.owners.list` API reference}. - */ - list: bindApiCall(this, "admin.teams.owners.list") - }, - settings: { - /** - * @description Fetch information about settings in a workspace. - * @see {@link https://api.slack.com/methods/admin.teams.owners.list `admin.teams.owners.list` API reference}. - */ - info: bindApiCall(this, "admin.teams.settings.info"), - /** - * @description Set the default channels of a workspace. - * @see {@link https://api.slack.com/methods/admin.teams.settings.setDefaultChannels `admin.teams.settings.setDefaultChannels` API reference}. - */ - setDefaultChannels: bindApiCall(this, "admin.teams.settings.setDefaultChannels"), - /** - * @description Set the description of a given workspace. - * @see {@link https://api.slack.com/methods/admin.teams.settings.setDescription `admin.teams.settings.setDescription` API reference}. - */ - setDescription: bindApiCall(this, "admin.teams.settings.setDescription"), - /** - * @description Set the discoverability of a given workspace. - * @see {@link https://api.slack.com/methods/admin.teams.settings.setDiscoverability `admin.teams.settings.setDiscoverability` API reference}. - */ - setDiscoverability: bindApiCall(this, "admin.teams.settings.setDiscoverability"), - /** - * @description Sets the icon of a workspace. - * @see {@link https://api.slack.com/methods/admin.teams.settings.setIcon `admin.teams.settings.setIcon` API reference}. - */ - setIcon: bindApiCall(this, "admin.teams.settings.setIcon"), - /** - * @description Set the name of a given workspace. - * @see {@link https://api.slack.com/methods/admin.teams.settings.setName `admin.teams.settings.setName` API reference}. - */ - setName: bindApiCall(this, "admin.teams.settings.setName") + index2++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index2]; + match = formatter.call(self2, val); + args.splice(index2, 1); + index2--; } + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend2; + debug.destroy = createDebug.destroy; + Object.defineProperty(debug, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; }, - usergroups: { - /** - * @description Add up to one hundred default channels to an IDP group. - * @see {@link https://api.slack.com/methods/admin.usergroups.addChannels `admin.teams.usergroups.addChannels` API reference}. - */ - addChannels: bindApiCall(this, "admin.usergroups.addChannels"), - /** - * @description Associate one or more default workspaces with an organization-wide IDP group. - * @see {@link https://api.slack.com/methods/admin.usergroups.addTeams `admin.teams.usergroups.addTeams` API reference}. - */ - addTeams: bindApiCall(this, "admin.usergroups.addTeams"), - /** - * @description List the channels linked to an org-level IDP group (user group). - * @see {@link https://api.slack.com/methods/admin.usergroups.listChannels `admin.teams.usergroups.listChannels` API reference}. - */ - listChannels: bindApiCall(this, "admin.usergroups.listChannels"), - /** - * @description Remove one or more default channels from an org-level IDP group (user group). - * @see {@link https://api.slack.com/methods/admin.usergroups.removeChannels `admin.teams.usergroups.removeChannels` API reference}. - */ - removeChannels: bindApiCall(this, "admin.usergroups.removeChannels") - }, - users: { - /** - * @description Add an Enterprise user to a workspace. - * @see {@link https://api.slack.com/methods/admin.users.assign `admin.users.assign` API reference}. - */ - assign: bindApiCall(this, "admin.users.assign"), - /** - * @description Invite a user to a workspace. - * @see {@link https://api.slack.com/methods/admin.users.invite `admin.users.invite` API reference}. - */ - invite: bindApiCall(this, "admin.users.invite"), - /** - * @description List users on a workspace. - * @see {@link https://api.slack.com/methods/admin.users.list `admin.users.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "admin.users.list"), - /** - * @description Remove a user from a workspace. - * @see {@link https://api.slack.com/methods/admin.users.remove `admin.users.remove` API reference}. - */ - remove: bindApiCall(this, "admin.users.remove"), - session: { - /** - * @description Clear user-specific session settings—the session duration and what happens when the client - * closes—for a list of users. - * @see {@link https://api.slack.com/methods/admin.users.session.clearSettings `admin.users.session.clearSettings` API reference}. - */ - clearSettings: bindApiCall(this, "admin.users.session.clearSettings"), - /** - * @description Get user-specific session settings—the session duration and what happens when the client - * closes—given a list of users. - * @see {@link https://api.slack.com/methods/admin.users.session.getSettings `admin.users.session.getSettings` API reference}. - */ - getSettings: bindApiCall(this, "admin.users.session.getSettings"), - /** - * @description Revoke a single session for a user. The user will be forced to login to Slack. - * @see {@link https://api.slack.com/methods/admin.users.session.invalidate `admin.users.session.invalidate` API reference}. - */ - invalidate: bindApiCall(this, "admin.users.session.invalidate"), - /** - * @description List active user sessions for an organization. - * @see {@link https://api.slack.com/methods/admin.users.session.list `admin.users.session.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "admin.users.session.list"), - /** - * @description Wipes all valid sessions on all devices for a given user. - * @see {@link https://api.slack.com/methods/admin.users.session.reset `admin.users.session.reset` API reference}. - */ - reset: bindApiCall(this, "admin.users.session.reset"), - /** - * @description Enqueues an asynchronous job to wipe all valid sessions on all devices for a given user list. - * @see {@link https://api.slack.com/methods/admin.users.session.resetBulk `admin.users.session.resetBulk` API reference}. - */ - resetBulk: bindApiCall(this, "admin.users.session.resetBulk"), - /** - * @description Configure the user-level session settings—the session duration and what happens when the client - * closes—for one or more users. - * @see {@link https://api.slack.com/methods/admin.users.session.setSettings `admin.users.session.setSettings` API reference}. - */ - setSettings: bindApiCall(this, "admin.users.session.setSettings") - }, - /** - * @description Set an existing guest, regular user, or owner to be an admin user. - * @see {@link https://api.slack.com/methods/admin.users.setAdmin `admin.users.setAdmin` API reference}. - */ - setAdmin: bindApiCall(this, "admin.users.setAdmin"), - /** - * @description Set an expiration for a guest user. - * @see {@link https://api.slack.com/methods/admin.users.setExpiration `admin.users.setExpiration` API reference}. - */ - setExpiration: bindApiCall(this, "admin.users.setExpiration"), - /** - * @description Set an existing guest, regular user, or admin user to be a workspace owner. - * @see {@link https://api.slack.com/methods/admin.users.setOwner `admin.users.setOwner` API reference}. - */ - setOwner: bindApiCall(this, "admin.users.setOwner"), - /** - * @description Set an existing guest user, admin user, or owner to be a regular user. - * @see {@link https://api.slack.com/methods/admin.users.setRegular `admin.users.setRegular` API reference}. - */ - setRegular: bindApiCall(this, "admin.users.setRegular"), - unsupportedVersions: { - /** - * @description Ask Slackbot to send you an export listing all workspace members using unsupported software, - * presented as a zipped CSV file. - * @see {@link https://api.slack.com/methods/admin.users.unsupportedVersions.export `admin.users.unsupportedVersions.export` API reference}. - */ - export: bindApiCall(this, "admin.users.unsupportedVersions.export") + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug); + } + return debug; + } + function extend2(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split3 = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns2 of split3) { + if (ns2[0] === "-") { + createDebug.skips.push(ns2.slice(1)); + } else { + createDebug.names.push(ns2); + } + } + } + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; + } + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; + } + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + for (const skip2 of createDebug.skips) { + if (matchesTemplate(name, skip2)) { + return false; + } + } + for (const ns2 of createDebug.names) { + if (matchesTemplate(name, ns2)) { + return true; + } + } + return false; + } + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + module2.exports = setup; + } +}); + +// node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/debug/src/browser.js"(exports2, module2) { + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load; + exports2.useColors = useColors; + exports2.storage = localstorage(); + exports2.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports2.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m2; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m2 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m2[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index2 = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index2++; + if (match === "%c") { + lastC = index2; + } + }); + args.splice(lastC, 0, c); + } + exports2.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports2.storage.setItem("debug", namespaces); + } else { + exports2.storage.removeItem("debug"); + } + } catch (error) { + } + } + function load() { + let r; + try { + r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); + } catch (error) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error) { + } + } + module2.exports = require_common2()(exports2); + var { formatters } = module2.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error) { + return "[UnexpectedJSONParseError]: " + error.message; + } + }; + } +}); + +// node_modules/has-flag/index.js +var require_has_flag2 = __commonJS({ + "node_modules/has-flag/index.js"(exports2, module2) { + "use strict"; + module2.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; + } +}); + +// node_modules/supports-color/index.js +var require_supports_color = __commonJS({ + "node_modules/supports-color/index.js"(exports2, module2) { + "use strict"; + var os2 = __require("os"); + var tty = __require("tty"); + var hasFlag = require_has_flag2(); + var { env } = process; + var forceColor; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { + forceColor = 0; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + forceColor = 1; + } + if ("FORCE_COLOR" in env) { + if (env.FORCE_COLOR === "true") { + forceColor = 1; + } else if (env.FORCE_COLOR === "false") { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } + } + function translateLevel(level) { + if (level === 0) { + return false; + } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; + } + if (hasFlag("color=256")) { + return 2; + } + if (haveStream && !streamIsTTY && forceColor === void 0) { + return 0; + } + const min = forceColor || 0; + if (env.TERM === "dumb") { + return min; + } + if (process.platform === "win32") { + const osRelease = os2.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign2) => sign2 in env) || env.CI_NAME === "codeship") { + return 1; + } + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if (env.COLORTERM === "truecolor") { + return 3; + } + if ("TERM_PROGRAM" in env) { + const version4 = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version4 >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; + } + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + return min; + } + function getSupportLevel(stream4) { + const level = supportsColor(stream4, stream4 && stream4.isTTY); + return translateLevel(level); + } + module2.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) + }; + } +}); + +// node_modules/debug/src/node.js +var require_node3 = __commonJS({ + "node_modules/debug/src/node.js"(exports2, module2) { + var tty = __require("tty"); + var util3 = __require("util"); + exports2.init = init; + exports2.log = log; + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load; + exports2.useColors = useColors; + exports2.destroy = util3.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports2.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = require_supports_color(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports2.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error) { + } + exports2.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k2) => { + return k2.toUpperCase(); + }); + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === "null") { + val = null; + } else { + val = Number(val); + } + obj[prop] = val; + return obj; + }, {}); + function useColors() { + return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + function formatArgs(args) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args[0] = prefix + args[0].split("\n").join("\n" + prefix); + args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + " " + args[0]; + } + } + function getDate() { + if (exports2.inspectOpts.hideDate) { + return ""; + } + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + function log(...args) { + return process.stderr.write(util3.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + } + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + function load() { + return process.env.DEBUG; + } + function init(debug) { + debug.inspectOpts = {}; + const keys = Object.keys(exports2.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + } + } + module2.exports = require_common2()(exports2); + var { formatters } = module2.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util3.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util3.inspect(v, this.inspectOpts); + }; + } +}); + +// node_modules/debug/src/index.js +var require_src = __commonJS({ + "node_modules/debug/src/index.js"(exports2, module2) { + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + module2.exports = require_browser(); + } else { + module2.exports = require_node3(); + } + } +}); + +// node_modules/follow-redirects/debug.js +var require_debug = __commonJS({ + "node_modules/follow-redirects/debug.js"(exports2, module2) { + var debug; + module2.exports = function() { + if (!debug) { + try { + debug = require_src()("follow-redirects"); + } catch (error) { + } + if (typeof debug !== "function") { + debug = function() { + }; + } + } + debug.apply(null, arguments); + }; + } +}); + +// node_modules/follow-redirects/index.js +var require_follow_redirects = __commonJS({ + "node_modules/follow-redirects/index.js"(exports2, module2) { + var url2 = __require("url"); + var URL2 = url2.URL; + var http3 = __require("http"); + var https2 = __require("https"); + var Writable = __require("stream").Writable; + var assert3 = __require("assert"); + var debug = require_debug(); + (function detectUnsupportedEnvironment() { + var looksLikeNode = typeof process !== "undefined"; + var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; + var looksLikeV8 = isFunction2(Error.captureStackTrace); + if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { + console.warn("The follow-redirects package should be excluded from browser builds."); + } + })(); + var useNativeURL = false; + try { + assert3(new URL2("")); + } catch (error) { + useNativeURL = error.code === "ERR_INVALID_URL"; + } + var preservedUrlFields = [ + "auth", + "host", + "hostname", + "href", + "path", + "pathname", + "port", + "protocol", + "query", + "search", + "hash" + ]; + var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; + var eventHandlers = /* @__PURE__ */ Object.create(null); + events.forEach(function(event) { + eventHandlers[event] = function(arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; + }); + var InvalidUrlError = createErrorType( + "ERR_INVALID_URL", + "Invalid URL", + TypeError + ); + var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "Redirected request failed" + ); + var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded", + RedirectionError + ); + var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" + ); + var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" + ); + var destroy = Writable.prototype.destroy || noop2; + function RedirectableRequest(options, responseCallback) { + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; + if (responseCallback) { + this.on("response", responseCallback); + } + var self2 = this; + this._onNativeResponse = function(response) { + try { + self2._processResponse(response); + } catch (cause) { + self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause })); + } + }; + this._performRequest(); + } + RedirectableRequest.prototype = Object.create(Writable.prototype); + RedirectableRequest.prototype.abort = function() { + destroyRequest(this._currentRequest); + this._currentRequest.abort(); + this.emit("abort"); + }; + RedirectableRequest.prototype.destroy = function(error) { + destroyRequest(this._currentRequest, error); + destroy.call(this, error); + return this; + }; + RedirectableRequest.prototype.write = function(data, encoding, callback) { + if (this._ending) { + throw new WriteAfterEndError(); + } + if (!isString2(data) && !isBuffer2(data)) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (isFunction2(encoding)) { + callback = encoding; + encoding = null; + } + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data, encoding }); + this._currentRequest.write(data, encoding, callback); + } else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } + }; + RedirectableRequest.prototype.end = function(data, encoding, callback) { + if (isFunction2(data)) { + callback = data; + data = encoding = null; + } else if (isFunction2(encoding)) { + callback = encoding; + encoding = null; + } + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } else { + var self2 = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function() { + self2._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; + } + }; + RedirectableRequest.prototype.setHeader = function(name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); + }; + RedirectableRequest.prototype.removeHeader = function(name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); + }; + RedirectableRequest.prototype.setTimeout = function(msecs, callback) { + var self2 = this; + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } + function startTimer(socket) { + if (self2._timeout) { + clearTimeout(self2._timeout); + } + self2._timeout = setTimeout(function() { + self2.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } + function clearTimer() { + if (self2._timeout) { + clearTimeout(self2._timeout); + self2._timeout = null; + } + self2.removeListener("abort", clearTimer); + self2.removeListener("error", clearTimer); + self2.removeListener("response", clearTimer); + self2.removeListener("close", clearTimer); + if (callback) { + self2.removeListener("timeout", callback); + } + if (!self2.socket) { + self2._currentRequest.removeListener("socket", startTimer); + } + } + if (callback) { + this.on("timeout", callback); + } + if (this.socket) { + startTimer(this.socket); + } else { + this._currentRequest.once("socket", startTimer); + } + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + this.on("close", clearTimer); + return this; + }; + [ + "flushHeaders", + "getHeader", + "setNoDelay", + "setSocketKeepAlive" + ].forEach(function(method) { + RedirectableRequest.prototype[method] = function(a, b2) { + return this._currentRequest[method](a, b2); + }; + }); + ["aborted", "connection", "socket"].forEach(function(property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function() { + return this._currentRequest[property]; + } + }); + }); + RedirectableRequest.prototype._sanitizeOptions = function(options) { + if (!options.headers) { + options.headers = {}; + } + if (options.host) { + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } + }; + RedirectableRequest.prototype._performRequest = function() { + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + throw new TypeError("Unsupported protocol " + protocol); + } + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } + var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse); + request._redirectable = this; + for (var event of events) { + request.on(event, eventHandlers[event]); + } + this._currentUrl = /^\//.test(this._options.path) ? url2.format(this._options) : ( + // When making a request to a proxy, […] + // a client MUST send the target URI in absolute-form […]. + this._options.path + ); + if (this._isRedirect) { + var i = 0; + var self2 = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + if (request === self2._currentRequest) { + if (error) { + self2.emit("error", error); + } else if (i < buffers.length) { + var buffer2 = buffers[i++]; + if (!request.finished) { + request.write(buffer2.data, buffer2.encoding, writeNext); + } + } else if (self2._ended) { + request.end(); } - }, - workflows: { - collaborators: { - /** - * @description Add collaborators to workflows within the team or enterprise. - * @see {@link https://api.slack.com/methods/admin.workflows.collaborators.add `admin.workflows.collaborators.add` API reference}. - */ - add: bindApiCall(this, "admin.workflows.collaborators.add"), - /** - * @description Remove collaborators from workflows within the team or enterprise. - * @see {@link https://api.slack.com/methods/admin.workflows.collaborators.remove `admin.workflows.collaborators.remove` API reference}. - */ - remove: bindApiCall(this, "admin.workflows.collaborators.remove") - }, - permissions: { - /** - * @description Look up the permissions for a set of workflows. - * @see {@link https://api.slack.com/methods/admin.workflows.permissions.lookup `admin.workflows.permissions.lookup` API reference}. - */ - lookup: bindApiCall(this, "admin.workflows.permissions.lookup") - }, - /** - * @description Search workflows within the team or enterprise. - * @see {@link https://api.slack.com/methods/admin.workflows.search `admin.workflows.search` API reference}. - */ - search: bindApiCallWithOptionalArgument(this, "admin.workflows.search"), - /** - * @description Unpublish workflows within the team or enterprise. - * @see {@link https://api.slack.com/methods/admin.workflows.unpublish `admin.workflows.unpublish` API reference}. - */ - unpublish: bindApiCall(this, "admin.workflows.unpublish") } - }; - this.api = { - /** - * @description Checks API calling code. - * @see {@link https://api.slack.com/methods/api.test `api.test` API reference}. - */ - test: bindApiCallWithOptionalArgument(this, "api.test") - }; - this.assistant = { - threads: { - /** - * @description Set loading status to indicate that the app is building a response. - * @see {@link https://api.slack.com/methods/assistant.threads.setStatus `assistant.threads.setStatus` API reference}. - */ - setStatus: bindApiCall(this, "assistant.threads.setStatus"), - /** - * @description Set suggested prompts for the user. Can suggest up to four prompts. - * @see {@link https://api.slack.com/methods/assistant.threads.setSuggestedPrompts `assistant.threads.setSuggestedPrompts` API reference}. - */ - setSuggestedPrompts: bindApiCall(this, "assistant.threads.setSuggestedPrompts"), - /** - * @description Set the title of the thread. This is shown when a user views the app's chat history. - * @see {@link https://api.slack.com/methods/assistant.threads.setTitle `assistant.threads.setTitle` API reference}. - */ - setTitle: bindApiCall(this, "assistant.threads.setTitle") + })(); + } + }; + RedirectableRequest.prototype._processResponse = function(response) { + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode + }); + } + var location = response.headers.location; + if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); + this._requestBodyBuffers = []; + return; + } + destroyRequest(this._currentRequest); + response.destroy(); + if (++this._redirectCount > this._options.maxRedirects) { + throw new TooManyRedirectsError(); + } + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + // The Host header was set by nativeProtocol.request + Host: response.req.getHeader("host") + }, this._options.headers); + } + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); + var currentUrlParts = parseUrl(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url2.format(Object.assign(currentUrlParts, { host: currentHost })); + var redirectUrl = resolveUrl(location, currentUrl); + debug("redirecting to", redirectUrl.href); + this._isRedirect = true; + spreadUrlObject(redirectUrl, this._options); + if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) { + removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); + } + if (isFunction2(beforeRedirect)) { + var responseDetails = { + headers: response.headers, + statusCode + }; + var requestDetails = { + url: currentUrl, + method, + headers: requestHeaders + }; + beforeRedirect(this._options, responseDetails, requestDetails); + this._sanitizeOptions(this._options); + } + this._performRequest(); + }; + function wrap(protocols) { + var exports3 = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024 + }; + var nativeProtocols = {}; + Object.keys(protocols).forEach(function(scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports3[scheme] = Object.create(nativeProtocol); + function request(input, options, callback) { + if (isURL(input)) { + input = spreadUrlObject(input); + } else if (isString2(input)) { + input = spreadUrlObject(parseUrl(input)); + } else { + callback = options; + options = validateUrl(input); + input = { protocol }; + } + if (isFunction2(options)) { + callback = options; + options = null; + } + options = Object.assign({ + maxRedirects: exports3.maxRedirects, + maxBodyLength: exports3.maxBodyLength + }, input, options); + options.nativeProtocols = nativeProtocols; + if (!isString2(options.host) && !isString2(options.hostname)) { + options.hostname = "::1"; + } + assert3.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true } + }); + }); + return exports3; + } + function noop2() { + } + function parseUrl(input) { + var parsed; + if (useNativeURL) { + parsed = new URL2(input); + } else { + parsed = validateUrl(url2.parse(input)); + if (!isString2(parsed.protocol)) { + throw new InvalidUrlError({ input }); + } + } + return parsed; + } + function resolveUrl(relative, base) { + return useNativeURL ? new URL2(relative, base) : parseUrl(url2.resolve(base, relative)); + } + function validateUrl(input) { + if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { + throw new InvalidUrlError({ input: input.href || input }); + } + if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { + throw new InvalidUrlError({ input: input.href || input }); + } + return input; + } + function spreadUrlObject(urlObject, target) { + var spread3 = target || {}; + for (var key of preservedUrlFields) { + spread3[key] = urlObject[key]; + } + if (spread3.hostname.startsWith("[")) { + spread3.hostname = spread3.hostname.slice(1, -1); + } + if (spread3.port !== "") { + spread3.port = Number(spread3.port); + } + spread3.path = spread3.search ? spread3.pathname + spread3.search : spread3.pathname; + return spread3; + } + function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } + } + return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim(); + } + function createErrorType(code, message, baseClass) { + function CustomError(properties) { + if (isFunction2(Error.captureStackTrace)) { + Error.captureStackTrace(this, this.constructor); + } + Object.assign(this, properties || {}); + this.code = code; + this.message = this.cause ? message + ": " + this.cause.message : message; + } + CustomError.prototype = new (baseClass || Error)(); + Object.defineProperties(CustomError.prototype, { + constructor: { + value: CustomError, + enumerable: false + }, + name: { + value: "Error [" + code + "]", + enumerable: false + } + }); + return CustomError; + } + function destroyRequest(request, error) { + for (var event of events) { + request.removeListener(event, eventHandlers[event]); + } + request.on("error", noop2); + request.destroy(error); + } + function isSubdomain(subdomain, domain) { + assert3(isString2(subdomain) && isString2(domain)); + var dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); + } + function isString2(value) { + return typeof value === "string" || value instanceof String; + } + function isFunction2(value) { + return typeof value === "function"; + } + function isBuffer2(value) { + return typeof value === "object" && "length" in value; + } + function isURL(value) { + return URL2 && value instanceof URL2; + } + module2.exports = wrap({ http: http3, https: https2 }); + module2.exports.wrap = wrap; + } +}); + +// node_modules/axios/dist/node/axios.cjs +var require_axios = __commonJS({ + "node_modules/axios/dist/node/axios.cjs"(exports2, module2) { + "use strict"; + var FormData$1 = require_form_data(); + var crypto4 = __require("crypto"); + var url2 = __require("url"); + var proxyFromEnv2 = require_proxy_from_env(); + var http3 = __require("http"); + var https2 = __require("https"); + var util3 = __require("util"); + var followRedirects2 = require_follow_redirects(); + var zlib2 = __require("zlib"); + var stream4 = __require("stream"); + var events = __require("events"); + function _interopDefaultLegacy(e) { + return e && typeof e === "object" && "default" in e ? e : { "default": e }; + } + var FormData__default = /* @__PURE__ */ _interopDefaultLegacy(FormData$1); + var crypto__default = /* @__PURE__ */ _interopDefaultLegacy(crypto4); + var url__default = /* @__PURE__ */ _interopDefaultLegacy(url2); + var proxyFromEnv__default = /* @__PURE__ */ _interopDefaultLegacy(proxyFromEnv2); + var http__default = /* @__PURE__ */ _interopDefaultLegacy(http3); + var https__default = /* @__PURE__ */ _interopDefaultLegacy(https2); + var util__default = /* @__PURE__ */ _interopDefaultLegacy(util3); + var followRedirects__default = /* @__PURE__ */ _interopDefaultLegacy(followRedirects2); + var zlib__default = /* @__PURE__ */ _interopDefaultLegacy(zlib2); + var stream__default = /* @__PURE__ */ _interopDefaultLegacy(stream4); + function bind2(fn2, thisArg) { + return function wrap() { + return fn2.apply(thisArg, arguments); + }; + } + var { toString: toString3 } = Object.prototype; + var { getPrototypeOf: getPrototypeOf2 } = Object; + var { iterator: iterator2, toStringTag: toStringTag2 } = Symbol; + var kindOf2 = /* @__PURE__ */ ((cache) => (thing) => { + const str = toString3.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + })(/* @__PURE__ */ Object.create(null)); + var kindOfTest2 = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf2(thing) === type; + }; + var typeOfTest2 = (type) => (thing) => typeof thing === type; + var { isArray: isArray2 } = Array; + var isUndefined2 = typeOfTest2("undefined"); + function isBuffer2(val) { + return val !== null && !isUndefined2(val) && val.constructor !== null && !isUndefined2(val.constructor) && isFunction2(val.constructor.isBuffer) && val.constructor.isBuffer(val); + } + var isArrayBuffer2 = kindOfTest2("ArrayBuffer"); + function isArrayBufferView2(val) { + let result; + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + result = ArrayBuffer.isView(val); + } else { + result = val && val.buffer && isArrayBuffer2(val.buffer); + } + return result; + } + var isString2 = typeOfTest2("string"); + var isFunction2 = typeOfTest2("function"); + var isNumber2 = typeOfTest2("number"); + var isObject2 = (thing) => thing !== null && typeof thing === "object"; + var isBoolean2 = (thing) => thing === true || thing === false; + var isPlainObject2 = (val) => { + if (kindOf2(val) !== "object") { + return false; + } + const prototype4 = getPrototypeOf2(val); + return (prototype4 === null || prototype4 === Object.prototype || Object.getPrototypeOf(prototype4) === null) && !(toStringTag2 in val) && !(iterator2 in val); + }; + var isDate2 = kindOfTest2("Date"); + var isFile2 = kindOfTest2("File"); + var isBlob2 = kindOfTest2("Blob"); + var isFileList2 = kindOfTest2("FileList"); + var isStream2 = (val) => isObject2(val) && isFunction2(val.pipe); + var isFormData2 = (thing) => { + let kind; + return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction2(thing.append) && ((kind = kindOf2(thing)) === "formdata" || // detect form-data instance + kind === "object" && isFunction2(thing.toString) && thing.toString() === "[object FormData]")); + }; + var isURLSearchParams2 = kindOfTest2("URLSearchParams"); + var [isReadableStream2, isRequest2, isResponse2, isHeaders2] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest2); + var trim5 = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); + function forEach2(obj, fn2, { allOwnKeys = false } = {}) { + if (obj === null || typeof obj === "undefined") { + return; + } + let i; + let l; + if (typeof obj !== "object") { + obj = [obj]; + } + if (isArray2(obj)) { + for (i = 0, l = obj.length; i < l; i++) { + fn2.call(null, obj[i], i, obj); + } + } else { + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + fn2.call(null, obj[key], key, obj); + } + } + } + function findKey2(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } + } + return null; + } + var _global2 = (() => { + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; + })(); + var isContextDefined2 = (context) => !isUndefined2(context) && context !== _global2; + function merge2() { + const { caseless } = isContextDefined2(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey2(result, key) || key; + if (isPlainObject2(result[targetKey]) && isPlainObject2(val)) { + result[targetKey] = merge2(result[targetKey], val); + } else if (isPlainObject2(val)) { + result[targetKey] = merge2({}, val); + } else if (isArray2(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach2(arguments[i], assignValue); + } + return result; + } + var extend2 = (a, b2, thisArg, { allOwnKeys } = {}) => { + forEach2(b2, (val, key) => { + if (thisArg && isFunction2(val)) { + a[key] = bind2(val, thisArg); + } else { + a[key] = val; + } + }, { allOwnKeys }); + return a; + }; + var stripBOM2 = (content) => { + if (content.charCodeAt(0) === 65279) { + content = content.slice(1); + } + return content; + }; + var inherits2 = (constructor, superConstructor, props, descriptors3) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors3); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, "super", { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); + }; + var toFlatObject2 = (sourceObj, destObj, filter2, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + destObj = destObj || {}; + if (sourceObj == null) return destObj; + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter2 !== false && getPrototypeOf2(sourceObj); + } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype); + return destObj; + }; + var endsWith2 = (str, searchString, position) => { + str = String(str); + if (position === void 0 || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; + }; + var toArray2 = (thing) => { + if (!thing) return null; + if (isArray2(thing)) return thing; + let i = thing.length; + if (!isNumber2(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; + }; + var isTypedArray2 = /* @__PURE__ */ ((TypedArray) => { + return (thing) => { + return TypedArray && thing instanceof TypedArray; + }; + })(typeof Uint8Array !== "undefined" && getPrototypeOf2(Uint8Array)); + var forEachEntry2 = (obj, fn2) => { + const generator = obj && obj[iterator2]; + const _iterator = generator.call(obj); + let result; + while ((result = _iterator.next()) && !result.done) { + const pair = result.value; + fn2.call(obj, pair[0], pair[1]); + } + }; + var matchAll2 = (regExp, str) => { + let matches; + const arr = []; + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + return arr; + }; + var isHTMLForm2 = kindOfTest2("HTMLFormElement"); + var toCamelCase2 = (str) => { + return str.toLowerCase().replace( + /[-_\s]([a-z\d])(\w*)/g, + function replacer(m2, p1, p2) { + return p1.toUpperCase() + p2; + } + ); + }; + var hasOwnProperty2 = (({ hasOwnProperty: hasOwnProperty3 }) => (obj, prop) => hasOwnProperty3.call(obj, prop))(Object.prototype); + var isRegExp2 = kindOfTest2("RegExp"); + var reduceDescriptors2 = (obj, reducer) => { + const descriptors3 = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + forEach2(descriptors3, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + Object.defineProperties(obj, reducedDescriptors); + }; + var freezeMethods2 = (obj) => { + reduceDescriptors2(obj, (descriptor, name) => { + if (isFunction2(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) { + return false; + } + const value = obj[name]; + if (!isFunction2(value)) return; + descriptor.enumerable = false; + if ("writable" in descriptor) { + descriptor.writable = false; + return; + } + if (!descriptor.set) { + descriptor.set = () => { + throw Error("Can not rewrite read-only method '" + name + "'"); + }; + } + }); + }; + var toObjectSet2 = (arrayOrString, delimiter) => { + const obj = {}; + const define2 = (arr) => { + arr.forEach((value) => { + obj[value] = true; + }); + }; + isArray2(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); + return obj; + }; + var noop2 = () => { + }; + var toFiniteNumber2 = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; + }; + function isSpecCompliantForm2(thing) { + return !!(thing && isFunction2(thing.append) && thing[toStringTag2] === "FormData" && thing[iterator2]); + } + var toJSONObject2 = (obj) => { + const stack = new Array(10); + const visit = (source, i) => { + if (isObject2(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + if (!("toJSON" in source)) { + stack[i] = source; + const target = isArray2(source) ? [] : {}; + forEach2(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined2(reducedValue) && (target[key] = reducedValue); + }); + stack[i] = void 0; + return target; + } + } + return source; + }; + return visit(obj, 0); + }; + var isAsyncFn2 = kindOfTest2("AsyncFunction"); + var isThenable2 = (thing) => thing && (isObject2(thing) || isFunction2(thing)) && isFunction2(thing.then) && isFunction2(thing.catch); + var _setImmediate2 = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; + } + return postMessageSupported ? ((token, callbacks) => { + _global2.addEventListener("message", ({ source, data }) => { + if (source === _global2 && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + return (cb) => { + callbacks.push(cb); + _global2.postMessage(token, "*"); + }; + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); + })( + typeof setImmediate === "function", + isFunction2(_global2.postMessage) + ); + var asap2 = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global2) : typeof process !== "undefined" && process.nextTick || _setImmediate2; + var isIterable2 = (thing) => thing != null && isFunction2(thing[iterator2]); + var utils$1 = { + isArray: isArray2, + isArrayBuffer: isArrayBuffer2, + isBuffer: isBuffer2, + isFormData: isFormData2, + isArrayBufferView: isArrayBufferView2, + isString: isString2, + isNumber: isNumber2, + isBoolean: isBoolean2, + isObject: isObject2, + isPlainObject: isPlainObject2, + isReadableStream: isReadableStream2, + isRequest: isRequest2, + isResponse: isResponse2, + isHeaders: isHeaders2, + isUndefined: isUndefined2, + isDate: isDate2, + isFile: isFile2, + isBlob: isBlob2, + isRegExp: isRegExp2, + isFunction: isFunction2, + isStream: isStream2, + isURLSearchParams: isURLSearchParams2, + isTypedArray: isTypedArray2, + isFileList: isFileList2, + forEach: forEach2, + merge: merge2, + extend: extend2, + trim: trim5, + stripBOM: stripBOM2, + inherits: inherits2, + toFlatObject: toFlatObject2, + kindOf: kindOf2, + kindOfTest: kindOfTest2, + endsWith: endsWith2, + toArray: toArray2, + forEachEntry: forEachEntry2, + matchAll: matchAll2, + isHTMLForm: isHTMLForm2, + hasOwnProperty: hasOwnProperty2, + hasOwnProp: hasOwnProperty2, + // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors: reduceDescriptors2, + freezeMethods: freezeMethods2, + toObjectSet: toObjectSet2, + toCamelCase: toCamelCase2, + noop: noop2, + toFiniteNumber: toFiniteNumber2, + findKey: findKey2, + global: _global2, + isContextDefined: isContextDefined2, + isSpecCompliantForm: isSpecCompliantForm2, + toJSONObject: toJSONObject2, + isAsyncFn: isAsyncFn2, + isThenable: isThenable2, + setImmediate: _setImmediate2, + asap: asap2, + isIterable: isIterable2 + }; + function AxiosError3(message, code, config3, request, response) { + Error.call(this); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; + } + this.message = message; + this.name = "AxiosError"; + code && (this.code = code); + config3 && (this.config = config3); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; + } + } + utils$1.inherits(AxiosError3, Error, { + toJSON: function toJSON2() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils$1.toJSONObject(this.config), + code: this.code, + status: this.status + }; + } + }); + var prototype$1 = AxiosError3.prototype; + var descriptors2 = {}; + [ + "ERR_BAD_OPTION_VALUE", + "ERR_BAD_OPTION", + "ECONNABORTED", + "ETIMEDOUT", + "ERR_NETWORK", + "ERR_FR_TOO_MANY_REDIRECTS", + "ERR_DEPRECATED", + "ERR_BAD_RESPONSE", + "ERR_BAD_REQUEST", + "ERR_CANCELED", + "ERR_NOT_SUPPORT", + "ERR_INVALID_URL" + // eslint-disable-next-line func-names + ].forEach((code) => { + descriptors2[code] = { value: code }; + }); + Object.defineProperties(AxiosError3, descriptors2); + Object.defineProperty(prototype$1, "isAxiosError", { value: true }); + AxiosError3.from = (error, code, config3, request, response, customProps) => { + const axiosError = Object.create(prototype$1); + utils$1.toFlatObject(error, axiosError, function filter2(obj) { + return obj !== Error.prototype; + }, (prop) => { + return prop !== "isAxiosError"; + }); + AxiosError3.call(axiosError, error.message, code, config3, request, response); + axiosError.cause = error; + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; + }; + function isVisitable2(thing) { + return utils$1.isPlainObject(thing) || utils$1.isArray(thing); + } + function removeBrackets2(key) { + return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key; + } + function renderKey2(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + token = removeBrackets2(token); + return !dots && i ? "[" + token + "]" : token; + }).join(dots ? "." : ""); + } + function isFlatArray2(arr) { + return utils$1.isArray(arr) && !arr.some(isVisitable2); + } + var predicates2 = utils$1.toFlatObject(utils$1, {}, null, function filter2(prop) { + return /^is[A-Z]/.test(prop); + }); + function toFormData3(obj, formData, options) { + if (!utils$1.isObject(obj)) { + throw new TypeError("target must be an object"); + } + formData = formData || new (FormData__default["default"] || FormData)(); + options = utils$1.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + return !utils$1.isUndefined(source[option]); + }); + const metaTokens = options.metaTokens; + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; + const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + if (!utils$1.isFunction(visitor)) { + throw new TypeError("visitor must be a function"); + } + function convertValue(value) { + if (value === null) return ""; + if (utils$1.isDate(value)) { + return value.toISOString(); + } + if (!useBlob && utils$1.isBlob(value)) { + throw new AxiosError3("Blob is not supported. Use a Buffer instead."); + } + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { + return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); + } + return value; + } + function defaultVisitor(value, key, path) { + let arr = value; + if (value && !path && typeof value === "object") { + if (utils$1.endsWith(key, "{}")) { + key = metaTokens ? key : key.slice(0, -2); + value = JSON.stringify(value); + } else if (utils$1.isArray(value) && isFlatArray2(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) { + key = removeBrackets2(key); + arr.forEach(function each(el2, index2) { + !(utils$1.isUndefined(el2) || el2 === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey2([key], index2, dots) : indexes === null ? key : key + "[]", + convertValue(el2) + ); + }); + return false; + } + } + if (isVisitable2(value)) { + return true; + } + formData.append(renderKey2(path, key, dots), convertValue(value)); + return false; + } + const stack = []; + const exposedHelpers = Object.assign(predicates2, { + defaultVisitor, + convertValue, + isVisitable: isVisitable2 + }); + function build(value, path) { + if (utils$1.isUndefined(value)) return; + if (stack.indexOf(value) !== -1) { + throw Error("Circular reference detected in " + path.join(".")); + } + stack.push(value); + utils$1.forEach(value, function each(el2, key) { + const result = !(utils$1.isUndefined(el2) || el2 === null) && visitor.call( + formData, + el2, + utils$1.isString(key) ? key.trim() : key, + path, + exposedHelpers + ); + if (result === true) { + build(el2, path ? path.concat(key) : [key]); + } + }); + stack.pop(); + } + if (!utils$1.isObject(obj)) { + throw new TypeError("data must be an object"); + } + build(obj); + return formData; + } + function encode$1(str) { + const charMap = { + "!": "%21", + "'": "%27", + "(": "%28", + ")": "%29", + "~": "%7E", + "%20": "+", + "%00": "\0" + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); + } + function AxiosURLSearchParams2(params, options) { + this._pairs = []; + params && toFormData3(params, this, options); + } + var prototype3 = AxiosURLSearchParams2.prototype; + prototype3.append = function append2(name, value) { + this._pairs.push([name, value]); + }; + prototype3.toString = function toString4(encoder5) { + const _encode = encoder5 ? function(value) { + return encoder5.call(this, value, encode$1); + } : encode$1; + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + "=" + _encode(pair[1]); + }, "").join("&"); + }; + function encode6(val) { + return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); + } + function buildURL2(url3, params, options) { + if (!params) { + return url3; + } + const _encode = options && options.encode || encode6; + if (utils$1.isFunction(options)) { + options = { + serialize: options + }; + } + const serializeFn = options && options.serialize; + let serializedParams; + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams2(params, options).toString(_encode); + } + if (serializedParams) { + const hashmarkIndex = url3.indexOf("#"); + if (hashmarkIndex !== -1) { + url3 = url3.slice(0, hashmarkIndex); + } + url3 += (url3.indexOf("?") === -1 ? "?" : "&") + serializedParams; + } + return url3; + } + var InterceptorManager2 = class { + constructor() { + this.handlers = []; + } + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id2) { + if (this.handlers[id2]) { + this.handlers[id2] = null; + } + } + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; + } + } + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn2) { + utils$1.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn2(h); + } + }); + } + }; + var InterceptorManager$1 = InterceptorManager2; + var transitionalDefaults = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false + }; + var URLSearchParams = url__default["default"].URLSearchParams; + var ALPHA2 = "abcdefghijklmnopqrstuvwxyz"; + var DIGIT2 = "0123456789"; + var ALPHABET2 = { + DIGIT: DIGIT2, + ALPHA: ALPHA2, + ALPHA_DIGIT: ALPHA2 + ALPHA2.toUpperCase() + DIGIT2 + }; + var generateString2 = (size5 = 16, alphabet = ALPHABET2.ALPHA_DIGIT) => { + let str = ""; + const { length } = alphabet; + const randomValues = new Uint32Array(size5); + crypto__default["default"].randomFillSync(randomValues); + for (let i = 0; i < size5; i++) { + str += alphabet[randomValues[i] % length]; + } + return str; + }; + var platform$1 = { + isNode: true, + classes: { + URLSearchParams, + FormData: FormData__default["default"], + Blob: typeof Blob !== "undefined" && Blob || null + }, + ALPHABET: ALPHABET2, + generateString: generateString2, + protocols: ["http", "https", "file", "data"] + }; + var hasBrowserEnv2 = typeof window !== "undefined" && typeof document !== "undefined"; + var _navigator2 = typeof navigator === "object" && navigator || void 0; + var hasStandardBrowserEnv2 = hasBrowserEnv2 && (!_navigator2 || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator2.product) < 0); + var hasStandardBrowserWebWorkerEnv2 = (() => { + return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; + })(); + var origin2 = hasBrowserEnv2 && window.location.href || "http://localhost"; + var utils = /* @__PURE__ */ Object.freeze({ + __proto__: null, + hasBrowserEnv: hasBrowserEnv2, + hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv2, + hasStandardBrowserEnv: hasStandardBrowserEnv2, + navigator: _navigator2, + origin: origin2 + }); + var platform = { + ...utils, + ...platform$1 + }; + function toURLEncodedForm2(data, options) { + return toFormData3(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform.isNode && utils$1.isBuffer(value)) { + this.append(key, value.toString("base64")); + return false; } - }; - this.apps = { - connections: { - /** - * @description Generate a temporary Socket Mode WebSocket URL that your app can connect to in order to receive - * events and interactive payloads over. - * @see {@link https://api.slack.com/methods/apps.connections.open `apps.connections.open` API reference}. - */ - open: bindApiCallWithOptionalArgument(this, "apps.connections.open") - }, - event: { - authorizations: { - /** - * @description Get a list of authorizations for the given event context. - * Each authorization represents an app installation that the event is visible to. - * @see {@link https://api.slack.com/methods/apps.event.authorizations.list `apps.event.authorizations.list` API reference}. - */ - list: bindApiCall(this, "apps.event.authorizations.list") + return helpers.defaultVisitor.apply(this, arguments); + } + }, options)); + } + function parsePropPath2(name) { + return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => { + return match[0] === "[]" ? "" : match[1] || match[0]; + }); + } + function arrayToObject2(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; + } + function formDataToJSON2(formData) { + function buildPath(path, value, target, index2) { + let name = path[index2++]; + if (name === "__proto__") return true; + const isNumericKey = Number.isFinite(+name); + const isLast = index2 >= path.length; + name = !name && utils$1.isArray(target) ? target.length : name; + if (isLast) { + if (utils$1.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + return !isNumericKey; + } + if (!target[name] || !utils$1.isObject(target[name])) { + target[name] = []; + } + const result = buildPath(path, value, target[name], index2); + if (result && utils$1.isArray(target[name])) { + target[name] = arrayToObject2(target[name]); + } + return !isNumericKey; + } + if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { + const obj = {}; + utils$1.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath2(name), value, obj, 0); + }); + return obj; + } + return null; + } + function stringifySafely2(rawValue, parser, encoder5) { + if (utils$1.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils$1.trim(rawValue); + } catch (e) { + if (e.name !== "SyntaxError") { + throw e; + } + } + } + return (encoder5 || JSON.stringify)(rawValue); + } + var defaults2 = { + transitional: transitionalDefaults, + adapter: ["xhr", "http", "fetch"], + transformRequest: [function transformRequest2(data, headers) { + const contentType = headers.getContentType() || ""; + const hasJSONContentType = contentType.indexOf("application/json") > -1; + const isObjectPayload = utils$1.isObject(data); + if (isObjectPayload && utils$1.isHTMLForm(data)) { + data = new FormData(data); + } + const isFormData3 = utils$1.isFormData(data); + if (isFormData3) { + return hasJSONContentType ? JSON.stringify(formDataToJSON2(data)) : data; + } + if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) { + return data; + } + if (utils$1.isArrayBufferView(data)) { + return data.buffer; + } + if (utils$1.isURLSearchParams(data)) { + headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); + return data.toString(); + } + let isFileList3; + if (isObjectPayload) { + if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { + return toURLEncodedForm2(data, this.formSerializer).toString(); + } + if ((isFileList3 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { + const _FormData = this.env && this.env.FormData; + return toFormData3( + isFileList3 ? { "files[]": data } : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + if (isObjectPayload || hasJSONContentType) { + headers.setContentType("application/json", false); + return stringifySafely2(data); + } + return data; + }], + transformResponse: [function transformResponse2(data) { + const transitional2 = this.transitional || defaults2.transitional; + const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing; + const JSONRequested = this.responseType === "json"; + if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) { + return data; + } + if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { + const silentJSONParsing = transitional2 && transitional2.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === "SyntaxError") { + throw AxiosError3.from(e, AxiosError3.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; } + } + } + return data; + }], + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + xsrfCookieName: "XSRF-TOKEN", + xsrfHeaderName: "X-XSRF-TOKEN", + maxContentLength: -1, + maxBodyLength: -1, + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + validateStatus: function validateStatus2(status) { + return status >= 200 && status < 300; + }, + headers: { + common: { + "Accept": "application/json, text/plain, */*", + "Content-Type": void 0 + } + } + }; + utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { + defaults2.headers[method] = {}; + }); + var defaults$1 = defaults2; + var ignoreDuplicateOf2 = utils$1.toObjectSet([ + "age", + "authorization", + "content-length", + "content-type", + "etag", + "expires", + "from", + "host", + "if-modified-since", + "if-unmodified-since", + "last-modified", + "location", + "max-forwards", + "proxy-authorization", + "referer", + "retry-after", + "user-agent" + ]); + var parseHeaders = (rawHeaders) => { + const parsed = {}; + let key; + let val; + let i; + rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { + i = line.indexOf(":"); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + if (!key || parsed[key] && ignoreDuplicateOf2[key]) { + return; + } + if (key === "set-cookie") { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; + } + }); + return parsed; + }; + var $internals2 = Symbol("internals"); + function normalizeHeader2(header) { + return header && String(header).trim().toLowerCase(); + } + function normalizeValue2(value) { + if (value === false || value == null) { + return value; + } + return utils$1.isArray(value) ? value.map(normalizeValue2) : String(value); + } + function parseTokens2(str) { + const tokens = /* @__PURE__ */ Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + while (match = tokensRE.exec(str)) { + tokens[match[1]] = match[2]; + } + return tokens; + } + var isValidHeaderName2 = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + function matchHeaderValue2(context, value, header, filter2, isHeaderNameFilter) { + if (utils$1.isFunction(filter2)) { + return filter2.call(this, value, header); + } + if (isHeaderNameFilter) { + value = header; + } + if (!utils$1.isString(value)) return; + if (utils$1.isString(filter2)) { + return value.indexOf(filter2) !== -1; + } + if (utils$1.isRegExp(filter2)) { + return filter2.test(value); + } + } + function formatHeader2(header) { + return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str) => { + return char.toUpperCase() + str; + }); + } + function buildAccessors2(obj, header) { + const accessorName = utils$1.toCamelCase(" " + header); + ["get", "set", "has"].forEach((methodName) => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); }, - manifest: { - /** - * @description Create an app from an app manifest. - * @see {@link https://api.slack.com/methods/apps.manifest.create `apps.manifest.create` API reference}. - */ - create: bindApiCall(this, "apps.manifest.create"), - /** - * @description Permanently deletes an app created through app manifests. - * @see {@link https://api.slack.com/methods/apps.manifest.delete `apps.manifest.delete` API reference}. - */ - delete: bindApiCall(this, "apps.manifest.delete"), - /** - * @description Export an app manifest from an existing app. - * @see {@link https://api.slack.com/methods/apps.manifest.export `apps.manifest.export` API reference}. - */ - export: bindApiCall(this, "apps.manifest.export"), - /** - * @description Update an app from an app manifest. - * @see {@link https://api.slack.com/methods/apps.manifest.update `apps.manifest.update` API reference}. - */ - update: bindApiCall(this, "apps.manifest.update"), - /** - * @description Validate an app manifest. - * @see {@link https://api.slack.com/methods/apps.manifest.validate `apps.manifest.validate` API reference}. - */ - validate: bindApiCall(this, "apps.manifest.validate") - }, - /** - * @description Uninstalls your app from a workspace. - * @see {@link https://api.slack.com/methods/apps.uninstall `apps.uninstall` API reference}. - */ - uninstall: bindApiCall(this, "apps.uninstall") - }; - this.auth = { - /** - * @description Revokes a token. - * @see {@link https://api.slack.com/methods/auth.revoke `auth.revoke` API reference}. - */ - revoke: bindApiCallWithOptionalArgument(this, "auth.revoke"), - teams: { - /** - * @description Obtain a full list of workspaces your org-wide app has been approved for. - * @see {@link https://api.slack.com/methods/auth.teams.list `auth.teams.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "auth.teams.list") - }, - test: bindApiCallWithOptionalArgument(this, "auth.test") - }; - this.bookmarks = { - /** - * @description Add bookmark to a channel. - * @see {@link https://api.slack.com/methods/bookmarks.add `bookmarks.add` API reference}. - */ - add: bindApiCall(this, "bookmarks.add"), - /** - * @description Edit bookmark. - * @see {@link https://api.slack.com/methods/bookmarks.edit `bookmarks.edit` API reference}. - */ - edit: bindApiCall(this, "bookmarks.edit"), - /** - * @description List bookmarks for a channel. - * @see {@link https://api.slack.com/methods/bookmarks.list `bookmarks.list` API reference}. - */ - list: bindApiCall(this, "bookmarks.list"), - /** - * @description Remove bookmark from a channel. - * @see {@link https://api.slack.com/methods/bookmarks.remove `bookmarks.remove` API reference}. - */ - remove: bindApiCall(this, "bookmarks.remove") - }; - this.bots = { - /** - * @description Gets information about a bot user. - * @see {@link https://api.slack.com/methods/bots.info `bots.info` API reference}. - */ - info: bindApiCallWithOptionalArgument(this, "bots.info") - }; - this.calls = { - /** - * @description Registers a new Call. - * @see {@link https://api.slack.com/methods/calls.add `calls.add` API reference}. - */ - add: bindApiCall(this, "calls.add"), - /** - * @description Ends a Call. - * @see {@link https://api.slack.com/methods/calls.end `calls.end` API reference}. - */ - end: bindApiCall(this, "calls.end"), - /** - * @description Returns information about a Call. - * @see {@link https://api.slack.com/methods/calls.info `calls.info` API reference}. - */ - info: bindApiCall(this, "calls.info"), - /** - * @description Updates information about a Call. - * @see {@link https://api.slack.com/methods/calls.info `calls.info` API reference}. - */ - update: bindApiCall(this, "calls.update"), - participants: { - /** - * @description Registers new participants added to a Call. - * @see {@link https://api.slack.com/methods/calls.participants.add `calls.participants.add` API reference}. - */ - add: bindApiCall(this, "calls.participants.add"), - remove: bindApiCall(this, "calls.participants.remove") + configurable: true + }); + }); + } + var AxiosHeaders3 = class { + constructor(headers) { + headers && this.set(headers); + } + set(header, valueOrRewrite, rewrite) { + const self2 = this; + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader2(_header); + if (!lHeader) { + throw new Error("header name must be a non-empty string"); + } + const key = utils$1.findKey(self2, lHeader); + if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { + self2[key || _header] = normalizeValue2(_value); + } + } + const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + if (utils$1.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName2(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else if (utils$1.isObject(header) && utils$1.isIterable(header)) { + let obj = {}, dest, key; + for (const entry of header) { + if (!utils$1.isArray(entry)) { + throw TypeError("Object iterator must return a key-value pair"); + } + obj[key = entry[0]] = (dest = obj[key]) ? utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1]; } - }; - this.canvases = { - access: { - /** - * @description Remove access to a canvas for specified entities. - * @see {@link https://api.slack.com/methods/canvases.access.delete `canvases.access.delete` API reference}. - */ - delete: bindApiCall(this, "canvases.access.delete"), - /** - * @description Sets the access level to a canvas for specified entities. - * @see {@link https://api.slack.com/methods/canvases.access.set `canvases.access.set` API reference}. - */ - set: bindApiCall(this, "canvases.access.set") - }, - /** - * @description Create Canvas for a user. - * @see {@link https://api.slack.com/methods/canvases.create `canvases.create` API reference}. - */ - create: bindApiCallWithOptionalArgument(this, "canvases.create"), - /** - * @description Deletes a canvas. - * @see {@link https://api.slack.com/methods/canvases.delete `canvases.delete` API reference}. - */ - delete: bindApiCall(this, "canvases.delete"), - /** - * @description Update an existing canvas. - * @see {@link https://api.slack.com/methods/canvases.edit `canvases.edit` API reference}. - */ - edit: bindApiCall(this, "canvases.edit"), - sections: { - /** - * @description Find sections matching the provided criteria. - * @see {@link https://api.slack.com/methods/canvases.sections.lookup `canvases.sections.lookup` API reference}. - */ - lookup: bindApiCall(this, "canvases.sections.lookup") + setHeaders(obj, valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + return this; + } + get(header, parser) { + header = normalizeHeader2(header); + if (header) { + const key = utils$1.findKey(this, header); + if (key) { + const value = this[key]; + if (!parser) { + return value; + } + if (parser === true) { + return parseTokens2(value); + } + if (utils$1.isFunction(parser)) { + return parser.call(this, value, key); + } + if (utils$1.isRegExp(parser)) { + return parser.exec(value); + } + throw new TypeError("parser must be boolean|regexp|function"); } + } + } + has(header, matcher) { + header = normalizeHeader2(header); + if (header) { + const key = utils$1.findKey(this, header); + return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue2(this, this[key], key, matcher))); + } + return false; + } + delete(header, matcher) { + const self2 = this; + let deleted = false; + function deleteHeader(_header) { + _header = normalizeHeader2(_header); + if (_header) { + const key = utils$1.findKey(self2, _header); + if (key && (!matcher || matchHeaderValue2(self2, self2[key], key, matcher))) { + delete self2[key]; + deleted = true; + } + } + } + if (utils$1.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + return deleted; + } + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + while (i--) { + const key = keys[i]; + if (!matcher || matchHeaderValue2(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + return deleted; + } + normalize(format) { + const self2 = this; + const headers = {}; + utils$1.forEach(this, (value, header) => { + const key = utils$1.findKey(headers, header); + if (key) { + self2[key] = normalizeValue2(value); + delete self2[header]; + return; + } + const normalized = format ? formatHeader2(header) : String(header).trim(); + if (normalized !== header) { + delete self2[header]; + } + self2[normalized] = normalizeValue2(value); + headers[normalized] = true; + }); + return this; + } + concat(...targets) { + return this.constructor.concat(this, ...targets); + } + toJSON(asStrings) { + const obj = /* @__PURE__ */ Object.create(null); + utils$1.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value); + }); + return obj; + } + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); + } + getSetCookie() { + return this.get("set-cookie") || []; + } + get [Symbol.toStringTag]() { + return "AxiosHeaders"; + } + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + static concat(first, ...targets) { + const computed = new this(first); + targets.forEach((target) => computed.set(target)); + return computed; + } + static accessor(header) { + const internals = this[$internals2] = this[$internals2] = { + accessors: {} }; - this.chat = { - /** - * @description Deletes a message. - * @see {@link https://api.slack.com/methods/chat.delete `chat.delete` API reference}. - */ - delete: bindApiCall(this, "chat.delete"), - /** - * @description Deletes a pending scheduled message from the queue. - * @see {@link https://api.slack.com/methods/chat.deleteScheduledMessage `chat.deleteScheduledMessage` API reference}. - */ - deleteScheduledMessage: bindApiCall(this, "chat.deleteScheduledMessage"), - /** - * @description Retrieve a permalink URL for a specific extant message. - * @see {@link https://api.slack.com/methods/chat.getPermalink `chat.getPermalink` API reference}. - */ - getPermalink: bindApiCall(this, "chat.getPermalink"), - /** - * @description Share a me message into a channel. - * @see {@link https://api.slack.com/methods/chat.meMessage `chat.meMessage` API reference}. - */ - meMessage: bindApiCall(this, "chat.meMessage"), - /** - * @description Sends an ephemeral message to a user in a channel. - * @see {@link https://api.slack.com/methods/chat.postEphemeral `chat.postEphemeral` API reference}. - */ - postEphemeral: bindApiCall(this, "chat.postEphemeral"), - /** - * @description Sends a message to a channel. - * @see {@link https://api.slack.com/methods/chat.postMessage `chat.postMessage` API reference}. - */ - postMessage: bindApiCall(this, "chat.postMessage"), - /** - * @description Schedules a message to be sent to a channel. - * @see {@link https://api.slack.com/methods/chat.scheduleMessage `chat.scheduleMessage` API reference}. - */ - scheduleMessage: bindApiCall(this, "chat.scheduleMessage"), - scheduledMessages: { - /** - * @description Returns a list of scheduled messages. - * @see {@link https://api.slack.com/methods/chat.scheduledMessages.list `chat.scheduledMessages.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "chat.scheduledMessages.list") - }, - /** - * @description Provide custom unfurl behavior for user-posted URLs. - * @see {@link https://api.slack.com/methods/chat.unfurl `chat.unfurl` API reference}. - */ - unfurl: bindApiCall(this, "chat.unfurl"), - /** - * @description Updates a message. - * @see {@link https://api.slack.com/methods/chat.update `chat.update` API reference}. - */ - update: bindApiCall(this, "chat.update") - }; - this.conversations = { - /** - * @description Accepts an invitation to a Slack Connect channel. - * @see {@link https://api.slack.com/methods/conversations.acceptSharedInvite `conversations.acceptSharedInvite` API reference}. - */ - acceptSharedInvite: bindApiCall(this, "conversations.acceptSharedInvite"), - /** - * @description Approves an invitation to a Slack Connect channel. - * @see {@link https://api.slack.com/methods/conversations.approveSharedInvite `conversations.approveSharedInvite` API reference}. - */ - approveSharedInvite: bindApiCall(this, "conversations.approveSharedInvite"), - /** - * @description Archives a conversation. - * @see {@link https://api.slack.com/methods/conversations.archive `conversations.archive` API reference}. - */ - archive: bindApiCall(this, "conversations.archive"), - canvases: { - /** - * @description Create a Channel Canvas for a channel. - * @see {@link https://api.slack.com/methods/conversations.canvases.create `conversations.canvases.create` API reference}. - */ - create: bindApiCall(this, "conversations.canvases.create") - }, - /** - * @description Closes a direct message or multi-person direct message. - * @see {@link https://api.slack.com/methods/conversations.close `conversations.close` API reference}. - */ - close: bindApiCall(this, "conversations.close"), - /** - * @description Initiates a public or private channel-based conversation. - * @see {@link https://api.slack.com/methods/conversations.create `conversations.create` API reference}. - */ - create: bindApiCall(this, "conversations.create"), - /** - * @description Declines an invitation to a Slack Connect channel. - * @see {@link https://api.slack.com/methods/conversations.declineSharedInvite `conversations.declineSharedInvite` API reference}. - */ - declineSharedInvite: bindApiCall(this, "conversations.declineSharedInvite"), - externalInvitePermissions: { - /** - * @description Convert a team in a shared channel from an External Limited channel to a fully shared Slack - * Connect channel or vice versa. - * @see {@link https://api.slack.com/methods/conversations.externalInvitePermissions.set `conversations.externalInvitePermissions.set` API reference}. - */ - set: bindApiCall(this, "conversations.externalInvitePermissions.set") - }, - /** - * @description Fetches a conversation's history of messages and events. - * @see {@link https://api.slack.com/methods/conversations.history `conversations.history` API reference}. - */ - history: bindApiCall(this, "conversations.history"), - /** - * @description Retrieve information about a conversation. - * @see {@link https://api.slack.com/methods/conversations.info `conversations.info` API reference}. - */ - info: bindApiCall(this, "conversations.info"), - /** - * @description Invites users to a channel. - * @see {@link https://api.slack.com/methods/conversations.invite `conversations.invite` API reference}. - */ - invite: bindApiCall(this, "conversations.invite"), - /** - * @description Sends an invitation to a Slack Connect channel. - * @see {@link https://api.slack.com/methods/conversations.inviteShared `conversations.inviteShared` API reference}. - */ - inviteShared: bindApiCall(this, "conversations.inviteShared"), - /** - * @description Joins an existing conversation. - * @see {@link https://api.slack.com/methods/conversations.join `conversations.join` API reference}. - */ - join: bindApiCall(this, "conversations.join"), - /** - * @description Removes a user from a conversation. - * @see {@link https://api.slack.com/methods/conversations.kick `conversations.kick` API reference}. - */ - kick: bindApiCall(this, "conversations.kick"), - /** - * @description Leaves a conversation. - * @see {@link https://api.slack.com/methods/conversations.leave `conversations.leave` API reference}. - */ - leave: bindApiCall(this, "conversations.leave"), - /** - * @description List all channels in a Slack team. - * @see {@link https://api.slack.com/methods/conversations.list `conversations.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "conversations.list"), - /** - * @description Lists shared channel invites that have been generated or received but have not been approved by - * all parties. - * @see {@link https://api.slack.com/methods/conversations.listConnectInvites `conversations.listConnectInvites` API reference}. - */ - listConnectInvites: bindApiCallWithOptionalArgument(this, "conversations.listConnectInvites"), - /** - * @description Sets the read cursor in a channel. - * @see {@link https://api.slack.com/methods/conversations.mark `conversations.mark` API reference}. - */ - mark: bindApiCall(this, "conversations.mark"), - /** - * @description Retrieve members of a conversation. - * @see {@link https://api.slack.com/methods/conversations.members `conversations.members` API reference}. - */ - members: bindApiCall(this, "conversations.members"), - /** - * @description Opens or resumes a direct message or multi-person direct message. - * @see {@link https://api.slack.com/methods/conversations.open `conversations.open` API reference}. - */ - open: bindApiCall(this, "conversations.open"), - /** - * @description Renames a conversation. - * @see {@link https://api.slack.com/methods/conversations.rename `conversations.rename` API reference}. - */ - rename: bindApiCall(this, "conversations.rename"), - /** - * @description Retrieve a thread of messages posted to a conversation. - * @see {@link https://api.slack.com/methods/conversations.replies `conversations.replies` API reference}. - */ - replies: bindApiCall(this, "conversations.replies"), - requestSharedInvite: { - /** - * @description Approves a request to add an external user to a channel and sends them a Slack Connect invite. - * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.approve `conversations.requestSharedInvite.approve` API reference}. - */ - approve: bindApiCall(this, "conversations.requestSharedInvite.approve"), - /** - * @description Denies a request to invite an external user to a channel. - * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.deny `conversations.requestSharedInvite.deny` API reference}. - */ - deny: bindApiCall(this, "conversations.requestSharedInvite.deny"), - /** - * @description Lists requests to add external users to channels with ability to filter. - * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.list `conversations.requestSharedInvite.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "conversations.requestSharedInvite.list") - }, - /** - * @description Sets the purpose for a conversation. - * @see {@link https://api.slack.com/methods/conversations.setPurpose `conversations.setPurpose` API reference}. - */ - setPurpose: bindApiCall(this, "conversations.setPurpose"), - /** - * @description Sets the topic for a conversation. - * @see {@link https://api.slack.com/methods/conversations.setTopic `conversations.setTopic` API reference}. - */ - setTopic: bindApiCall(this, "conversations.setTopic"), - /** - * @description Reverses conversation archival. - * @see {@link https://api.slack.com/methods/conversations.unarchive `conversations.unarchive` API reference}. - */ - unarchive: bindApiCall(this, "conversations.unarchive") - }; - this.dialog = { - /** - * @description Open a dialog with a user. - * @see {@link https://api.slack.com/methods/dialog.open `dialog.open` API reference}. - */ - open: bindApiCall(this, "dialog.open") - }; - this.dnd = { - /** - * @description Ends the current user's Do Not Disturb session immediately. - * @see {@link https://api.slack.com/methods/dnd.endDnd `dnd.endDnd` API reference}. - */ - endDnd: bindApiCallWithOptionalArgument(this, "dnd.endDnd"), - /** - * @description Ends the current user's snooze mode immediately. - * @see {@link https://api.slack.com/methods/dnd.endSnooze `dnd.endSnooze` API reference}. - */ - endSnooze: bindApiCallWithOptionalArgument(this, "dnd.endSnooze"), - /** - * @description Retrieves a user's current Do Not Disturb status. - * @see {@link https://api.slack.com/methods/dnd.info `dnd.info` API reference}. - */ - info: bindApiCallWithOptionalArgument(this, "dnd.info"), - /** - * @description Turns on Do Not Disturb mode for the current user, or changes its duration. - * @see {@link https://api.slack.com/methods/dnd.setSnooze `dnd.setSnooze` API reference}. - */ - setSnooze: bindApiCall(this, "dnd.setSnooze"), - /** - * @description Retrieves the Do Not Disturb status for up to 50 users on a team. - * @see {@link https://api.slack.com/methods/dnd.teamInfo `dnd.teamInfo` API reference}. - */ - teamInfo: bindApiCall(this, "dnd.teamInfo") - }; - this.emoji = { - /** - * @description Lists custom emoji for a team. - * @see {@link https://api.slack.com/methods/emoji.list `emoji.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "emoji.list") - }; - this.files = { - /** - * @description Finishes an upload started with {@link https://api.slack.com/methods/files.getUploadURLExternal `files.getUploadURLExternal`}. - * @see {@link https://api.slack.com/methods/files.completeUploadExternal `files.completeUploadExternal` API reference}. - */ - completeUploadExternal: bindApiCall(this, "files.completeUploadExternal"), - /** - * @description Deletes a file. - * @see {@link https://api.slack.com/methods/files.delete `files.delete` API reference}. - */ - delete: bindApiCall(this, "files.delete"), - /** - * @description Gets a URL for an edge external file upload. - * @see {@link https://api.slack.com/methods/files.getUploadURLExternal `files.getUploadURLExternal` API reference}. - */ - getUploadURLExternal: bindApiCall(this, "files.getUploadURLExternal"), - /** - * @description Gets information about a file. - * @see {@link https://api.slack.com/methods/files.info `files.info` API reference}. - */ - info: bindApiCall(this, "files.info"), - /** - * @description List files for a team, in a channel, or from a user with applied filters. - * @see {@link https://api.slack.com/methods/files.list `files.list` API reference}. - */ - list: bindApiCall(this, "files.list"), - /** - * @description Revokes public/external sharing access for a file. - * @see {@link https://api.slack.com/methods/files.revokePublicURL `files.revokePublicURL` API reference}. - */ - revokePublicURL: bindApiCall(this, "files.revokePublicURL"), - /** - * @description Enables a file for public/external sharing. - * @see {@link https://api.slack.com/methods/files.revokePublicURL `files.revokePublicURL` API reference}. - */ - sharedPublicURL: bindApiCall(this, "files.sharedPublicURL"), - /** - * @description Uploads or creates a file. - * @deprecated Use `uploadV2` instead. See {@link https://api.slack.com/changelog/2024-04-a-better-way-to-upload-files-is-here-to-stay our post on retiring `files.upload`}. - * @see {@link https://api.slack.com/methods/files.upload `files.upload` API reference}. - */ - upload: bindApiCall(this, "files.upload"), - /** - * @description Custom method to support a new way of uploading files to Slack. - * Supports a single file upload - * Supply: - * - (required) single file or content - * - (optional) channel, alt_text, snippet_type, - * Supports multiple file uploads - * Supply: - * - multiple upload_files - * Will try to honor both single file or content data supplied as well - * as multiple file uploads property. - * @see {@link https://tools.slack.dev/node-slack-sdk/web-api#upload-a-file `@slack/web-api` Upload a file documentation}. - */ - uploadV2: bindFilesUploadV2(this), - comments: { - /** - * @description Deletes an existing comment on a file. - * @see {@link https://api.slack.com/methods/files.comments.delete `files.comments.delete` API reference}. - */ - delete: bindApiCall(this, "files.comments.delete") - }, - remote: { - /** - * @description Adds a file from a remote service. - * @see {@link https://api.slack.com/methods/files.remote.add `files.remote.add` API reference}. - */ - add: bindApiCall(this, "files.remote.add"), - /** - * @description Retrieve information about a remote file added to Slack. - * @see {@link https://api.slack.com/methods/files.remote.info `files.remote.info` API reference}. - */ - info: bindApiCall(this, "files.remote.info"), - /** - * @description List remote files added to Slack. - * @see {@link https://api.slack.com/methods/files.remote.list `files.remote.list` API reference}. - */ - list: bindApiCall(this, "files.remote.list"), - /** - * @description Remove a remote file. - * @see {@link https://api.slack.com/methods/files.remote.remove `files.remote.remove` API reference}. - */ - remove: bindApiCall(this, "files.remote.remove"), - /** - * @description Share a remote file into a channel. - * @see {@link https://api.slack.com/methods/files.remote.share `files.remote.share` API reference}. - */ - share: bindApiCall(this, "files.remote.share"), - /** - * @description Updates an existing remote file. - * @see {@link https://api.slack.com/methods/files.remote.update `files.remote.update` API reference}. - */ - update: bindApiCall(this, "files.remote.update") + const accessors = internals.accessors; + const prototype4 = this.prototype; + function defineAccessor(_header) { + const lHeader = normalizeHeader2(_header); + if (!accessors[lHeader]) { + buildAccessors2(prototype4, _header); + accessors[lHeader] = true; + } + } + utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + return this; + } + }; + AxiosHeaders3.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); + utils$1.reduceDescriptors(AxiosHeaders3.prototype, ({ value }, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } + }; + }); + utils$1.freezeMethods(AxiosHeaders3); + var AxiosHeaders$1 = AxiosHeaders3; + function transformData2(fns, response) { + const config3 = this || defaults$1; + const context = response || config3; + const headers = AxiosHeaders$1.from(context.headers); + let data = context.data; + utils$1.forEach(fns, function transform(fn2) { + data = fn2.call(config3, data, headers.normalize(), response ? response.status : void 0); + }); + headers.normalize(); + return data; + } + function isCancel3(value) { + return !!(value && value.__CANCEL__); + } + function CanceledError3(message, config3, request) { + AxiosError3.call(this, message == null ? "canceled" : message, AxiosError3.ERR_CANCELED, config3, request); + this.name = "CanceledError"; + } + utils$1.inherits(CanceledError3, AxiosError3, { + __CANCEL__: true + }); + function settle2(resolve, reject, response) { + const validateStatus2 = response.config.validateStatus; + if (!response.status || !validateStatus2 || validateStatus2(response.status)) { + resolve(response); + } else { + reject(new AxiosError3( + "Request failed with status code " + response.status, + [AxiosError3.ERR_BAD_REQUEST, AxiosError3.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } + } + function isAbsoluteURL2(url3) { + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url3); + } + function combineURLs2(baseURL, relativeURL) { + return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; + } + function buildFullPath2(baseURL, requestedURL, allowAbsoluteUrls) { + let isRelativeUrl = !isAbsoluteURL2(requestedURL); + if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) { + return combineURLs2(baseURL, requestedURL); + } + return requestedURL; + } + var VERSION3 = "1.9.0"; + function parseProtocol2(url3) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url3); + return match && match[1] || ""; + } + var DATA_URL_PATTERN2 = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; + function fromDataURI2(uri, asBlob, options) { + const _Blob = options && options.Blob || platform.classes.Blob; + const protocol = parseProtocol2(uri); + if (asBlob === void 0 && _Blob) { + asBlob = true; + } + if (protocol === "data") { + uri = protocol.length ? uri.slice(protocol.length + 1) : uri; + const match = DATA_URL_PATTERN2.exec(uri); + if (!match) { + throw new AxiosError3("Invalid URL", AxiosError3.ERR_INVALID_URL); + } + const mime = match[1]; + const isBase64 = match[2]; + const body = match[3]; + const buffer2 = Buffer.from(decodeURIComponent(body), isBase64 ? "base64" : "utf8"); + if (asBlob) { + if (!_Blob) { + throw new AxiosError3("Blob is not supported", AxiosError3.ERR_NOT_SUPPORT); } + return new _Blob([buffer2], { type: mime }); + } + return buffer2; + } + throw new AxiosError3("Unsupported protocol " + protocol, AxiosError3.ERR_NOT_SUPPORT); + } + var kInternals2 = Symbol("internals"); + var AxiosTransformStream2 = class extends stream__default["default"].Transform { + constructor(options) { + options = utils$1.toFlatObject(options, { + maxRate: 0, + chunkSize: 64 * 1024, + minChunkSize: 100, + timeWindow: 500, + ticksRate: 2, + samplesCount: 15 + }, null, (prop, source) => { + return !utils$1.isUndefined(source[prop]); + }); + super({ + readableHighWaterMark: options.chunkSize + }); + const internals = this[kInternals2] = { + timeWindow: options.timeWindow, + chunkSize: options.chunkSize, + maxRate: options.maxRate, + minChunkSize: options.minChunkSize, + bytesSeen: 0, + isCaptured: false, + notifiedBytesLoaded: 0, + ts: Date.now(), + bytes: 0, + onReadCallback: null }; - this.functions = { - /** - * @description Signal the failure to execute a Custom Function. - * @see {@link https://api.slack.com/methods/functions.completeError `functions.completeError` API reference}. - */ - completeError: bindApiCall(this, "functions.completeError"), - /** - * @description Signal the successful completion of a Custom Function. - * @see {@link https://api.slack.com/methods/functions.completeSuccess `functions.completeSuccess` API reference}. - */ - completeSuccess: bindApiCall(this, "functions.completeSuccess") - }; - this.migration = { - /** - * @description For Enterprise Grid workspaces, map local user IDs to global user IDs. - * @see {@link https://api.slack.com/methods/migration.exchange `migration.exchange` API reference}. - */ - exchange: bindApiCall(this, "migration.exchange") + this.on("newListener", (event) => { + if (event === "progress") { + if (!internals.isCaptured) { + internals.isCaptured = true; + } + } + }); + } + _read(size5) { + const internals = this[kInternals2]; + if (internals.onReadCallback) { + internals.onReadCallback(); + } + return super._read(size5); + } + _transform(chunk, encoding, callback) { + const internals = this[kInternals2]; + const maxRate = internals.maxRate; + const readableHighWaterMark = this.readableHighWaterMark; + const timeWindow = internals.timeWindow; + const divider = 1e3 / timeWindow; + const bytesThreshold = maxRate / divider; + const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; + const pushChunk = (_chunk, _callback) => { + const bytes = Buffer.byteLength(_chunk); + internals.bytesSeen += bytes; + internals.bytes += bytes; + internals.isCaptured && this.emit("progress", internals.bytesSeen); + if (this.push(_chunk)) { + process.nextTick(_callback); + } else { + internals.onReadCallback = () => { + internals.onReadCallback = null; + process.nextTick(_callback); + }; + } }; - this.oauth = { - /** - * @description Exchanges a temporary OAuth verifier code for an access token. - * @deprecated This is a legacy method only used by classic Slack apps. Use `oauth.v2.access` for new Slack apps. - * @see {@link https://api.slack.com/methods/oauth.access `oauth.access` API reference}. - */ - access: bindApiCall(this, "oauth.access"), - v2: { - /** - * @description Exchanges a temporary OAuth verifier code for an access token. - * @see {@link https://api.slack.com/methods/oauth.v2.access `oauth.v2.access` API reference}. - */ - access: bindApiCall(this, "oauth.v2.access"), - /** - * @description Exchanges a legacy access token for a new expiring access token and refresh token. - * @see {@link https://api.slack.com/methods/oauth.v2.exchange `oauth.v2.exchange` API reference}. - */ - exchange: bindApiCall(this, "oauth.v2.exchange") + const transformChunk = (_chunk, _callback) => { + const chunkSize = Buffer.byteLength(_chunk); + let chunkRemainder = null; + let maxChunkSize = readableHighWaterMark; + let bytesLeft; + let passed = 0; + if (maxRate) { + const now = Date.now(); + if (!internals.ts || (passed = now - internals.ts) >= timeWindow) { + internals.ts = now; + bytesLeft = bytesThreshold - internals.bytes; + internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; + passed = 0; + } + bytesLeft = bytesThreshold - internals.bytes; + } + if (maxRate) { + if (bytesLeft <= 0) { + return setTimeout(() => { + _callback(null, _chunk); + }, timeWindow - passed); + } + if (bytesLeft < maxChunkSize) { + maxChunkSize = bytesLeft; + } + } + if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) { + chunkRemainder = _chunk.subarray(maxChunkSize); + _chunk = _chunk.subarray(0, maxChunkSize); } + pushChunk(_chunk, chunkRemainder ? () => { + process.nextTick(_callback, null, chunkRemainder); + } : _callback); }; - this.openid = { - connect: { - /** - * @description Exchanges a temporary OAuth verifier code for an access token for {@link https://api.slack.com/authentication/sign-in-with-slack Sign in with Slack}. - * @see {@link https://api.slack.com/methods/openid.connect.token `openid.connect.token` API reference}. - */ - token: bindApiCall(this, "openid.connect.token"), - /** - * @description Get the identity of a user who has authorized {@link https://api.slack.com/authentication/sign-in-with-slack Sign in with Slack}. - * @see {@link https://api.slack.com/methods/openid.connect.userInfo `openid.connect.userInfo` API reference}. - */ - userInfo: bindApiCallWithOptionalArgument(this, "openid.connect.userInfo") + transformChunk(chunk, function transformNextChunk(err, _chunk) { + if (err) { + return callback(err); + } + if (_chunk) { + transformChunk(_chunk, transformNextChunk); + } else { + callback(null); + } + }); + } + }; + var AxiosTransformStream$1 = AxiosTransformStream2; + var { asyncIterator: asyncIterator2 } = Symbol; + var readBlob2 = async function* (blob) { + if (blob.stream) { + yield* blob.stream(); + } else if (blob.arrayBuffer) { + yield await blob.arrayBuffer(); + } else if (blob[asyncIterator2]) { + yield* blob[asyncIterator2](); + } else { + yield blob; + } + }; + var readBlob$1 = readBlob2; + var BOUNDARY_ALPHABET2 = platform.ALPHABET.ALPHA_DIGIT + "-_"; + var textEncoder2 = typeof TextEncoder === "function" ? new TextEncoder() : new util__default["default"].TextEncoder(); + var CRLF2 = "\r\n"; + var CRLF_BYTES2 = textEncoder2.encode(CRLF2); + var CRLF_BYTES_COUNT2 = 2; + var FormDataPart2 = class { + constructor(name, value) { + const { escapeName } = this.constructor; + const isStringValue = utils$1.isString(value); + let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF2}`; + if (isStringValue) { + value = textEncoder2.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF2)); + } else { + headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF2}`; + } + this.headers = textEncoder2.encode(headers + CRLF2); + this.contentLength = isStringValue ? value.byteLength : value.size; + this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT2; + this.name = name; + this.value = value; + } + async *encode() { + yield this.headers; + const { value } = this; + if (utils$1.isTypedArray(value)) { + yield value; + } else { + yield* readBlob$1(value); + } + yield CRLF_BYTES2; + } + static escapeName(name) { + return String(name).replace(/[\r\n"]/g, (match) => ({ + "\r": "%0D", + "\n": "%0A", + '"': "%22" + })[match]); + } + }; + var formDataToStream2 = (form, headersHandler, options) => { + const { + tag = "form-data-boundary", + size: size5 = 25, + boundary = tag + "-" + platform.generateString(size5, BOUNDARY_ALPHABET2) + } = options || {}; + if (!utils$1.isFormData(form)) { + throw TypeError("FormData instance required"); + } + if (boundary.length < 1 || boundary.length > 70) { + throw Error("boundary must be 10-70 characters long"); + } + const boundaryBytes = textEncoder2.encode("--" + boundary + CRLF2); + const footerBytes = textEncoder2.encode("--" + boundary + "--" + CRLF2); + let contentLength = footerBytes.byteLength; + const parts = Array.from(form.entries()).map(([name, value]) => { + const part = new FormDataPart2(name, value); + contentLength += part.size; + return part; + }); + contentLength += boundaryBytes.byteLength * parts.length; + contentLength = utils$1.toFiniteNumber(contentLength); + const computedHeaders = { + "Content-Type": `multipart/form-data; boundary=${boundary}` + }; + if (Number.isFinite(contentLength)) { + computedHeaders["Content-Length"] = contentLength; + } + headersHandler && headersHandler(computedHeaders); + return stream4.Readable.from(async function* () { + for (const part of parts) { + yield boundaryBytes; + yield* part.encode(); + } + yield footerBytes; + }()); + }; + var formDataToStream$1 = formDataToStream2; + var ZlibHeaderTransformStream2 = class extends stream__default["default"].Transform { + __transform(chunk, encoding, callback) { + this.push(chunk); + callback(); + } + _transform(chunk, encoding, callback) { + if (chunk.length !== 0) { + this._transform = this.__transform; + if (chunk[0] !== 120) { + const header = Buffer.alloc(2); + header[0] = 120; + header[1] = 156; + this.push(header, encoding); + } + } + this.__transform(chunk, encoding, callback); + } + }; + var ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream2; + var callbackify2 = (fn2, reducer) => { + return utils$1.isAsyncFn(fn2) ? function(...args) { + const cb = args.pop(); + fn2.apply(this, args).then((value) => { + try { + reducer ? cb(null, ...reducer(value)) : cb(null, value); + } catch (err) { + cb(err); + } + }, cb); + } : fn2; + }; + var callbackify$1 = callbackify2; + function speedometer2(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + min = min !== void 0 ? min : 1e3; + return function push(chunkLength) { + const now = Date.now(); + const startedAt = timestamps[tail]; + if (!firstSampleTS) { + firstSampleTS = now; + } + bytes[head] = chunkLength; + timestamps[head] = now; + let i = tail; + let bytesCount = 0; + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + head = (head + 1) % samplesCount; + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + if (now - firstSampleTS < min) { + return; + } + const passed = startedAt && now - startedAt; + return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; + }; + } + function throttle2(fn2, freq) { + let timestamp = 0; + let threshold = 1e3 / freq; + let lastArgs; + let timer; + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn2.apply(null, args); + }; + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if (passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs); + }, threshold - passed); } + } + }; + const flush = () => lastArgs && invoke(lastArgs); + return [throttled, flush]; + } + var progressEventReducer2 = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer2(50, 250); + return throttle2((e) => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : void 0; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange2 = loaded <= total; + bytesNotified = loaded; + const data = { + loaded, + total, + progress: total ? loaded / total : void 0, + bytes: progressBytes, + rate: rate ? rate : void 0, + estimated: rate && total && inRange2 ? (total - loaded) / rate : void 0, + event: e, + lengthComputable: total != null, + [isDownloadStream ? "download" : "upload"]: true }; - this.pins = { - /** - * @description Pins an item to a channel. - * @see {@link https://api.slack.com/methods/pins.add `pins.add` API reference}. - */ - add: bindApiCall(this, "pins.add"), - /** - * @description Lists items pinned to a channel. - * @see {@link https://api.slack.com/methods/pins.list `pins.list` API reference}. - */ - list: bindApiCall(this, "pins.list"), - /** - * @description Un-pins an item from a channel. - * @see {@link https://api.slack.com/methods/pins.remove `pins.remove` API reference}. - */ - remove: bindApiCall(this, "pins.remove") + listener(data); + }, freq); + }; + var progressEventDecorator2 = (total, throttled) => { + const lengthComputable = total != null; + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; + }; + var asyncDecorator2 = (fn2) => (...args) => utils$1.asap(() => fn2(...args)); + var zlibOptions2 = { + flush: zlib__default["default"].constants.Z_SYNC_FLUSH, + finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH + }; + var brotliOptions2 = { + flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH + }; + var isBrotliSupported2 = utils$1.isFunction(zlib__default["default"].createBrotliDecompress); + var { http: httpFollow2, https: httpsFollow2 } = followRedirects__default["default"]; + var isHttps2 = /https:?/; + var supportedProtocols2 = platform.protocols.map((protocol) => { + return protocol + ":"; + }); + var flushOnFinish2 = (stream5, [throttled, flush]) => { + stream5.on("end", flush).on("error", flush); + return throttled; + }; + function dispatchBeforeRedirect2(options, responseDetails) { + if (options.beforeRedirects.proxy) { + options.beforeRedirects.proxy(options); + } + if (options.beforeRedirects.config) { + options.beforeRedirects.config(options, responseDetails); + } + } + function setProxy2(options, configProxy, location) { + let proxy = configProxy; + if (!proxy && proxy !== false) { + const proxyUrl = proxyFromEnv__default["default"].getProxyForUrl(location); + if (proxyUrl) { + proxy = new URL(proxyUrl); + } + } + if (proxy) { + if (proxy.username) { + proxy.auth = (proxy.username || "") + ":" + (proxy.password || ""); + } + if (proxy.auth) { + if (proxy.auth.username || proxy.auth.password) { + proxy.auth = (proxy.auth.username || "") + ":" + (proxy.auth.password || ""); + } + const base64 = Buffer.from(proxy.auth, "utf8").toString("base64"); + options.headers["Proxy-Authorization"] = "Basic " + base64; + } + options.headers.host = options.hostname + (options.port ? ":" + options.port : ""); + const proxyHost = proxy.hostname || proxy.host; + options.hostname = proxyHost; + options.host = proxyHost; + options.port = proxy.port; + options.path = location; + if (proxy.protocol) { + options.protocol = proxy.protocol.includes(":") ? proxy.protocol : `${proxy.protocol}:`; + } + } + options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { + setProxy2(redirectOptions, configProxy, redirectOptions.href); + }; + } + var isHttpAdapterSupported2 = typeof process !== "undefined" && utils$1.kindOf(process) === "process"; + var wrapAsync2 = (asyncExecutor) => { + return new Promise((resolve, reject) => { + let onDone; + let isDone; + const done = (value, isRejected) => { + if (isDone) return; + isDone = true; + onDone && onDone(value, isRejected); }; - this.reactions = { - /** - * @description Adds a reaction to an item. - * @see {@link https://api.slack.com/methods/reactions.add `reactions.add` API reference}. - */ - add: bindApiCall(this, "reactions.add"), - /** - * @description Gets reactions for an item. - * @see {@link https://api.slack.com/methods/reactions.get `reactions.get` API reference}. - */ - get: bindApiCall(this, "reactions.get"), - /** - * @description List reactions made by a user. - * @see {@link https://api.slack.com/methods/reactions.list `reactions.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "reactions.list"), - /** - * @description Removes a reaction from an item. - * @see {@link https://api.slack.com/methods/reactions.remove `reactions.remove` API reference}. - */ - remove: bindApiCall(this, "reactions.remove") + const _resolve = (value) => { + done(value); + resolve(value); }; - this.reminders = { - /** - * @description Creates a reminder. - * @see {@link https://api.slack.com/methods/reminders.add `reminders.add` API reference}. - */ - add: bindApiCall(this, "reminders.add"), - /** - * @description Marks a reminder as complete. - * @see {@link https://api.slack.com/methods/reminders.complete `reminders.complete` API reference}. - */ - complete: bindApiCall(this, "reminders.complete"), - /** - * @description Deletes a reminder. - * @see {@link https://api.slack.com/methods/reminders.delete `reminders.delete` API reference}. - */ - delete: bindApiCall(this, "reminders.delete"), - /** - * @description Gets information about a reminder. - * @see {@link https://api.slack.com/methods/reminders.info `reminders.info` API reference}. - */ - info: bindApiCall(this, "reminders.info"), - /** - * @description Lists all reminders created by or for a given user. - * @see {@link https://api.slack.com/methods/reminders.list `reminders.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "reminders.list") + const _reject = (reason) => { + done(reason, true); + reject(reason); }; - this.rtm = { - /** - * @description Starts a Real Time Messaging session. - * @see {@link https://api.slack.com/methods/rtm.connect `rtm.connect` API reference}. - */ - connect: bindApiCallWithOptionalArgument(this, "rtm.connect"), - /** - * @description Starts a Real Time Messaging session. - * @deprecated Use `rtm.connect` instead. See {@link https://api.slack.com/changelog/2021-10-rtm-start-to-stop our post on retiring `rtm.start`}. - * @see {@link https://api.slack.com/methods/rtm.start `rtm.start` API reference}. - */ - start: bindApiCallWithOptionalArgument(this, "rtm.start") + asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject); + }); + }; + var resolveFamily2 = ({ address, family }) => { + if (!utils$1.isString(address)) { + throw TypeError("address must be a string"); + } + return { + address, + family: family || (address.indexOf(".") < 0 ? 6 : 4) + }; + }; + var buildAddressEntry2 = (address, family) => resolveFamily2(utils$1.isObject(address) ? address : { address, family }); + var httpAdapter2 = isHttpAdapterSupported2 && function httpAdapter3(config3) { + return wrapAsync2(async function dispatchHttpRequest(resolve, reject, onDone) { + let { data, lookup, family } = config3; + const { responseType, responseEncoding } = config3; + const method = config3.method.toUpperCase(); + let isDone; + let rejected = false; + let req; + if (lookup) { + const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]); + lookup = (hostname, opt, cb) => { + _lookup(hostname, opt, (err, arg0, arg1) => { + if (err) { + return cb(err); + } + const addresses = utils$1.isArray(arg0) ? arg0.map((addr) => buildAddressEntry2(addr)) : [buildAddressEntry2(arg0, arg1)]; + opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); + }); + }; + } + const emitter = new events.EventEmitter(); + const onFinished = () => { + if (config3.cancelToken) { + config3.cancelToken.unsubscribe(abort); + } + if (config3.signal) { + config3.signal.removeEventListener("abort", abort); + } + emitter.removeAllListeners(); }; - this.search = { - /** - * @description Searches for messages and files matching a query. - * @see {@link https://api.slack.com/methods/search.all search.all` API reference}. - */ - all: bindApiCall(this, "search.all"), - /** - * @description Searches for files matching a query. - * @see {@link https://api.slack.com/methods/search.files search.files` API reference}. - */ - files: bindApiCall(this, "search.files"), - /** - * @description Searches for messages matching a query. - * @see {@link https://api.slack.com/methods/search.messages search.messages` API reference}. - */ - messages: bindApiCall(this, "search.messages") + onDone((value, isRejected) => { + isDone = true; + if (isRejected) { + rejected = true; + onFinished(); + } + }); + function abort(reason) { + emitter.emit("abort", !reason || reason.type ? new CanceledError3(null, config3, req) : reason); + } + emitter.once("abort", reject); + if (config3.cancelToken || config3.signal) { + config3.cancelToken && config3.cancelToken.subscribe(abort); + if (config3.signal) { + config3.signal.aborted ? abort() : config3.signal.addEventListener("abort", abort); + } + } + const fullPath = buildFullPath2(config3.baseURL, config3.url, config3.allowAbsoluteUrls); + const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : void 0); + const protocol = parsed.protocol || supportedProtocols2[0]; + if (protocol === "data:") { + let convertedData; + if (method !== "GET") { + return settle2(resolve, reject, { + status: 405, + statusText: "method not allowed", + headers: {}, + config: config3 + }); + } + try { + convertedData = fromDataURI2(config3.url, responseType === "blob", { + Blob: config3.env && config3.env.Blob + }); + } catch (err) { + throw AxiosError3.from(err, AxiosError3.ERR_BAD_REQUEST, config3); + } + if (responseType === "text") { + convertedData = convertedData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === "utf8") { + convertedData = utils$1.stripBOM(convertedData); + } + } else if (responseType === "stream") { + convertedData = stream__default["default"].Readable.from(convertedData); + } + return settle2(resolve, reject, { + data: convertedData, + status: 200, + statusText: "OK", + headers: new AxiosHeaders$1(), + config: config3 + }); + } + if (supportedProtocols2.indexOf(protocol) === -1) { + return reject(new AxiosError3( + "Unsupported protocol " + protocol, + AxiosError3.ERR_BAD_REQUEST, + config3 + )); + } + const headers = AxiosHeaders$1.from(config3.headers).normalize(); + headers.set("User-Agent", "axios/" + VERSION3, false); + const { onUploadProgress, onDownloadProgress } = config3; + const maxRate = config3.maxRate; + let maxUploadRate = void 0; + let maxDownloadRate = void 0; + if (utils$1.isSpecCompliantForm(data)) { + const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); + data = formDataToStream$1(data, (formHeaders) => { + headers.set(formHeaders); + }, { + tag: `axios-${VERSION3}-boundary`, + boundary: userBoundary && userBoundary[1] || void 0 + }); + } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) { + headers.set(data.getHeaders()); + if (!headers.hasContentLength()) { + try { + const knownLength = await util__default["default"].promisify(data.getLength).call(data); + Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); + } catch (e) { + } + } + } else if (utils$1.isBlob(data) || utils$1.isFile(data)) { + data.size && headers.setContentType(data.type || "application/octet-stream"); + headers.setContentLength(data.size || 0); + data = stream__default["default"].Readable.from(readBlob$1(data)); + } else if (data && !utils$1.isStream(data)) { + if (Buffer.isBuffer(data)) ; + else if (utils$1.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils$1.isString(data)) { + data = Buffer.from(data, "utf-8"); + } else { + return reject(new AxiosError3( + "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream", + AxiosError3.ERR_BAD_REQUEST, + config3 + )); + } + headers.setContentLength(data.length, false); + if (config3.maxBodyLength > -1 && data.length > config3.maxBodyLength) { + return reject(new AxiosError3( + "Request body larger than maxBodyLength limit", + AxiosError3.ERR_BAD_REQUEST, + config3 + )); + } + } + const contentLength = utils$1.toFiniteNumber(headers.getContentLength()); + if (utils$1.isArray(maxRate)) { + maxUploadRate = maxRate[0]; + maxDownloadRate = maxRate[1]; + } else { + maxUploadRate = maxDownloadRate = maxRate; + } + if (data && (onUploadProgress || maxUploadRate)) { + if (!utils$1.isStream(data)) { + data = stream__default["default"].Readable.from(data, { objectMode: false }); + } + data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ + maxRate: utils$1.toFiniteNumber(maxUploadRate) + })], utils$1.noop); + onUploadProgress && data.on("progress", flushOnFinish2( + data, + progressEventDecorator2( + contentLength, + progressEventReducer2(asyncDecorator2(onUploadProgress), false, 3) + ) + )); + } + let auth = void 0; + if (config3.auth) { + const username = config3.auth.username || ""; + const password = config3.auth.password || ""; + auth = username + ":" + password; + } + if (!auth && parsed.username) { + const urlUsername = parsed.username; + const urlPassword = parsed.password; + auth = urlUsername + ":" + urlPassword; + } + auth && headers.delete("authorization"); + let path; + try { + path = buildURL2( + parsed.pathname + parsed.search, + config3.params, + config3.paramsSerializer + ).replace(/^\?/, ""); + } catch (err) { + const customErr = new Error(err.message); + customErr.config = config3; + customErr.url = config3.url; + customErr.exists = true; + return reject(customErr); + } + headers.set( + "Accept-Encoding", + "gzip, compress, deflate" + (isBrotliSupported2 ? ", br" : ""), + false + ); + const options = { + path, + method, + headers: headers.toJSON(), + agents: { http: config3.httpAgent, https: config3.httpsAgent }, + auth, + protocol, + family, + beforeRedirect: dispatchBeforeRedirect2, + beforeRedirects: {} }; - this.team = { - /** - * @description Gets the access logs for the current team. - * @see {@link https://api.slack.com/methods/team.accessLogs `team.accessLogs` API reference}. - */ - accessLogs: bindApiCallWithOptionalArgument(this, "team.accessLogs"), - /** - * @description Gets billable users information for the current team. - * @see {@link https://api.slack.com/methods/team.billableInfo `team.billableInfo` API reference}. - */ - billableInfo: bindApiCallWithOptionalArgument(this, "team.billableInfo"), - billing: { - /** - * @description Reads a workspace's billing plan information. - * @see {@link https://api.slack.com/methods/team.billing.info `team.billing.info` API reference}. - */ - info: bindApiCall(this, "team.billing.info") - }, - externalTeams: { - /** - * @description Disconnect an external organization. - * @see {@link https://api.slack.com/methods/team.externalTeams.disconnect `team.externalTeams.disconnect` API reference}. - */ - disconnect: bindApiCall(this, "team.externalTeams.disconnect"), - /** - * @description Returns a list of all the external teams connected and details about the connection. - * @see {@link https://api.slack.com/methods/team.externalTeams.list `team.externalTeams.list` API reference}. - */ - list: bindApiCall(this, "team.externalTeams.list") - }, - /** - * @description Gets information about the current team. - * @see {@link https://api.slack.com/methods/team.info `team.info` API reference}. - */ - info: bindApiCallWithOptionalArgument(this, "team.info"), - /** - * @description Gets the integration logs for the current team. - * @see {@link https://api.slack.com/methods/team.integrationLogs `team.integrationLogs` API reference}. - */ - integrationLogs: bindApiCallWithOptionalArgument(this, "team.integrationLogs"), - preferences: { - /** - * @description Retrieve a list of a workspace's team preferences. - * @see {@link https://api.slack.com/methods/team.preferences.list `team.preferences.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "team.preferences.list") - }, - profile: { - /** - * @description Retrieve a team's profile. - * @see {@link https://api.slack.com/methods/team.profile.get `team.profile.get` API reference}. - */ - get: bindApiCallWithOptionalArgument(this, "team.profile.get") + !utils$1.isUndefined(lookup) && (options.lookup = lookup); + if (config3.socketPath) { + options.socketPath = config3.socketPath; + } else { + options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; + options.port = parsed.port; + setProxy2(options, config3.proxy, protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options.path); + } + let transport; + const isHttpsRequest = isHttps2.test(options.protocol); + options.agent = isHttpsRequest ? config3.httpsAgent : config3.httpAgent; + if (config3.transport) { + transport = config3.transport; + } else if (config3.maxRedirects === 0) { + transport = isHttpsRequest ? https__default["default"] : http__default["default"]; + } else { + if (config3.maxRedirects) { + options.maxRedirects = config3.maxRedirects; + } + if (config3.beforeRedirect) { + options.beforeRedirects.config = config3.beforeRedirect; + } + transport = isHttpsRequest ? httpsFollow2 : httpFollow2; + } + if (config3.maxBodyLength > -1) { + options.maxBodyLength = config3.maxBodyLength; + } else { + options.maxBodyLength = Infinity; + } + if (config3.insecureHTTPParser) { + options.insecureHTTPParser = config3.insecureHTTPParser; + } + req = transport.request(options, function handleResponse(res) { + if (req.destroyed) return; + const streams = [res]; + const responseLength = +res.headers["content-length"]; + if (onDownloadProgress || maxDownloadRate) { + const transformStream = new AxiosTransformStream$1({ + maxRate: utils$1.toFiniteNumber(maxDownloadRate) + }); + onDownloadProgress && transformStream.on("progress", flushOnFinish2( + transformStream, + progressEventDecorator2( + responseLength, + progressEventReducer2(asyncDecorator2(onDownloadProgress), true, 3) + ) + )); + streams.push(transformStream); + } + let responseStream = res; + const lastRequest = res.req || req; + if (config3.decompress !== false && res.headers["content-encoding"]) { + if (method === "HEAD" || res.statusCode === 204) { + delete res.headers["content-encoding"]; + } + switch ((res.headers["content-encoding"] || "").toLowerCase()) { + /*eslint default-case:0*/ + case "gzip": + case "x-gzip": + case "compress": + case "x-compress": + streams.push(zlib__default["default"].createUnzip(zlibOptions2)); + delete res.headers["content-encoding"]; + break; + case "deflate": + streams.push(new ZlibHeaderTransformStream$1()); + streams.push(zlib__default["default"].createUnzip(zlibOptions2)); + delete res.headers["content-encoding"]; + break; + case "br": + if (isBrotliSupported2) { + streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions2)); + delete res.headers["content-encoding"]; + } + } + } + responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0]; + const offListeners = stream__default["default"].finished(responseStream, () => { + offListeners(); + onFinished(); + }); + const response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: new AxiosHeaders$1(res.headers), + config: config3, + request: lastRequest + }; + if (responseType === "stream") { + response.data = responseStream; + settle2(resolve, reject, response); + } else { + const responseBuffer = []; + let totalResponseBytes = 0; + responseStream.on("data", function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; + if (config3.maxContentLength > -1 && totalResponseBytes > config3.maxContentLength) { + rejected = true; + responseStream.destroy(); + reject(new AxiosError3( + "maxContentLength size of " + config3.maxContentLength + " exceeded", + AxiosError3.ERR_BAD_RESPONSE, + config3, + lastRequest + )); + } + }); + responseStream.on("aborted", function handlerStreamAborted() { + if (rejected) { + return; + } + const err = new AxiosError3( + "stream has been aborted", + AxiosError3.ERR_BAD_RESPONSE, + config3, + lastRequest + ); + responseStream.destroy(err); + reject(err); + }); + responseStream.on("error", function handleStreamError(err) { + if (req.destroyed) return; + reject(AxiosError3.from(err, null, config3, lastRequest)); + }); + responseStream.on("end", function handleStreamEnd() { + try { + let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (responseType !== "arraybuffer") { + responseData = responseData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === "utf8") { + responseData = utils$1.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + return reject(AxiosError3.from(err, null, config3, response.request, response)); + } + settle2(resolve, reject, response); + }); } - }; - this.tooling = { - tokens: { - /** - * @description Exchanges a refresh token for a new app configuration token. - * @see {@link https://api.slack.com/methods/tooling.tokens.rotate `tooling.tokens.rotate` API reference}. - */ - rotate: bindApiCall(this, "tooling.tokens.rotate") + emitter.once("abort", (err) => { + if (!responseStream.destroyed) { + responseStream.emit("error", err); + responseStream.destroy(); + } + }); + }); + emitter.once("abort", (err) => { + reject(err); + req.destroy(err); + }); + req.on("error", function handleRequestError(err) { + reject(AxiosError3.from(err, null, config3, req)); + }); + req.on("socket", function handleRequestSocket(socket) { + socket.setKeepAlive(true, 1e3 * 60); + }); + if (config3.timeout) { + const timeout = parseInt(config3.timeout, 10); + if (Number.isNaN(timeout)) { + reject(new AxiosError3( + "error trying to parse `config.timeout` to int", + AxiosError3.ERR_BAD_OPTION_VALUE, + config3, + req + )); + return; } - }; - this.usergroups = { - /** - * @description Create a User Group. - * @see {@link https://api.slack.com/methods/usergroups.create `usergroups.create` API reference}. - */ - create: bindApiCall(this, "usergroups.create"), - /** - * @description Disable an existing User Group. - * @see {@link https://api.slack.com/methods/usergroups.disable `usergroups.disable` API reference}. - */ - disable: bindApiCall(this, "usergroups.disable"), - /** - * @description Enable an existing User Group. - * @see {@link https://api.slack.com/methods/usergroups.enable `usergroups.enable` API reference}. - */ - enable: bindApiCall(this, "usergroups.enable"), - /** - * @description List all User Groups for a team. - * @see {@link https://api.slack.com/methods/usergroups.list `usergroups.list` API reference}. - */ - list: bindApiCallWithOptionalArgument(this, "usergroups.list"), - /** - * @description Update an existing User Group. - * @see {@link https://api.slack.com/methods/usergroups.update `usergroups.update` API reference}. - */ - update: bindApiCall(this, "usergroups.update"), - users: { - /** - * @description List all users in a User Group. - * @see {@link https://api.slack.com/methods/usergroups.users.list `usergroups.users.list` API reference}. - */ - list: bindApiCall(this, "usergroups.users.list"), - /** - * @description Update the list of users in a User Group. - * @see {@link https://api.slack.com/methods/usergroups.users.update `usergroups.users.update` API reference}. - */ - update: bindApiCall(this, "usergroups.users.update") + req.setTimeout(timeout, function handleRequestTimeout() { + if (isDone) return; + let timeoutErrorMessage = config3.timeout ? "timeout of " + config3.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = config3.transitional || transitionalDefaults; + if (config3.timeoutErrorMessage) { + timeoutErrorMessage = config3.timeoutErrorMessage; + } + reject(new AxiosError3( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError3.ETIMEDOUT : AxiosError3.ECONNABORTED, + config3, + req + )); + abort(); + }); + } + if (utils$1.isStream(data)) { + let ended = false; + let errored = false; + data.on("end", () => { + ended = true; + }); + data.once("error", (err) => { + errored = true; + req.destroy(err); + }); + data.on("close", () => { + if (!ended && !errored) { + abort(new CanceledError3("Request stream has been aborted", config3, req)); + } + }); + data.pipe(req); + } else { + req.end(data); + } + }); + }; + var isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin3, isMSIE) => (url3) => { + url3 = new URL(url3, platform.origin); + return origin3.protocol === url3.protocol && origin3.host === url3.host && (isMSIE || origin3.port === url3.port); + })( + new URL(platform.origin), + platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) + ) : () => true; + var cookies = platform.hasStandardBrowserEnv ? ( + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + "=" + encodeURIComponent(value)]; + utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); + utils$1.isString(path) && cookie.push("path=" + path); + utils$1.isString(domain) && cookie.push("domain=" + domain); + secure === true && cookie.push("secure"); + document.cookie = cookie.join("; "); + }, + read(name) { + const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)")); + return match ? decodeURIComponent(match[3]) : null; + }, + remove(name) { + this.write(name, "", Date.now() - 864e5); + } + } + ) : ( + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() { + }, + read() { + return null; + }, + remove() { + } + } + ); + var headersToObject2 = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; + function mergeConfig3(config1, config22) { + config22 = config22 || {}; + const config3 = {}; + function getMergedValue(target, source, prop, caseless) { + if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { + return utils$1.merge.call({ caseless }, target, source); + } else if (utils$1.isPlainObject(source)) { + return utils$1.merge({}, source); + } else if (utils$1.isArray(source)) { + return source.slice(); + } + return source; + } + function mergeDeepProperties(a, b2, prop, caseless) { + if (!utils$1.isUndefined(b2)) { + return getMergedValue(a, b2, prop, caseless); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(void 0, a, prop, caseless); + } + } + function valueFromConfig2(a, b2) { + if (!utils$1.isUndefined(b2)) { + return getMergedValue(void 0, b2); + } + } + function defaultToConfig2(a, b2) { + if (!utils$1.isUndefined(b2)) { + return getMergedValue(void 0, b2); + } else if (!utils$1.isUndefined(a)) { + return getMergedValue(void 0, a); + } + } + function mergeDirectKeys(a, b2, prop) { + if (prop in config22) { + return getMergedValue(a, b2); + } else if (prop in config1) { + return getMergedValue(void 0, a); + } + } + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b2, prop) => mergeDeepProperties(headersToObject2(a), headersToObject2(b2), prop, true) + }; + utils$1.forEach(Object.keys(Object.assign({}, config1, config22)), function computeConfigValue(prop) { + const merge3 = mergeMap[prop] || mergeDeepProperties; + const configValue = merge3(config1[prop], config22[prop], prop); + utils$1.isUndefined(configValue) && merge3 !== mergeDirectKeys || (config3[prop] = configValue); + }); + return config3; + } + var resolveConfig = (config3) => { + const newConfig = mergeConfig3({}, config3); + let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; + newConfig.headers = headers = AxiosHeaders$1.from(headers); + newConfig.url = buildURL2(buildFullPath2(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config3.params, config3.paramsSerializer); + if (auth) { + headers.set( + "Authorization", + "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : "")) + ); + } + let contentType; + if (utils$1.isFormData(data)) { + if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(void 0); + } else if ((contentType = headers.getContentType()) !== false) { + const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; + headers.setContentType([type || "multipart/form-data", ...tokens].join("; ")); + } + } + if (platform.hasStandardBrowserEnv) { + withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) { + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); } - }; - this.users = { - /** - * @description List conversations the calling user may access. - * @see {@link https://api.slack.com/methods/users.conversations `users.conversations` API reference}. - */ - conversations: bindApiCall(this, "users.conversations"), - /** - * @description Delete the user profile photo. - * @see {@link https://api.slack.com/methods/users.deletePhoto `users.deletePhoto` API reference}. - */ - deletePhoto: bindApiCall(this, "users.deletePhoto"), - discoverableContacts: { - /** - * @description Lookup an email address to see if someone is on Slack. - * @see {@link https://api.slack.com/methods/users.discoverableContacts.lookup `users.discoverableContacts.lookup` API reference}. - */ - lookup: bindApiCall(this, "users.discoverableContacts.lookup") - }, - /** - * @description Gets user presence information. - * @see {@link https://api.slack.com/methods/users.getPresence `users.getPresence` API reference}. - */ - getPresence: bindApiCall(this, "users.getPresence"), - /** - * @description Get a user's identity. - * @see {@link https://api.slack.com/methods/users.identity `users.identity` API reference}. - */ - identity: bindApiCall(this, "users.identity"), - /** - * @description Gets information about a user. - * @see {@link https://api.slack.com/methods/users.info `users.info` API reference}. - */ - info: bindApiCall(this, "users.info"), - /** - * @description Lists all users in a Slack team. - * @see {@link https://api.slack.com/methods/users.list `users.list` API reference}. - */ - list: bindApiCall(this, "users.list"), - /** - * @description Find a user with an email address. - * @see {@link https://api.slack.com/methods/users.lookupByEmail `users.lookupByEmail` API reference}. - */ - lookupByEmail: bindApiCall(this, "users.lookupByEmail"), - /** - * @description Set the user profile photo. - * @see {@link https://api.slack.com/methods/users.setPhoto `users.setPhoto` API reference}. - */ - setPhoto: bindApiCall(this, "users.setPhoto"), - /** - * @description Manually sets user presence. - * @see {@link https://api.slack.com/methods/users.setPresence `users.setPresence` API reference}. - */ - setPresence: bindApiCall(this, "users.setPresence"), - profile: { - /** - * @description Retrieve a user's profile information, including their custom status. - * @see {@link https://api.slack.com/methods/users.profile.get `users.profile.get` API reference}. - */ - get: bindApiCall(this, "users.profile.get"), - /** - * @description Set a user's profile information, including custom status. - * @see {@link https://api.slack.com/methods/users.profile.set `users.profile.set` API reference}. - */ - set: bindApiCall(this, "users.profile.set") + } + } + return newConfig; + }; + var isXHRAdapterSupported2 = typeof XMLHttpRequest !== "undefined"; + var xhrAdapter = isXHRAdapterSupported2 && function(config3) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig(config3); + let requestData = _config.data; + const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); + let { responseType, onUploadProgress, onDownloadProgress } = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + function done() { + flushUpload && flushUpload(); + flushDownload && flushDownload(); + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + _config.signal && _config.signal.removeEventListener("abort", onCanceled); + } + let request = new XMLHttpRequest(); + request.open(_config.method.toUpperCase(), _config.url, true); + request.timeout = _config.timeout; + function onloadend() { + if (!request) { + return; } + const responseHeaders = AxiosHeaders$1.from( + "getAllResponseHeaders" in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config3, + request + }; + settle2(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + request = null; + } + if ("onloadend" in request) { + request.onloadend = onloadend; + } else { + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { + return; + } + setTimeout(onloadend); + }; + } + request.onabort = function handleAbort() { + if (!request) { + return; + } + reject(new AxiosError3("Request aborted", AxiosError3.ECONNABORTED, config3, request)); + request = null; }; - this.views = { - /** - * @description Open a view for a user. - * @see {@link https://api.slack.com/methods/views.open `views.open` API reference}. - */ - open: bindApiCall(this, "views.open"), - /** - * @description Publish a static view for a user. - * @see {@link https://api.slack.com/methods/views.publish `views.publish` API reference}. - */ - publish: bindApiCall(this, "views.publish"), - /** - * @description Push a view onto the stack of a root view. - * @see {@link https://api.slack.com/methods/views.push `views.push` API reference}. - */ - push: bindApiCall(this, "views.push"), - /** - * @description Update an existing view. - * @see {@link https://api.slack.com/methods/views.update `views.update` API reference}. - */ - update: bindApiCall(this, "views.update") - }; - this.stars = { - /** - * @description Save an item for later. Formerly known as adding a star. - * @deprecated Stars can still be added but they can no longer be viewed or interacted with by end-users. - * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. - * @see {@link https://api.slack.com/methods/stars.add `stars.add` API reference}. - */ - add: bindApiCall(this, "stars.add"), - /** - * @description List a user's saved items, formerly known as stars. - * @deprecated Stars can still be listed but they can no longer be viewed or interacted with by end-users. - * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. - * @see {@link https://api.slack.com/methods/stars.list `stars.list` API reference}. - */ - list: bindApiCall(this, "stars.list"), - /** - * @description Remove a saved item from a user's saved items, formerly known as stars. - * @deprecated Stars can still be removed but they can no longer be viewed or interacted with by end-users. - * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. - * @see {@link https://api.slack.com/methods/stars.remove `stars.remove` API reference}. - */ - remove: bindApiCall(this, "stars.remove") + request.onerror = function handleError() { + reject(new AxiosError3("Network Error", AxiosError3.ERR_NETWORK, config3, request)); + request = null; }; - this.workflows = { - /** - * @description Indicate that an app's step in a workflow completed execution. - * @deprecated Steps from Apps is deprecated. - * We're retiring all Slack app functionality around Steps from Apps in September 2024. - * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. - * @see {@link https://api.slack.com/methods/workflows.stepCompleted `workflows.stepCompleted` API reference}. - */ - stepCompleted: bindApiCall(this, "workflows.stepCompleted"), - /** - * @description Indicate that an app's step in a workflow failed to execute. - * @deprecated Steps from Apps is deprecated. - * We're retiring all Slack app functionality around Steps from Apps in September 2024. - * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. - * @see {@link https://api.slack.com/methods/workflows.stepFailed `workflows.stepFailed` API reference}. - */ - stepFailed: bindApiCall(this, "workflows.stepFailed"), - /** - * @description Update the configuration for a workflow step. - * @deprecated Steps from Apps is deprecated. - * We're retiring all Slack app functionality around Steps from Apps in September 2024. - * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. - * @see {@link https://api.slack.com/methods/workflows.updateStep `workflows.updateStep` API reference}. - */ - updateStep: bindApiCall(this, "workflows.updateStep") + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = _config.transitional || transitionalDefaults; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new AxiosError3( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError3.ETIMEDOUT : AxiosError3.ECONNABORTED, + config3, + request + )); + request = null; }; - if (new.target !== WebClient_1.WebClient && !(new.target.prototype instanceof WebClient_1.WebClient)) { - throw new Error("Attempt to inherit from WebClient methods without inheriting from WebClient"); + requestData === void 0 && requestHeaders.setContentType(null); + if ("setRequestHeader" in request) { + utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + if (!utils$1.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + if (responseType && responseType !== "json") { + request.responseType = _config.responseType; + } + if (onDownloadProgress) { + [downloadThrottled, flushDownload] = progressEventReducer2(onDownloadProgress, true); + request.addEventListener("progress", downloadThrottled); + } + if (onUploadProgress && request.upload) { + [uploadThrottled, flushUpload] = progressEventReducer2(onUploadProgress); + request.upload.addEventListener("progress", uploadThrottled); + request.upload.addEventListener("loadend", flushUpload); + } + if (_config.cancelToken || _config.signal) { + onCanceled = (cancel) => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError3(null, config3, request) : cancel); + request.abort(); + request = null; + }; + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled); + } } - } - }; - exports2.Methods = Methods; - __exportStar(require_dist3(), exports2); - } -}); - -// node_modules/@slack/web-api/dist/retry-policies.js -var require_retry_policies = __commonJS({ - "node_modules/@slack/web-api/dist/retry-policies.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.rapidRetryPolicy = exports2.fiveRetriesInFiveMinutes = exports2.tenRetriesInAboutThirtyMinutes = void 0; - exports2.tenRetriesInAboutThirtyMinutes = { - retries: 10, - factor: 1.96821, - randomize: true + const protocol = parseProtocol2(_config.url); + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError3("Unsupported protocol " + protocol + ":", AxiosError3.ERR_BAD_REQUEST, config3)); + return; + } + request.send(requestData || null); + }); }; - exports2.fiveRetriesInFiveMinutes = { - retries: 5, - factor: 3.86 + var composeSignals2 = (signals, timeout) => { + const { length } = signals = signals ? signals.filter(Boolean) : []; + if (timeout || length) { + let controller = new AbortController(); + let aborted; + const onabort = function(reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof AxiosError3 ? err : new CanceledError3(err instanceof Error ? err.message : err)); + } + }; + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new AxiosError3(`timeout ${timeout} of ms exceeded`, AxiosError3.ETIMEDOUT)); + }, timeout); + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach((signal2) => { + signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort); + }); + signals = null; + } + }; + signals.forEach((signal2) => signal2.addEventListener("abort", onabort)); + const { signal } = controller; + signal.unsubscribe = () => utils$1.asap(unsubscribe); + return signal; + } }; - exports2.rapidRetryPolicy = { - minTimeout: 0, - maxTimeout: 1 + var composeSignals$1 = composeSignals2; + var streamChunk2 = function* (chunk, chunkSize) { + let len = chunk.byteLength; + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + let pos = 0; + let end; + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } }; - var policies = { - tenRetriesInAboutThirtyMinutes: exports2.tenRetriesInAboutThirtyMinutes, - fiveRetriesInFiveMinutes: exports2.fiveRetriesInFiveMinutes, - rapidRetryPolicy: exports2.rapidRetryPolicy + var readBytes2 = async function* (iterable, chunkSize) { + for await (const chunk of readStream2(iterable)) { + yield* streamChunk2(chunk, chunkSize); + } }; - exports2.default = policies; - } -}); - -// node_modules/@slack/web-api/dist/WebClient.js -var require_WebClient = __commonJS({ - "node_modules/@slack/web-api/dist/WebClient.js"(exports2) { - "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m2, k2); - if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m2[k2]; - } }; + var readStream2 = async function* (stream5) { + if (stream5[Symbol.asyncIterator]) { + yield* stream5; + return; } - Object.defineProperty(o, k22, desc); - } : function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - o[k22] = m2[k2]; - }); - var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - } : function(o, v) { - o["default"] = v; - }); - var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar2 = []; - for (var k2 in o2) if (Object.prototype.hasOwnProperty.call(o2, k2)) ar2[ar2.length] = k2; - return ar2; - }; - return ownKeys(o); - }; - return function(mod2) { - if (mod2 && mod2.__esModule) return mod2; - var result = {}; - if (mod2 != null) { - for (var k2 = ownKeys(mod2), i = 0; i < k2.length; i++) if (k2[i] !== "default") __createBinding(result, mod2, k2[i]); + const reader = stream5.getReader(); + try { + for (; ; ) { + const { done, value } = await reader.read(); + if (done) { + break; + } + yield value; } - __setModuleDefault(result, mod2); - return result; - }; - }(); - var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { - function adopt(value) { - return value instanceof P2 ? value : new P2(function(resolve) { - resolve(value); - }); + } finally { + await reader.cancel(); } - return new (P2 || (P2 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + }; + var trackStream2 = (stream5, chunkSize, onProgress, onFinish) => { + const iterator3 = readBytes2(stream5, chunkSize); + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); } - function rejected(value) { + }; + return new ReadableStream({ + async pull(controller) { try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + const { done: done2, value } = await iterator3.next(); + if (done2) { + _onFinish(); + controller.close(); + return; + } + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); + } catch (err) { + _onFinish(err); + throw err; } + }, + cancel(reason) { + _onFinish(reason); + return iterator3.return(); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + }, { + highWaterMark: 2 }); }; - var __await = exports2 && exports2.__await || function(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); + var isFetchSupported2 = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function"; + var isReadableStreamSupported2 = isFetchSupported2 && typeof ReadableStream === "function"; + var encodeText2 = isFetchSupported2 && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder5) => (str) => encoder5.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Response(str).arrayBuffer())); + var test2 = (fn2, ...args) => { + try { + return !!fn2(...args); + } catch (e) { + return false; + } }; - var __asyncGenerator = exports2 && exports2.__asyncGenerator || function(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q2 = []; - return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function awaitReturn(f) { - return function(v) { - return Promise.resolve(v).then(f, reject); - }; + var supportsRequestStream2 = isReadableStreamSupported2 && test2(() => { + let duplexAccessed = false; + const hasContentType = new Request(platform.origin, { + body: new ReadableStream(), + method: "POST", + get duplex() { + duplexAccessed = true; + return "half"; + } + }).headers.has("Content-Type"); + return duplexAccessed && !hasContentType; + }); + var DEFAULT_CHUNK_SIZE2 = 64 * 1024; + var supportsResponseStream2 = isReadableStreamSupported2 && test2(() => utils$1.isReadableStream(new Response("").body)); + var resolvers2 = { + stream: supportsResponseStream2 && ((res) => res.body) + }; + isFetchSupported2 && ((res) => { + ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => { + !resolvers2[type] && (resolvers2[type] = utils$1.isFunction(res[type]) ? (res2) => res2[type]() : (_, config3) => { + throw new AxiosError3(`Response type '${type}' is not supported`, AxiosError3.ERR_NOT_SUPPORT, config3); + }); + }); + })(new Response()); + var getBodyLength2 = async (body) => { + if (body == null) { + return 0; } - function verb(n, f) { - if (g[n]) { - i[n] = function(v) { - return new Promise(function(a, b2) { - q2.push([n, v, a, b2]) > 1 || resume(n, v); - }); - }; - if (f) i[n] = f(i[n]); + if (utils$1.isBlob(body)) { + return body.size; + } + if (utils$1.isSpecCompliantForm(body)) { + const _request = new Request(platform.origin, { + method: "POST", + body + }); + return (await _request.arrayBuffer()).byteLength; + } + if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { + return body.byteLength; + } + if (utils$1.isURLSearchParams(body)) { + body = body + ""; + } + if (utils$1.isString(body)) { + return (await encodeText2(body)).byteLength; + } + }; + var resolveBodyLength2 = async (headers, body) => { + const length = utils$1.toFiniteNumber(headers.getContentLength()); + return length == null ? getBodyLength2(body) : length; + }; + var fetchAdapter = isFetchSupported2 && (async (config3) => { + let { + url: url3, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = "same-origin", + fetchOptions + } = resolveConfig(config3); + responseType = responseType ? (responseType + "").toLowerCase() : "text"; + let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + let request; + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + let requestContentLength; + try { + if (onUploadProgress && supportsRequestStream2 && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength2(headers, data)) !== 0) { + let _request = new Request(url3, { + method: "POST", + body: data, + duplex: "half" + }); + let contentTypeHeader; + if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) { + headers.setContentType(contentTypeHeader); + } + if (_request.body) { + const [onProgress, flush] = progressEventDecorator2( + requestContentLength, + progressEventReducer2(asyncDecorator2(onUploadProgress)) + ); + data = trackStream2(_request.body, DEFAULT_CHUNK_SIZE2, onProgress, flush); + } + } + if (!utils$1.isString(withCredentials)) { + withCredentials = withCredentials ? "include" : "omit"; } + const isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url3, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : void 0 + }); + let response = await fetch(request); + const isStreamResponse = supportsResponseStream2 && (responseType === "stream" || responseType === "response"); + if (supportsResponseStream2 && (onDownloadProgress || isStreamResponse && unsubscribe)) { + const options = {}; + ["status", "statusText", "headers"].forEach((prop) => { + options[prop] = response[prop]; + }); + const responseContentLength = utils$1.toFiniteNumber(response.headers.get("content-length")); + const [onProgress, flush] = onDownloadProgress && progressEventDecorator2( + responseContentLength, + progressEventReducer2(asyncDecorator2(onDownloadProgress), true) + ) || []; + response = new Response( + trackStream2(response.body, DEFAULT_CHUNK_SIZE2, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + responseType = responseType || "text"; + let responseData = await resolvers2[utils$1.findKey(resolvers2, responseType) || "text"](response, config3); + !isStreamResponse && unsubscribe && unsubscribe(); + return await new Promise((resolve, reject) => { + settle2(resolve, reject, { + data: responseData, + headers: AxiosHeaders$1.from(response.headers), + status: response.status, + statusText: response.statusText, + config: config3, + request + }); + }); + } catch (err) { + unsubscribe && unsubscribe(); + if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError3("Network Error", AxiosError3.ERR_NETWORK, config3, request), + { + cause: err.cause || err + } + ); + } + throw AxiosError3.from(err, err && err.code, config3, request); } - function resume(n, v) { + }); + var knownAdapters2 = { + http: httpAdapter2, + xhr: xhrAdapter, + fetch: fetchAdapter + }; + utils$1.forEach(knownAdapters2, (fn2, value) => { + if (fn2) { try { - step(g[n](v)); + Object.defineProperty(fn2, "name", { value }); } catch (e) { - settle2(q2[0][3], e); } + Object.defineProperty(fn2, "adapterName", { value }); } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle2(q2[0][2], r); + }); + var renderReason2 = (reason) => `- ${reason}`; + var isResolvedHandle2 = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; + var adapters = { + getAdapter: (adapters2) => { + adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2]; + const { length } = adapters2; + let nameOrAdapter; + let adapter; + const rejectedReasons = {}; + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters2[i]; + let id2; + adapter = nameOrAdapter; + if (!isResolvedHandle2(nameOrAdapter)) { + adapter = knownAdapters2[(id2 = String(nameOrAdapter)).toLowerCase()]; + if (adapter === void 0) { + throw new AxiosError3(`Unknown adapter '${id2}'`); + } + } + if (adapter) { + break; + } + rejectedReasons[id2 || "#" + i] = adapter; + } + if (!adapter) { + const reasons = Object.entries(rejectedReasons).map( + ([id2, state]) => `adapter ${id2} ` + (state === false ? "is not supported by the environment" : "is not available in the build") + ); + let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason2).join("\n") : " " + renderReason2(reasons[0]) : "as no adapter specified"; + throw new AxiosError3( + `There is no suitable adapter to dispatch the request ` + s, + "ERR_NOT_SUPPORT" + ); + } + return adapter; + }, + adapters: knownAdapters2 + }; + function throwIfCancellationRequested2(config3) { + if (config3.cancelToken) { + config3.cancelToken.throwIfRequested(); } - function fulfill(value) { - resume("next", value); + if (config3.signal && config3.signal.aborted) { + throw new CanceledError3(null, config3); } - function reject(value) { - resume("throw", value); + } + function dispatchRequest2(config3) { + throwIfCancellationRequested2(config3); + config3.headers = AxiosHeaders$1.from(config3.headers); + config3.data = transformData2.call( + config3, + config3.transformRequest + ); + if (["post", "put", "patch"].indexOf(config3.method) !== -1) { + config3.headers.setContentType("application/x-www-form-urlencoded", false); + } + const adapter = adapters.getAdapter(config3.adapter || defaults$1.adapter); + return adapter(config3).then(function onAdapterResolution(response) { + throwIfCancellationRequested2(config3); + response.data = transformData2.call( + config3, + config3.transformResponse, + response + ); + response.headers = AxiosHeaders$1.from(response.headers); + return response; + }, function onAdapterRejection(reason) { + if (!isCancel3(reason)) { + throwIfCancellationRequested2(config3); + if (reason && reason.response) { + reason.response.data = transformData2.call( + config3, + config3.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + } + } + return Promise.reject(reason); + }); + } + var validators$1 = {}; + ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => { + validators$1[type] = function validator2(thing) { + return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type; + }; + }); + var deprecatedWarnings2 = {}; + validators$1.transitional = function transitional2(validator2, version4, message) { + function formatMessage(opt, desc) { + return "[Axios v" + VERSION3 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); + } + return (value, opt, opts) => { + if (validator2 === false) { + throw new AxiosError3( + formatMessage(opt, " has been removed" + (version4 ? " in " + version4 : "")), + AxiosError3.ERR_DEPRECATED + ); + } + if (version4 && !deprecatedWarnings2[opt]) { + deprecatedWarnings2[opt] = true; + console.warn( + formatMessage( + opt, + " has been deprecated since v" + version4 + " and will be removed in the near future" + ) + ); + } + return validator2 ? validator2(value, opt, opts) : true; + }; + }; + validators$1.spelling = function spelling2(correctSpelling) { + return (value, opt) => { + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + }; + }; + function assertOptions2(options, schema, allowUnknown) { + if (typeof options !== "object") { + throw new AxiosError3("options must be an object", AxiosError3.ERR_BAD_OPTION_VALUE); } - function settle2(f, v) { - if (f(v), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]); + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator2 = schema[opt]; + if (validator2) { + const value = options[opt]; + const result = value === void 0 || validator2(value, opt, options); + if (result !== true) { + throw new AxiosError3("option " + opt + " must be " + result, AxiosError3.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError3("Unknown option " + opt, AxiosError3.ERR_BAD_OPTION); + } } + } + var validator = { + assertOptions: assertOptions2, + validators: validators$1 }; - var __asyncValues = exports2 && exports2.__asyncValues || function(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m2 = o[Symbol.asyncIterator], i; - return m2 ? m2.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve, reject) { - v = o[n](v), settle2(resolve, reject, v.done, v.value); - }); + var validators3 = validator.validators; + var Axios3 = class { + constructor(instanceConfig) { + this.defaults = instanceConfig || {}; + this.interceptors = { + request: new InterceptorManager$1(), + response: new InterceptorManager$1() }; } - function settle2(resolve, reject, d, v) { - Promise.resolve(v).then(function(v2) { - resolve({ value: v2, done: d }); - }, reject); - } - }; - var __importDefault = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; - }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.WebClient = exports2.WebClientEvent = void 0; - exports2.buildThreadTsWarningMessage = buildThreadTsWarningMessage; - var node_path_1 = __require("node:path"); - var node_querystring_1 = __require("node:querystring"); - var node_util_1 = __require("node:util"); - var node_zlib_1 = __importDefault(__require("node:zlib")); - var axios_1 = __importDefault(require_axios()); - var form_data_1 = __importDefault(require_form_data()); - var is_electron_1 = __importDefault(require_is_electron()); - var is_stream_1 = __importDefault(require_is_stream()); - var p_queue_1 = __importDefault(require_dist()); - var p_retry_1 = __importStar(require_p_retry()); - var errors_1 = require_errors3(); - var file_upload_1 = require_file_upload(); - var helpers_1 = __importDefault(require_helpers()); - var instrument_1 = require_instrument(); - var logger_1 = require_logger2(); - var methods_1 = require_methods(); - var retry_policies_1 = require_retry_policies(); - var axiosHeaderPropsToIgnore = [ - "delete", - "common", - "get", - "put", - "head", - "post", - "link", - "patch", - "purge", - "unlink", - "options" - ]; - var defaultFilename = "Untitled"; - var defaultPageSize = 200; - var noopPageReducer = () => void 0; - var WebClientEvent; - (function(WebClientEvent2) { - WebClientEvent2["RATE_LIMITED"] = "rate_limited"; - })(WebClientEvent || (exports2.WebClientEvent = WebClientEvent = {})); - var WebClient2 = class _WebClient extends methods_1.Methods { /** - * @param token - An API token to authenticate/authorize with Slack (usually start with `xoxp`, `xoxb`) - * @param {Object} [webClientOptions] - Configuration options. - * @param {Function} [webClientOptions.requestInterceptor] - An interceptor to mutate outgoing requests. See {@link https://axios-http.com/docs/interceptors Axios interceptors} - * @param {Function} [webClientOptions.adapter] - An adapter to allow custom handling of requests. Useful if you would like to use a pre-configured http client. See {@link https://github.com/axios/axios/blob/v1.x/README.md?plain=1#L586 Axios adapter} + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled */ - constructor(token, { slackApiUrl = "https://slack.com/api/", logger = void 0, logLevel = void 0, maxRequestConcurrency = 100, retryConfig = retry_policies_1.tenRetriesInAboutThirtyMinutes, agent = void 0, tls = void 0, timeout = 0, rejectRateLimitedCalls = false, headers = {}, teamId = void 0, allowAbsoluteUrls = true, attachOriginalToWebAPIRequestError = true, requestInterceptor = void 0, adapter = void 0 } = {}) { - super(); - this.token = token; - this.slackApiUrl = slackApiUrl; - if (!this.slackApiUrl.endsWith("/")) { - this.slackApiUrl += "/"; - } - this.retryConfig = retryConfig; - this.requestQueue = new p_queue_1.default({ concurrency: maxRequestConcurrency }); - this.tlsConfig = tls !== void 0 ? tls : {}; - this.rejectRateLimitedCalls = rejectRateLimitedCalls; - this.teamId = teamId; - this.allowAbsoluteUrls = allowAbsoluteUrls; - this.attachOriginalToWebAPIRequestError = attachOriginalToWebAPIRequestError; - if (typeof logger !== "undefined") { - this.logger = logger; - if (typeof logLevel !== "undefined") { - this.logger.debug("The logLevel given to WebClient was ignored as you also gave logger"); + async request(configOrUrl, config3) { + try { + return await this._request(configOrUrl, config3); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error(); + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; + try { + if (!err.stack) { + err.stack = stack; + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { + err.stack += "\n" + stack; + } + } catch (e) { + } } + throw err; + } + } + _request(configOrUrl, config3) { + if (typeof configOrUrl === "string") { + config3 = config3 || {}; + config3.url = configOrUrl; } else { - this.logger = (0, logger_1.getLogger)(_WebClient.loggerName, logLevel !== null && logLevel !== void 0 ? logLevel : logger_1.LogLevel.INFO, logger); + config3 = configOrUrl || {}; } - if (this.token && !headers.Authorization) - headers.Authorization = `Bearer ${this.token}`; - this.axios = axios_1.default.create({ - adapter: adapter ? (config3) => adapter(Object.assign(Object.assign({}, config3), { adapter: void 0 })) : void 0, - timeout, - baseURL: this.slackApiUrl, - headers: (0, is_electron_1.default)() ? headers : Object.assign({ "User-Agent": (0, instrument_1.getUserAgent)() }, headers), - httpAgent: agent, - httpsAgent: agent, - validateStatus: () => true, - // all HTTP status codes should result in a resolved promise (as opposed to only 2xx) - maxRedirects: 0, - // disabling axios' automatic proxy support: - // axios would read from envvars to configure a proxy automatically, but it doesn't support TLS destinations. - // for compatibility with https://api.slack.com, and for a larger set of possible proxies (SOCKS or other - // protocols), users of this package should use the `agent` option to configure a proxy. - proxy: false - }); - this.axios.defaults.headers.post["Content-Type"] = void 0; - if (requestInterceptor) { - this.axios.interceptors.request.use(requestInterceptor, null); + config3 = mergeConfig3(this.defaults, config3); + const { transitional: transitional2, paramsSerializer, headers } = config3; + if (transitional2 !== void 0) { + validator.assertOptions(transitional2, { + silentJSONParsing: validators3.transitional(validators3.boolean), + forcedJSONParsing: validators3.transitional(validators3.boolean), + clarifyTimeoutError: validators3.transitional(validators3.boolean) + }, false); } - this.axios.interceptors.request.use(this.serializeApiCallData.bind(this), null); - this.logger.debug("initialized"); - } - /** - * Generic method for calling a Web API method - * @param method - the Web API method to call {@link https://api.slack.com/methods} - * @param options - options - */ - apiCall(method_1) { - return __awaiter(this, arguments, void 0, function* (method, options = {}) { - this.logger.debug(`apiCall('${method}') start`); - warnDeprecations(method, this.logger); - warnIfFallbackIsMissing(method, this.logger, options); - warnIfThreadTsIsNotString(method, this.logger, options); - if (typeof options === "string" || typeof options === "number" || typeof options === "boolean") { - throw new TypeError(`Expected an options argument but instead received a ${typeof options}`); - } - (0, file_upload_1.warnIfNotUsingFilesUploadV2)(method, this.logger); - if (method === "files.uploadV2") - return this.filesUploadV2(options); - const headers = {}; - if (options.token) - headers.Authorization = `Bearer ${options.token}`; - const url2 = this.deriveRequestUrl(method); - const response = yield this.makeRequest(url2, Object.assign({ team_id: this.teamId }, options), headers); - const result = yield this.buildResult(response); - this.logger.debug(`http request result: ${JSON.stringify(result)}`); - if (result.response_metadata !== void 0 && result.response_metadata.warnings !== void 0) { - result.response_metadata.warnings.forEach(this.logger.warn.bind(this.logger)); - } - if (result.response_metadata !== void 0 && result.response_metadata.messages !== void 0) { - for (const msg of result.response_metadata.messages) { - const errReg = /\[ERROR\](.*)/; - const warnReg = /\[WARN\](.*)/; - if (errReg.test(msg)) { - const errMatch = msg.match(errReg); - if (errMatch != null) { - this.logger.error(errMatch[1].trim()); - } - } else if (warnReg.test(msg)) { - const warnMatch = msg.match(warnReg); - if (warnMatch != null) { - this.logger.warn(warnMatch[1].trim()); - } - } - } + if (paramsSerializer != null) { + if (utils$1.isFunction(paramsSerializer)) { + config3.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions(paramsSerializer, { + encode: validators3.function, + serialize: validators3.function + }, true); } - if (!result.ok && response.headers["content-type"] !== "application/gzip") { - throw (0, errors_1.platformErrorFromResult)(result); + } + if (config3.allowAbsoluteUrls !== void 0) ; + else if (this.defaults.allowAbsoluteUrls !== void 0) { + config3.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; + } else { + config3.allowAbsoluteUrls = true; + } + validator.assertOptions(config3, { + baseUrl: validators3.spelling("baseURL"), + withXsrfToken: validators3.spelling("withXSRFToken") + }, true); + config3.method = (config3.method || this.defaults.method || "get").toLowerCase(); + let contextHeaders = headers && utils$1.merge( + headers.common, + headers[config3.method] + ); + headers && utils$1.forEach( + ["delete", "get", "head", "post", "put", "patch", "common"], + (method) => { + delete headers[method]; } - if ("ok" in result && result.ok === false) { - throw (0, errors_1.platformErrorFromResult)(result); + ); + config3.headers = AxiosHeaders$1.concat(contextHeaders, headers); + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config3) === false) { + return; } - this.logger.debug(`apiCall('${method}') end`); - return result; + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); }); - } - paginate(method, options, shouldStop, reduce) { - const pageSize = (() => { - if (options !== void 0 && typeof options.limit === "number") { - const { limit } = options; - options.limit = void 0; - return limit; + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + let promise; + let i = 0; + let len; + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest2.bind(this), void 0]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + promise = Promise.resolve(config3); + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); } - return defaultPageSize; - })(); - function generatePages() { - return __asyncGenerator(this, arguments, function* generatePages_1() { - let result; - let paginationOptions = { - limit: pageSize - }; - if (options !== void 0 && options.cursor !== void 0) { - paginationOptions.cursor = options.cursor; - } - while (result === void 0 || paginationOptions !== void 0) { - result = yield __await(this.apiCall(method, Object.assign(options !== void 0 ? options : {}, paginationOptions))); - yield yield __await(result); - paginationOptions = paginationOptionsForNextPage(result, pageSize); - } - }); - } - if (shouldStop === void 0) { - return generatePages.call(this); + return promise; } - const pageReducer = reduce !== void 0 ? reduce : noopPageReducer; - let index2 = 0; - return (() => __awaiter(this, void 0, void 0, function* () { - var _a2, e_1, _b, _c2; - const pageIterator = generatePages.call(this); - const firstIteratorResult = yield pageIterator.next(void 0); - const firstPage = firstIteratorResult.value; - let accumulator = pageReducer(void 0, firstPage, index2); - index2 += 1; - if (shouldStop(firstPage)) { - return accumulator; - } + len = requestInterceptorChain.length; + let newConfig = config3; + i = 0; + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; try { - for (var _d2 = true, pageIterator_1 = __asyncValues(pageIterator), pageIterator_1_1; pageIterator_1_1 = yield pageIterator_1.next(), _a2 = pageIterator_1_1.done, !_a2; _d2 = true) { - _c2 = pageIterator_1_1.value; - _d2 = false; - const page = _c2; - accumulator = pageReducer(accumulator, page, index2); - if (shouldStop(page)) { - return accumulator; - } - index2 += 1; - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (!_d2 && !_a2 && (_b = pageIterator_1.return)) yield _b.call(pageIterator_1); - } finally { - if (e_1) throw e_1.error; - } + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; } - return accumulator; - }))(); + } + try { + promise = dispatchRequest2.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + i = 0; + len = responseInterceptorChain.length; + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + return promise; } - /** - * This wrapper method provides an easy way to upload files using the following endpoints: - * - * **#1**: For each file submitted with this method, submit filenames - * and file metadata to {@link https://api.slack.com/methods/files.getUploadURLExternal files.getUploadURLExternal} to request a URL to - * which to send the file data to and an id for the file - * - * **#2**: for each returned file `upload_url`, upload corresponding file to - * URLs returned from step 1 (e.g. https://files.slack.com/upload/v1/...\") - * - * **#3**: Complete uploads {@link https://api.slack.com/methods/files.completeUploadExternal files.completeUploadExternal} - * @param options - */ - filesUploadV2(options) { - return __awaiter(this, void 0, void 0, function* () { - this.logger.debug("files.uploadV2() start"); - const fileUploads = yield this.getAllFileUploads(options); - const fileUploadsURLRes = yield this.fetchAllUploadURLExternal(fileUploads); - fileUploadsURLRes.forEach((res, idx) => { - fileUploads[idx].upload_url = res.upload_url; - fileUploads[idx].file_id = res.file_id; - }); - yield this.postFileUploadsToExternalURL(fileUploads, options); - const completion = yield this.completeFileUploads(fileUploads); - return { ok: true, files: completion }; - }); + getUri(config3) { + config3 = mergeConfig3(this.defaults, config3); + const fullPath = buildFullPath2(config3.baseURL, config3.url, config3.allowAbsoluteUrls); + return buildURL2(fullPath, config3.params, config3.paramsSerializer); } - /** - * For each file submitted with this method, submits filenames - * and file metadata to files.getUploadURLExternal to request a URL to - * which to send the file data to and an id for the file - * @param fileUploads - */ - fetchAllUploadURLExternal(fileUploads) { - return __awaiter(this, void 0, void 0, function* () { - return Promise.all(fileUploads.map((upload) => { - const options = { - filename: upload.filename, - length: upload.length, - alt_text: upload.alt_text, - snippet_type: upload.snippet_type - }; - if ("token" in upload) { - options.token = upload.token; - } - return this.files.getUploadURLExternal(options); + }; + utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData2(method) { + Axios3.prototype[method] = function(url3, config3) { + return this.request(mergeConfig3(config3 || {}, { + method, + url: url3, + data: (config3 || {}).data + })); + }; + }); + utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData2(method) { + function generateHTTPMethod(isForm) { + return function httpMethod(url3, data, config3) { + return this.request(mergeConfig3(config3 || {}, { + method, + headers: isForm ? { + "Content-Type": "multipart/form-data" + } : {}, + url: url3, + data })); - }); - } - /** - * Complete uploads. - * @param fileUploads - * @returns - */ - completeFileUploads(fileUploads) { - return __awaiter(this, void 0, void 0, function* () { - const toComplete = Object.values((0, file_upload_1.getAllFileUploadsToComplete)(fileUploads)); - return Promise.all(toComplete.map((job) => this.files.completeUploadExternal(job))); - }); + }; } - /** - * for each returned file upload URL, upload corresponding file - * @param fileUploads - * @returns - */ - postFileUploadsToExternalURL(fileUploads, options) { - return __awaiter(this, void 0, void 0, function* () { - return Promise.all(fileUploads.map((upload) => __awaiter(this, void 0, void 0, function* () { - const { upload_url, file_id, filename, data } = upload; - const body = data; - if (upload_url) { - const headers = {}; - if (options.token) - headers.Authorization = `Bearer ${options.token}`; - const uploadRes = yield this.makeRequest(upload_url, { - body - }, headers); - if (uploadRes.status !== 200) { - return Promise.reject(Error(`Failed to upload file (id:${file_id}, filename: ${filename})`)); - } - const returnData = { ok: true, body: uploadRes.data }; - return Promise.resolve(returnData); - } - return Promise.reject(Error(`No upload url found for file (id: ${file_id}, filename: ${filename}`)); - }))); + Axios3.prototype[method] = generateHTTPMethod(); + Axios3.prototype[method + "Form"] = generateHTTPMethod(true); + }); + var Axios$1 = Axios3; + var CancelToken3 = class _CancelToken { + constructor(executor) { + if (typeof executor !== "function") { + throw new TypeError("executor must be a function."); + } + let resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; }); - } - /** - * @param options All file uploads arguments - * @returns An array of file upload entries - */ - getAllFileUploads(options) { - return __awaiter(this, void 0, void 0, function* () { - let fileUploads = []; - if ("file" in options || "content" in options) { - fileUploads.push(yield (0, file_upload_1.getFileUploadJob)(options, this.logger)); + const token = this; + this.promise.then((cancel) => { + if (!token._listeners) return; + let i = token._listeners.length; + while (i-- > 0) { + token._listeners[i](cancel); } - if ("file_uploads" in options) { - fileUploads = fileUploads.concat(yield (0, file_upload_1.getMultipleFileUploadJobs)(options, this.logger)); + token._listeners = null; + }); + this.promise.then = (onfulfilled) => { + let _resolve; + const promise = new Promise((resolve) => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + return promise; + }; + executor(function cancel(message, config3, request) { + if (token.reason) { + return; } - return fileUploads; + token.reason = new CanceledError3(message, config3, request); + resolvePromise(token.reason); }); } /** - * Low-level function to make a single API request. handles queuing, retries, and http-level errors + * Throws a `CanceledError` if cancellation has been requested. */ - makeRequest(url_1, body_1) { - return __awaiter(this, arguments, void 0, function* (url2, body, headers = {}) { - const task = () => this.requestQueue.add(() => __awaiter(this, void 0, void 0, function* () { - try { - const config3 = Object.assign({ headers }, this.tlsConfig); - if (url2.endsWith("admin.analytics.getFile")) { - config3.responseType = "arraybuffer"; - } - if (url2.endsWith("apps.event.authorizations.list")) { - body.token = void 0; - } - this.logger.debug(`http request url: ${url2}`); - this.logger.debug(`http request body: ${JSON.stringify(redact(body))}`); - let allHeaders = Object.keys(this.axios.defaults.headers).reduce((acc, cur) => { - if (!axiosHeaderPropsToIgnore.includes(cur)) { - acc[cur] = this.axios.defaults.headers[cur]; - } - return acc; - }, {}); - allHeaders = Object.assign(Object.assign(Object.assign({}, this.axios.defaults.headers.common), allHeaders), headers); - this.logger.debug(`http request headers: ${JSON.stringify(redact(allHeaders))}`); - const response = yield this.axios.post(url2, body, config3); - this.logger.debug("http response received"); - if (response.status === 429) { - const retrySec = parseRetryHeaders(response); - if (retrySec !== void 0) { - this.emit(WebClientEvent.RATE_LIMITED, retrySec, { url: url2, body }); - if (this.rejectRateLimitedCalls) { - throw new p_retry_1.AbortError((0, errors_1.rateLimitedErrorWithDelay)(retrySec)); - } - this.logger.info(`API Call failed due to rate limiting. Will retry in ${retrySec} seconds.`); - this.requestQueue.pause(); - yield (0, helpers_1.default)(retrySec * 1e3); - this.requestQueue.start(); - throw new Error(`A rate limit was exceeded (url: ${url2}, retry-after: ${retrySec})`); - } - throw new p_retry_1.AbortError(new Error(`Retry header did not contain a valid timeout (url: ${url2}, retry-after header: ${response.headers["retry-after"]})`)); - } - if (response.status !== 200) { - throw (0, errors_1.httpErrorFromResponse)(response); - } - return response; - } catch (error) { - const e = error; - this.logger.warn("http request failed", e.message); - if (e.request) { - throw (0, errors_1.requestErrorWithOriginal)(e, this.attachOriginalToWebAPIRequestError); - } - throw error; - } - })); - return (0, p_retry_1.default)(task, this.retryConfig); - }); + throwIfRequested() { + if (this.reason) { + throw this.reason; + } } /** - * Get the complete request URL for the provided URL. - * @param url - The resource to POST to. Either a Slack API method or absolute URL. + * Subscribe to the cancel signal */ - deriveRequestUrl(url2) { - const isAbsoluteURL2 = url2.startsWith("https://") || url2.startsWith("http://"); - if (isAbsoluteURL2 && this.allowAbsoluteUrls) { - return url2; + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; } - return `${this.axios.getUri() + url2}`; } /** - * Transforms options (a simple key-value object) into an acceptable value for a body. This can be either - * a string, used when posting with a content-type of url-encoded. Or, it can be a readable stream, used - * when the options contain a binary (a stream or a buffer) and the upload should be done with content-type - * multipart/form-data. - * @param config - The Axios request configuration object + * Unsubscribe from the cancel signal */ - serializeApiCallData(config3) { - const { data, headers } = config3; - let containsBinaryData = false; - const flattened = Object.entries(data).map(([key, value]) => { - if (value === void 0 || value === null) { - return []; - } - let serializedValue = value; - if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { - containsBinaryData = true; - } else if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") { - serializedValue = JSON.stringify(value); - } - return [key, serializedValue]; - }); - if (containsBinaryData) { - this.logger.debug("Request arguments contain binary data"); - const form = flattened.reduce((frm, [key, value]) => { - if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { - const opts = {}; - opts.filename = (() => { - const streamOrBuffer = value; - if (typeof streamOrBuffer.name === "string") { - return (0, node_path_1.basename)(streamOrBuffer.name); - } - if (typeof streamOrBuffer.path === "string") { - return (0, node_path_1.basename)(streamOrBuffer.path); - } - return defaultFilename; - })(); - frm.append(key, value, opts); - } else if (key !== void 0 && value !== void 0) { - frm.append(key, value); - } - return frm; - }, new form_data_1.default()); - if (headers) { - for (const [header, value] of Object.entries(form.getHeaders())) { - headers[header] = value; - } - } - config3.data = form; - config3.headers = headers; - return config3; + unsubscribe(listener) { + if (!this._listeners) { + return; } - if (headers) - headers["Content-Type"] = "application/x-www-form-urlencoded"; - const initialValue = {}; - config3.data = (0, node_querystring_1.stringify)(flattened.reduce((accumulator, [key, value]) => { - if (key !== void 0 && value !== void 0) { - accumulator[key] = value; - } - return accumulator; - }, initialValue)); - config3.headers = headers; - return config3; + const index2 = this._listeners.indexOf(listener); + if (index2 !== -1) { + this._listeners.splice(index2, 1); + } + } + toAbortSignal() { + const controller = new AbortController(); + const abort = (err) => { + controller.abort(err); + }; + this.subscribe(abort); + controller.signal.unsubscribe = () => this.unsubscribe(abort); + return controller.signal; } /** - * Processes an HTTP response into a WebAPICallResult by performing JSON parsing on the body and merging relevant - * HTTP headers into the object. - * @param response - an http response + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. */ - buildResult(response) { - return __awaiter(this, void 0, void 0, function* () { - let { data } = response; - const isGzipResponse = response.headers["content-type"] === "application/gzip"; - if (isGzipResponse) { - try { - const unzippedData = yield new Promise((resolve, reject) => { - node_zlib_1.default.unzip(data, (err, buf) => { - if (err) { - return reject(err); - } - return resolve(buf.toString().split("\n")); - }); - }).then((res) => res).catch((err) => { - throw err; - }); - const fileData = []; - if (Array.isArray(unzippedData)) { - for (const dataset of unzippedData) { - if (dataset && dataset.length > 0) { - fileData.push(JSON.parse(dataset)); - } - } - } - data = { file_data: fileData }; - } catch (err) { - data = { ok: false, error: err }; - } - } else if (!isGzipResponse && response.request.path === "/api/admin.analytics.getFile") { - data = JSON.parse(new node_util_1.TextDecoder().decode(data)); - } - if (typeof data === "string") { - try { - data = JSON.parse(data); - } catch (_) { - data = { ok: false, error: data }; - } - } - if (data.response_metadata === void 0) { - data.response_metadata = {}; - } - if (response.headers["x-oauth-scopes"] !== void 0) { - data.response_metadata.scopes = response.headers["x-oauth-scopes"].trim().split(/\s*,\s*/); - } - if (response.headers["x-accepted-oauth-scopes"] !== void 0) { - data.response_metadata.acceptedScopes = response.headers["x-accepted-oauth-scopes"].trim().split(/\s*,\s*/); - } - const retrySec = parseRetryHeaders(response); - if (retrySec !== void 0) { - data.response_metadata.retryAfter = retrySec; - } - return data; + static source() { + let cancel; + const token = new _CancelToken(function executor(c) { + cancel = c; }); - } - }; - exports2.WebClient = WebClient2; - WebClient2.loggerName = "WebClient"; - exports2.default = WebClient2; - function paginationOptionsForNextPage(previousResult, pageSize) { - if (previousResult !== void 0 && previousResult.response_metadata !== void 0 && previousResult.response_metadata.next_cursor !== void 0 && previousResult.response_metadata.next_cursor !== "") { return { - limit: pageSize, - cursor: previousResult.response_metadata.next_cursor + token, + cancel }; } - return void 0; + }; + var CancelToken$1 = CancelToken3; + function spread3(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; } - function parseRetryHeaders(response) { - if (response.headers["retry-after"] !== void 0) { - const retryAfter = Number.parseInt(response.headers["retry-after"], 10); - if (!Number.isNaN(retryAfter)) { - return retryAfter; - } + function isAxiosError3(payload) { + return utils$1.isObject(payload) && payload.isAxiosError === true; + } + var HttpStatusCode3 = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511 + }; + Object.entries(HttpStatusCode3).forEach(([key, value]) => { + HttpStatusCode3[value] = key; + }); + var HttpStatusCode$1 = HttpStatusCode3; + function createInstance2(defaultConfig) { + const context = new Axios$1(defaultConfig); + const instance = bind2(Axios$1.prototype.request, context); + utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true }); + utils$1.extend(instance, context, null, { allOwnKeys: true }); + instance.create = function create(instanceConfig) { + return createInstance2(mergeConfig3(defaultConfig, instanceConfig)); + }; + return instance; + } + var axios2 = createInstance2(defaults$1); + axios2.Axios = Axios$1; + axios2.CanceledError = CanceledError3; + axios2.CancelToken = CancelToken$1; + axios2.isCancel = isCancel3; + axios2.VERSION = VERSION3; + axios2.toFormData = toFormData3; + axios2.AxiosError = AxiosError3; + axios2.Cancel = axios2.CanceledError; + axios2.all = function all3(promises) { + return Promise.all(promises); + }; + axios2.spread = spread3; + axios2.isAxiosError = isAxiosError3; + axios2.mergeConfig = mergeConfig3; + axios2.AxiosHeaders = AxiosHeaders$1; + axios2.formToJSON = (thing) => formDataToJSON2(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); + axios2.getAdapter = adapters.getAdapter; + axios2.HttpStatusCode = HttpStatusCode$1; + axios2.default = axios2; + module2.exports = axios2; + } +}); + +// node_modules/is-electron/index.js +var require_is_electron = __commonJS({ + "node_modules/is-electron/index.js"(exports2, module2) { + function isElectron() { + if (typeof window !== "undefined" && typeof window.process === "object" && window.process.type === "renderer") { + return true; } - return void 0; + if (typeof process !== "undefined" && typeof process.versions === "object" && !!process.versions.electron) { + return true; + } + if (typeof navigator === "object" && typeof navigator.userAgent === "string" && navigator.userAgent.indexOf("Electron") >= 0) { + return true; + } + return false; } - function warnDeprecations(method, logger) { - const deprecatedMethods = ["workflows."]; - const isDeprecated = deprecatedMethods.some((depMethod) => { - const re2 = new RegExp(`^${depMethod}`); - return re2.test(method); - }); - if (isDeprecated) { - logger.warn(`${method} is deprecated. Please check on https://api.slack.com/methods for an alternative.`); + module2.exports = isElectron; + } +}); + +// node_modules/p-queue/node_modules/eventemitter3/index.js +var require_eventemitter3 = __commonJS({ + "node_modules/p-queue/node_modules/eventemitter3/index.js"(exports2, module2) { + "use strict"; + var has = Object.prototype.hasOwnProperty; + var prefix = "~"; + function Events() { + } + if (Object.create) { + Events.prototype = /* @__PURE__ */ Object.create(null); + if (!new Events().__proto__) prefix = false; + } + function EE(fn2, context, once) { + this.fn = fn2; + this.context = context; + this.once = once || false; + } + function addListener(emitter, event, fn2, context, once) { + if (typeof fn2 !== "function") { + throw new TypeError("The listener must be a function"); } + var listener = new EE(fn2, context || emitter, once), evt = prefix ? prefix + event : event; + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + return emitter; } - function warnIfFallbackIsMissing(method, logger, options) { - const targetMethods = ["chat.postEphemeral", "chat.postMessage", "chat.scheduleMessage"]; - const isTargetMethod = targetMethods.includes(method); - const hasAttachments = (args) => Array.isArray(args.attachments) && args.attachments.length; - const missingAttachmentFallbackDetected = (args) => Array.isArray(args.attachments) && args.attachments.some((attachment) => !attachment.fallback || attachment.fallback.trim() === ""); - const isEmptyText = (args) => args.text === void 0 || args.text === null || args.text === ""; - const buildMissingTextWarning = () => `The top-level \`text\` argument is missing in the request payload for a ${method} call - It's a best practice to always provide a \`text\` argument when posting a message. The \`text\` is used in places where the content cannot be rendered such as: system push notifications, assistive technology such as screen readers, etc.`; - const buildMissingFallbackWarning = () => `Additionally, the attachment-level \`fallback\` argument is missing in the request payload for a ${method} call - To avoid this warning, it is recommended to always provide a top-level \`text\` argument when posting a message. Alternatively, you can provide an attachment-level \`fallback\` argument, though this is now considered a legacy field (see https://api.slack.com/reference/messaging/attachments#legacy_fields for more details).`; - if (isTargetMethod && typeof options === "object") { - if (hasAttachments(options)) { - if (missingAttachmentFallbackDetected(options) && isEmptyText(options)) { - logger.warn(buildMissingTextWarning()); - logger.warn(buildMissingFallbackWarning()); + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + function EventEmitter3() { + this._events = new Events(); + this._eventsCount = 0; + } + EventEmitter3.prototype.eventNames = function eventNames() { + var names = [], events, name; + if (this._eventsCount === 0) return names; + for (name in events = this._events) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + return names; + }; + EventEmitter3.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event, handlers = this._events[evt]; + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + for (var i = 0, l = handlers.length, ee2 = new Array(l); i < l; i++) { + ee2[i] = handlers[i].fn; + } + return ee2; + }; + EventEmitter3.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event, listeners = this._events[evt]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + EventEmitter3.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return false; + var listeners = this._events[evt], len = arguments.length, args, i; + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); + switch (len) { + case 1: + return listeners.fn.call(listeners.context), true; + case 2: + return listeners.fn.call(listeners.context, a1), true; + case 3: + return listeners.fn.call(listeners.context, a1, a2), true; + case 4: + return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: + return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: + return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + for (i = 1, args = new Array(len - 1); i < len; i++) { + args[i - 1] = arguments[i]; + } + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length, j2; + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); + switch (len) { + case 1: + listeners[i].fn.call(listeners[i].context); + break; + case 2: + listeners[i].fn.call(listeners[i].context, a1); + break; + case 3: + listeners[i].fn.call(listeners[i].context, a1, a2); + break; + case 4: + listeners[i].fn.call(listeners[i].context, a1, a2, a3); + break; + default: + if (!args) for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) { + args[j2 - 1] = arguments[j2]; + } + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + return true; + }; + EventEmitter3.prototype.on = function on2(event, fn2, context) { + return addListener(this, event, fn2, context, false); + }; + EventEmitter3.prototype.once = function once(event, fn2, context) { + return addListener(this, event, fn2, context, true); + }; + EventEmitter3.prototype.removeListener = function removeListener(event, fn2, context, once) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return this; + if (!fn2) { + clearEvent(this, evt); + return this; + } + var listeners = this._events[evt]; + if (listeners.fn) { + if (listeners.fn === fn2 && (!once || listeners.once) && (!context || listeners.context === context)) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if (listeners[i].fn !== fn2 || once && !listeners[i].once || context && listeners[i].context !== context) { + events.push(listeners[i]); } - } else if (isEmptyText(options)) { - logger.warn(buildMissingTextWarning()); } + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); } - } - function warnIfThreadTsIsNotString(method, logger, options) { - const targetMethods = ["chat.postEphemeral", "chat.postMessage", "chat.scheduleMessage", "files.upload"]; - const isTargetMethod = targetMethods.includes(method); - if (isTargetMethod && (options === null || options === void 0 ? void 0 : options.thread_ts) !== void 0 && typeof (options === null || options === void 0 ? void 0 : options.thread_ts) !== "string") { - logger.warn(buildThreadTsWarningMessage(method)); + return this; + }; + EventEmitter3.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; } + return this; + }; + EventEmitter3.prototype.off = EventEmitter3.prototype.removeListener; + EventEmitter3.prototype.addListener = EventEmitter3.prototype.on; + EventEmitter3.prefixed = prefix; + EventEmitter3.EventEmitter = EventEmitter3; + if ("undefined" !== typeof module2) { + module2.exports = EventEmitter3; } - function buildThreadTsWarningMessage(method) { - return `The given thread_ts value in the request payload for a ${method} call is a float value. We highly recommend using a string value instead.`; - } - function redact(body) { - const flattened = Object.entries(body).map(([key, value]) => { - if (value === void 0 || value === null) { - return []; - } - let serializedValue = value; - if (key.match(/.*token.*/) !== null || key.match(/[Aa]uthorization/)) { - serializedValue = "[[REDACTED]]"; - } - if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { - serializedValue = "[[BINARY VALUE OMITTED]]"; - } else if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") { - serializedValue = JSON.stringify(value); - } - return [key, serializedValue]; + } +}); + +// node_modules/p-finally/index.js +var require_p_finally = __commonJS({ + "node_modules/p-finally/index.js"(exports2, module2) { + "use strict"; + module2.exports = (promise, onFinally) => { + onFinally = onFinally || (() => { }); - const initialValue = {}; - return flattened.reduce((accumulator, [key, value]) => { - if (key !== void 0 && value !== void 0) { - accumulator[key] = value; - } - return accumulator; - }, initialValue); - } + return promise.then( + (val) => new Promise((resolve) => { + resolve(onFinally()); + }).then(() => val), + (err) => new Promise((resolve) => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); + }; } }); -// node_modules/@slack/web-api/dist/types/request/index.js -var require_request = __commonJS({ - "node_modules/@slack/web-api/dist/types/request/index.js"(exports2) { +// node_modules/p-timeout/index.js +var require_p_timeout = __commonJS({ + "node_modules/p-timeout/index.js"(exports2, module2) { "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); + var pFinally = require_p_finally(); + var TimeoutError2 = class extends Error { + constructor(message) { + super(message); + this.name = "TimeoutError"; + } + }; + var pTimeout = (promise, milliseconds, fallback2) => new Promise((resolve, reject) => { + if (typeof milliseconds !== "number" || milliseconds < 0) { + throw new TypeError("Expected `milliseconds` to be a positive number"); + } + if (milliseconds === Infinity) { + resolve(promise); + return; + } + const timer = setTimeout(() => { + if (typeof fallback2 === "function") { + try { + resolve(fallback2()); + } catch (error) { + reject(error); + } + return; + } + const message = typeof fallback2 === "string" ? fallback2 : `Promise timed out after ${milliseconds} milliseconds`; + const timeoutError = fallback2 instanceof Error ? fallback2 : new TimeoutError2(message); + if (typeof promise.cancel === "function") { + promise.cancel(); + } + reject(timeoutError); + }, milliseconds); + pFinally( + // eslint-disable-next-line promise/prefer-await-to-then + promise.then(resolve, reject), + () => { + clearTimeout(timer); + } + ); + }); + module2.exports = pTimeout; + module2.exports.default = pTimeout; + module2.exports.TimeoutError = TimeoutError2; } }); -// node_modules/@slack/web-api/dist/types/response/index.js -var require_response = __commonJS({ - "node_modules/@slack/web-api/dist/types/response/index.js"(exports2) { +// node_modules/p-queue/dist/lower-bound.js +var require_lower_bound = __commonJS({ + "node_modules/p-queue/dist/lower-bound.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); + function lowerBound(array, value, comparator) { + let first = 0; + let count = array.length; + while (count > 0) { + const step = count / 2 | 0; + let it2 = first + step; + if (comparator(array[it2], value) <= 0) { + first = ++it2; + count -= step + 1; + } else { + count = step; + } + } + return first; + } + exports2.default = lowerBound; } }); -// node_modules/@slack/web-api/dist/index.js -var require_dist4 = __commonJS({ - "node_modules/@slack/web-api/dist/index.js"(exports2) { +// node_modules/p-queue/dist/priority-queue.js +var require_priority_queue = __commonJS({ + "node_modules/p-queue/dist/priority-queue.js"(exports2) { "use strict"; - var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m2, k2); - if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { - return m2[k2]; - } }; + Object.defineProperty(exports2, "__esModule", { value: true }); + var lower_bound_1 = require_lower_bound(); + var PriorityQueue = class { + constructor() { + this._queue = []; + } + enqueue(run, options) { + options = Object.assign({ priority: 0 }, options); + const element = { + priority: options.priority, + run + }; + if (this.size && this._queue[this.size - 1].priority >= options.priority) { + this._queue.push(element); + return; + } + const index2 = lower_bound_1.default(this._queue, element, (a, b2) => b2.priority - a.priority); + this._queue.splice(index2, 0, element); + } + dequeue() { + const item = this._queue.shift(); + return item === null || item === void 0 ? void 0 : item.run; + } + filter(options) { + return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); + } + get size() { + return this._queue.length; } - Object.defineProperty(o, k22, desc); - } : function(o, m2, k2, k22) { - if (k22 === void 0) k22 = k2; - o[k22] = m2[k2]; - }); - var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { - for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); - }; - var __importDefault = exports2 && exports2.__importDefault || function(mod2) { - return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; }; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.addAppMetadata = exports2.retryPolicies = exports2.ErrorCode = exports2.LogLevel = exports2.WebClientEvent = exports2.WebClient = void 0; - var WebClient_1 = require_WebClient(); - Object.defineProperty(exports2, "WebClient", { enumerable: true, get: function() { - return WebClient_1.WebClient; - } }); - Object.defineProperty(exports2, "WebClientEvent", { enumerable: true, get: function() { - return WebClient_1.WebClientEvent; - } }); - var logger_1 = require_logger2(); - Object.defineProperty(exports2, "LogLevel", { enumerable: true, get: function() { - return logger_1.LogLevel; - } }); - var errors_1 = require_errors3(); - Object.defineProperty(exports2, "ErrorCode", { enumerable: true, get: function() { - return errors_1.ErrorCode; - } }); - var retry_policies_1 = require_retry_policies(); - Object.defineProperty(exports2, "retryPolicies", { enumerable: true, get: function() { - return __importDefault(retry_policies_1).default; - } }); - var instrument_1 = require_instrument(); - Object.defineProperty(exports2, "addAppMetadata", { enumerable: true, get: function() { - return instrument_1.addAppMetadata; - } }); - __exportStar(require_methods(), exports2); - __exportStar(require_request(), exports2); - __exportStar(require_response(), exports2); + exports2.default = PriorityQueue; } }); -// node_modules/@prisma/client/runtime/library.js -var require_library = __commonJS({ - "node_modules/@prisma/client/runtime/library.js"(exports, module) { +// node_modules/p-queue/dist/index.js +var require_dist = __commonJS({ + "node_modules/p-queue/dist/index.js"(exports2) { "use strict"; - var eu = Object.create; - var Nr = Object.defineProperty; - var tu = Object.getOwnPropertyDescriptor; - var ru = Object.getOwnPropertyNames; - var nu = Object.getPrototypeOf; - var iu = Object.prototype.hasOwnProperty; - var Z = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports); - var Ut = (e, t) => { - for (var r in t) Nr(e, r, { get: t[r], enumerable: true }); - }; - var ho = (e, t, r, n) => { - if (t && typeof t == "object" || typeof t == "function") for (let i of ru(t)) !iu.call(e, i) && i !== r && Nr(e, i, { get: () => t[i], enumerable: !(n = tu(t, i)) || n.enumerable }); - return e; + Object.defineProperty(exports2, "__esModule", { value: true }); + var EventEmitter3 = require_eventemitter3(); + var p_timeout_1 = require_p_timeout(); + var priority_queue_1 = require_priority_queue(); + var empty2 = () => { }; - var k = (e, t, r) => (r = e != null ? eu(nu(e)) : {}, ho(t || !e || !e.__esModule ? Nr(r, "default", { value: e, enumerable: true }) : r, e)); - var ou = (e) => ho(Nr({}, "__esModule", { value: true }), e); - var jo = Z((pf, Zn) => { - "use strict"; - var v = Zn.exports; - Zn.exports.default = v; - var D = "\x1B[", Ht = "\x1B]", ft = "\x07", Jr = ";", qo = process.env.TERM_PROGRAM === "Apple_Terminal"; - v.cursorTo = (e, t) => { - if (typeof e != "number") throw new TypeError("The `x` argument is required"); - return typeof t != "number" ? D + (e + 1) + "G" : D + (t + 1) + ";" + (e + 1) + "H"; - }; - v.cursorMove = (e, t) => { - if (typeof e != "number") throw new TypeError("The `x` argument is required"); - let r = ""; - return e < 0 ? r += D + -e + "D" : e > 0 && (r += D + e + "C"), t < 0 ? r += D + -t + "A" : t > 0 && (r += D + t + "B"), r; - }; - v.cursorUp = (e = 1) => D + e + "A"; - v.cursorDown = (e = 1) => D + e + "B"; - v.cursorForward = (e = 1) => D + e + "C"; - v.cursorBackward = (e = 1) => D + e + "D"; - v.cursorLeft = D + "G"; - v.cursorSavePosition = qo ? "\x1B7" : D + "s"; - v.cursorRestorePosition = qo ? "\x1B8" : D + "u"; - v.cursorGetPosition = D + "6n"; - v.cursorNextLine = D + "E"; - v.cursorPrevLine = D + "F"; - v.cursorHide = D + "?25l"; - v.cursorShow = D + "?25h"; - v.eraseLines = (e) => { - let t = ""; - for (let r = 0; r < e; r++) t += v.eraseLine + (r < e - 1 ? v.cursorUp() : ""); - return e && (t += v.cursorLeft), t; - }; - v.eraseEndLine = D + "K"; - v.eraseStartLine = D + "1K"; - v.eraseLine = D + "2K"; - v.eraseDown = D + "J"; - v.eraseUp = D + "1J"; - v.eraseScreen = D + "2J"; - v.scrollUp = D + "S"; - v.scrollDown = D + "T"; - v.clearScreen = "\x1Bc"; - v.clearTerminal = process.platform === "win32" ? `${v.eraseScreen}${D}0f` : `${v.eraseScreen}${D}3J${D}H`; - v.beep = ft; - v.link = (e, t) => [Ht, "8", Jr, Jr, t, ft, e, Ht, "8", Jr, Jr, ft].join(""); - v.image = (e, t = {}) => { - let r = `${Ht}1337;File=inline=1`; - return t.width && (r += `;width=${t.width}`), t.height && (r += `;height=${t.height}`), t.preserveAspectRatio === false && (r += ";preserveAspectRatio=0"), r + ":" + e.toString("base64") + ft; - }; - v.iTerm = { setCwd: (e = process.cwd()) => `${Ht}50;CurrentDir=${e}${ft}`, annotation: (e, t = {}) => { - let r = `${Ht}1337;`, n = typeof t.x < "u", i = typeof t.y < "u"; - if ((n || i) && !(n && i && typeof t.length < "u")) throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined"); - return e = e.replace(/\|/g, ""), r += t.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=", t.length > 0 ? r += (n ? [e, t.length, t.x, t.y] : [t.length, e]).join("|") : r += e, r + ft; - } }; - }); - var Xn = Z((df, Vo) => { - "use strict"; - Vo.exports = (e, t = process.argv) => { - let r = e.startsWith("-") ? "" : e.length === 1 ? "-" : "--", n = t.indexOf(r + e), i = t.indexOf("--"); - return n !== -1 && (i === -1 || n < i); - }; - }); - var Go = Z((mf, Uo) => { - "use strict"; - var Gu = __require("os"), Bo = __require("tty"), de = Xn(), { env: Q } = process, Qe; - de("no-color") || de("no-colors") || de("color=false") || de("color=never") ? Qe = 0 : (de("color") || de("colors") || de("color=true") || de("color=always")) && (Qe = 1); - "FORCE_COLOR" in Q && (Q.FORCE_COLOR === "true" ? Qe = 1 : Q.FORCE_COLOR === "false" ? Qe = 0 : Qe = Q.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(Q.FORCE_COLOR, 10), 3)); - function ei(e) { - return e === 0 ? false : { level: e, hasBasic: true, has256: e >= 2, has16m: e >= 3 }; + var timeoutError = new p_timeout_1.TimeoutError(); + var PQueue = class extends EventEmitter3 { + constructor(options) { + var _a2, _b, _c2, _d2; + super(); + this._intervalCount = 0; + this._intervalEnd = 0; + this._pendingCount = 0; + this._resolveEmpty = empty2; + this._resolveIdle = empty2; + options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); + if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { + throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a2 = options.intervalCap) === null || _a2 === void 0 ? void 0 : _a2.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`); + } + if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) { + throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d2 = (_c2 = options.interval) === null || _c2 === void 0 ? void 0 : _c2.toString()) !== null && _d2 !== void 0 ? _d2 : ""}\` (${typeof options.interval})`); + } + this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; + this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; + this._intervalCap = options.intervalCap; + this._interval = options.interval; + this._queue = new options.queueClass(); + this._queueClass = options.queueClass; + this.concurrency = options.concurrency; + this._timeout = options.timeout; + this._throwOnTimeout = options.throwOnTimeout === true; + this._isPaused = options.autoStart === false; } - function ti(e, t) { - if (Qe === 0) return 0; - if (de("color=16m") || de("color=full") || de("color=truecolor")) return 3; - if (de("color=256")) return 2; - if (e && !t && Qe === void 0) return 0; - let r = Qe || 0; - if (Q.TERM === "dumb") return r; - if (process.platform === "win32") { - let n = Gu.release().split("."); - return Number(n[0]) >= 10 && Number(n[2]) >= 10586 ? Number(n[2]) >= 14931 ? 3 : 2 : 1; + get _doesIntervalAllowAnother() { + return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + } + get _doesConcurrentAllowAnother() { + return this._pendingCount < this._concurrency; + } + _next() { + this._pendingCount--; + this._tryToStartAnother(); + this.emit("next"); + } + _resolvePromises() { + this._resolveEmpty(); + this._resolveEmpty = empty2; + if (this._pendingCount === 0) { + this._resolveIdle(); + this._resolveIdle = empty2; + this.emit("idle"); } - if ("CI" in Q) return ["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((n) => n in Q) || Q.CI_NAME === "codeship" ? 1 : r; - if ("TEAMCITY_VERSION" in Q) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Q.TEAMCITY_VERSION) ? 1 : 0; - if (Q.COLORTERM === "truecolor") return 3; - if ("TERM_PROGRAM" in Q) { - let n = parseInt((Q.TERM_PROGRAM_VERSION || "").split(".")[0], 10); - switch (Q.TERM_PROGRAM) { - case "iTerm.app": - return n >= 3 ? 3 : 2; - case "Apple_Terminal": - return 2; + } + _onResumeInterval() { + this._onInterval(); + this._initializeIntervalIfNeeded(); + this._timeoutId = void 0; + } + _isIntervalPaused() { + const now = Date.now(); + if (this._intervalId === void 0) { + const delay = this._intervalEnd - now; + if (delay < 0) { + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + } else { + if (this._timeoutId === void 0) { + this._timeoutId = setTimeout(() => { + this._onResumeInterval(); + }, delay); + } + return true; + } + } + return false; + } + _tryToStartAnother() { + if (this._queue.size === 0) { + if (this._intervalId) { + clearInterval(this._intervalId); + } + this._intervalId = void 0; + this._resolvePromises(); + return false; + } + if (!this._isPaused) { + const canInitializeInterval = !this._isIntervalPaused(); + if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { + const job = this._queue.dequeue(); + if (!job) { + return false; + } + this.emit("active"); + job(); + if (canInitializeInterval) { + this._initializeIntervalIfNeeded(); + } + return true; } } - return /-256(color)?$/i.test(Q.TERM) ? 2 : /^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Q.TERM) || "COLORTERM" in Q ? 1 : r; + return false; + } + _initializeIntervalIfNeeded() { + if (this._isIntervalIgnored || this._intervalId !== void 0) { + return; + } + this._intervalId = setInterval(() => { + this._onInterval(); + }, this._interval); + this._intervalEnd = Date.now() + this._interval; + } + _onInterval() { + if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { + clearInterval(this._intervalId); + this._intervalId = void 0; + } + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + this._processQueue(); + } + /** + Executes all queued functions until it reaches the limit. + */ + _processQueue() { + while (this._tryToStartAnother()) { + } + } + get concurrency() { + return this._concurrency; + } + set concurrency(newConcurrency) { + if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + } + this._concurrency = newConcurrency; + this._processQueue(); + } + /** + Adds a sync or async task to the queue. Always returns a promise. + */ + async add(fn2, options = {}) { + return new Promise((resolve, reject) => { + const run = async () => { + this._pendingCount++; + this._intervalCount++; + try { + const operation = this._timeout === void 0 && options.timeout === void 0 ? fn2() : p_timeout_1.default(Promise.resolve(fn2()), options.timeout === void 0 ? this._timeout : options.timeout, () => { + if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) { + reject(timeoutError); + } + return void 0; + }); + resolve(await operation); + } catch (error) { + reject(error); + } + this._next(); + }; + this._queue.enqueue(run, options); + this._tryToStartAnother(); + this.emit("add"); + }); + } + /** + Same as `.add()`, but accepts an array of sync or async functions. + + @returns A promise that resolves when all functions are resolved. + */ + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); + } + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this._isPaused) { + return this; + } + this._isPaused = false; + this._processQueue(); + return this; } - function Qu(e) { - let t = ti(e, e && e.isTTY); - return ei(t); + /** + Put queue execution on hold. + */ + pause() { + this._isPaused = true; } - Uo.exports = { supportsColor: Qu, stdout: ei(ti(true, Bo.isatty(1))), stderr: ei(ti(true, Bo.isatty(2))) }; - }); - var Wo = Z((ff, Jo) => { - "use strict"; - var Ju = Go(), gt = Xn(); - function Qo(e) { - if (/^\d{3,4}$/.test(e)) { - let r = /(\d{1,2})(\d{2})/.exec(e); - return { major: 0, minor: parseInt(r[1], 10), patch: parseInt(r[2], 10) }; - } - let t = (e || "").split(".").map((r) => parseInt(r, 10)); - return { major: t[0], minor: t[1], patch: t[2] }; + /** + Clear the queue. + */ + clear() { + this._queue = new this._queueClass(); } - function ri(e) { - let { env: t } = process; - if ("FORCE_HYPERLINK" in t) return !(t.FORCE_HYPERLINK.length > 0 && parseInt(t.FORCE_HYPERLINK, 10) === 0); - if (gt("no-hyperlink") || gt("no-hyperlinks") || gt("hyperlink=false") || gt("hyperlink=never")) return false; - if (gt("hyperlink=true") || gt("hyperlink=always") || "NETLIFY" in t) return true; - if (!Ju.supportsColor(e) || e && !e.isTTY || process.platform === "win32" || "CI" in t || "TEAMCITY_VERSION" in t) return false; - if ("TERM_PROGRAM" in t) { - let r = Qo(t.TERM_PROGRAM_VERSION); - switch (t.TERM_PROGRAM) { - case "iTerm.app": - return r.major === 3 ? r.minor >= 1 : r.major > 3; - case "WezTerm": - return r.major >= 20200620; - case "vscode": - return r.major > 1 || r.major === 1 && r.minor >= 72; - } - } - if ("VTE_VERSION" in t) { - if (t.VTE_VERSION === "0.50.0") return false; - let r = Qo(t.VTE_VERSION); - return r.major > 0 || r.minor >= 50; + /** + Can be called multiple times. Useful if you for example add additional items at a later time. + + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + if (this._queue.size === 0) { + return; } - return false; + return new Promise((resolve) => { + const existingResolve = this._resolveEmpty; + this._resolveEmpty = () => { + existingResolve(); + resolve(); + }; + }); } - Jo.exports = { supportsHyperlink: ri, stdout: ri(process.stdout), stderr: ri(process.stderr) }; - }); - var Ko = Z((gf, Kt) => { - "use strict"; - var Wu = jo(), ni = Wo(), Ho = (e, t, { target: r = "stdout", ...n } = {}) => ni[r] ? Wu.link(e, t) : n.fallback === false ? e : typeof n.fallback == "function" ? n.fallback(e, t) : `${e} (\u200B${t}\u200B)`; - Kt.exports = (e, t, r = {}) => Ho(e, t, r); - Kt.exports.stderr = (e, t, r = {}) => Ho(e, t, { target: "stderr", ...r }); - Kt.exports.isSupported = ni.stdout; - Kt.exports.stderr.isSupported = ni.stderr; - }); - var oi = Z((Rf, Hu) => { - Hu.exports = { name: "@prisma/engines-version", version: "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2", main: "index.js", types: "index.d.ts", license: "Apache-2.0", author: "Tim Suchanek ", prisma: { enginesVersion: "605197351a3c8bdd595af2d2a9bc3025bca48ea2" }, repository: { type: "git", url: "https://github.com/prisma/engines-wrapper.git", directory: "packages/engines-version" }, devDependencies: { "@types/node": "18.19.34", typescript: "4.9.5" }, files: ["index.js", "index.d.ts"], scripts: { build: "tsc -d" } }; - }); - var si = Z((Wr) => { - "use strict"; - Object.defineProperty(Wr, "__esModule", { value: true }); - Wr.enginesVersion = void 0; - Wr.enginesVersion = oi().prisma.enginesVersion; - }); - var Xo = Z((Gf, Yu) => { - Yu.exports = { name: "dotenv", version: "16.0.3", description: "Loads environment variables from .env file", main: "lib/main.js", types: "lib/main.d.ts", exports: { ".": { require: "./lib/main.js", types: "./lib/main.d.ts", default: "./lib/main.js" }, "./config": "./config.js", "./config.js": "./config.js", "./lib/env-options": "./lib/env-options.js", "./lib/env-options.js": "./lib/env-options.js", "./lib/cli-options": "./lib/cli-options.js", "./lib/cli-options.js": "./lib/cli-options.js", "./package.json": "./package.json" }, scripts: { "dts-check": "tsc --project tests/types/tsconfig.json", lint: "standard", "lint-readme": "standard-markdown", pretest: "npm run lint && npm run dts-check", test: "tap tests/*.js --100 -Rspec", prerelease: "npm test", release: "standard-version" }, repository: { type: "git", url: "git://github.com/motdotla/dotenv.git" }, keywords: ["dotenv", "env", ".env", "environment", "variables", "config", "settings"], readmeFilename: "README.md", license: "BSD-2-Clause", devDependencies: { "@types/node": "^17.0.9", decache: "^4.6.1", dtslint: "^3.7.0", sinon: "^12.0.1", standard: "^16.0.4", "standard-markdown": "^7.1.0", "standard-version": "^9.3.2", tap: "^15.1.6", tar: "^6.1.11", typescript: "^4.5.4" }, engines: { node: ">=12" } }; - }); - var ts = Z((Qf, Kr) => { - "use strict"; - var Zu = __require("fs"), es = __require("path"), Xu = __require("os"), ec = Xo(), tc = ec.version, rc = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; - function nc2(e) { - let t = {}, r = e.toString(); - r = r.replace(/\r\n?/mg, ` -`); - let n; - for (; (n = rc.exec(r)) != null; ) { - let i = n[1], o = n[2] || ""; - o = o.trim(); - let s = o[0]; - o = o.replace(/^(['"`])([\s\S]*)\1$/mg, "$2"), s === '"' && (o = o.replace(/\\n/g, ` -`), o = o.replace(/\\r/g, "\r")), t[i] = o; + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + if (this._pendingCount === 0 && this._queue.size === 0) { + return; } - return t; + return new Promise((resolve) => { + const existingResolve = this._resolveIdle; + this._resolveIdle = () => { + existingResolve(); + resolve(); + }; + }); } - function ci(e) { - console.log(`[dotenv@${tc}][DEBUG] ${e}`); + /** + Size of the queue. + */ + get size() { + return this._queue.size; } - function ic(e) { - return e[0] === "~" ? es.join(Xu.homedir(), e.slice(1)) : e; + /** + Size of the queue, filtered by the given options. + + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + return this._queue.filter(options).length; } - function oc(e) { - let t = es.resolve(process.cwd(), ".env"), r = "utf8", n = !!(e && e.debug), i = !!(e && e.override); - e && (e.path != null && (t = ic(e.path)), e.encoding != null && (r = e.encoding)); - try { - let o = Hr.parse(Zu.readFileSync(t, { encoding: r })); - return Object.keys(o).forEach(function(s) { - Object.prototype.hasOwnProperty.call(process.env, s) ? (i === true && (process.env[s] = o[s]), n && ci(i === true ? `"${s}" is already defined in \`process.env\` and WAS overwritten` : `"${s}" is already defined in \`process.env\` and was NOT overwritten`)) : process.env[s] = o[s]; - }), { parsed: o }; - } catch (o) { - return n && ci(`Failed to load ${t} ${o.message}`), { error: o }; + /** + Number of pending promises. + */ + get pending() { + return this._pendingCount; + } + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this._isPaused; + } + get timeout() { + return this._timeout; + } + /** + Set the timeout for future operations. + */ + set timeout(milliseconds) { + this._timeout = milliseconds; + } + }; + exports2.default = PQueue; + } +}); + +// node_modules/retry/lib/retry_operation.js +var require_retry_operation = __commonJS({ + "node_modules/retry/lib/retry_operation.js"(exports2, module2) { + function RetryOperation(timeouts, options) { + if (typeof options === "boolean") { + options = { forever: options }; + } + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); + } + } + module2.exports = RetryOperation; + RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); + }; + RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } + this._timeouts = []; + this._cachedTimeouts = null; + }; + RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (!err) { + return false; + } + var currentTime = (/* @__PURE__ */ new Date()).getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error("RetryOperation timeout occurred")); + return false; + } + this._errors.push(err); + var timeout = this._timeouts.shift(); + if (timeout === void 0) { + if (this._cachedTimeouts) { + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; } } - var Hr = { config: oc, parse: nc2 }; - Kr.exports.config = Hr.config; - Kr.exports.parse = Hr.parse; - Kr.exports = Hr; - }); - var as = Z((Zf, ss) => { - "use strict"; - ss.exports = (e) => { - let t = e.match(/^[ \t]*(?=\S)/gm); - return t ? t.reduce((r, n) => Math.min(r, n.length), 1 / 0) : 0; - }; - }); - var us = Z((Xf, ls) => { - "use strict"; - var uc = as(); - ls.exports = (e) => { - let t = uc(e); - if (t === 0) return e; - let r = new RegExp(`^[ \\t]{${t}}`, "gm"); - return e.replace(r, ""); - }; - }); - var fi = Z((og, cs) => { - "use strict"; - cs.exports = (e, t = 1, r) => { - if (r = { indent: " ", includeEmptyLines: false, ...r }, typeof e != "string") throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof e}\``); - if (typeof t != "number") throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof t}\``); - if (typeof r.indent != "string") throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof r.indent}\``); - if (t === 0) return e; - let n = r.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; - return e.replace(n, r.indent.repeat(t)); - }; - }); - var fs = Z((lg, ms) => { - "use strict"; - ms.exports = ({ onlyFirst: e = false } = {}) => { - let t = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"); - return new RegExp(t, e ? void 0 : "g"); - }; - }); - var bi = Z((ug, gs) => { - "use strict"; - var yc = fs(); - gs.exports = (e) => typeof e == "string" ? e.replace(yc(), "") : e; - }); - var hs = Z((dg, Zr) => { - "use strict"; - Zr.exports = (e = {}) => { - let t; - if (e.repoUrl) t = e.repoUrl; - else if (e.user && e.repo) t = `https://github.com/${e.user}/${e.repo}`; - else throw new Error("You need to specify either the `repoUrl` option or both the `user` and `repo` options"); - let r = new URL(`${t}/issues/new`), n = ["body", "title", "labels", "template", "milestone", "assignee", "projects"]; - for (let i of n) { - let o = e[i]; - if (o !== void 0) { - if (i === "labels" || i === "projects") { - if (!Array.isArray(o)) throw new TypeError(`The \`${i}\` option should be an array`); - o = o.join(","); - } - r.searchParams.set(i, o); + var self2 = this; + this._timer = setTimeout(function() { + self2._attempts++; + if (self2._operationTimeoutCb) { + self2._timeout = setTimeout(function() { + self2._operationTimeoutCb(self2._attempts); + }, self2._operationTimeout); + if (self2._options.unref) { + self2._timeout.unref(); } } - return r.toString(); - }; - Zr.exports.default = Zr.exports; - }); - var Ai = Z((Th, $s) => { - "use strict"; - $s.exports = /* @__PURE__ */ function() { - function e(t, r, n, i, o) { - return t < r || n < r ? t > n ? n + 1 : t + 1 : i === o ? r : r + 1; + self2._fn(self2._attempts); + }, timeout); + if (this._options.unref) { + this._timer.unref(); + } + return true; + }; + RetryOperation.prototype.attempt = function(fn2, timeoutOps) { + this._fn = fn2; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; } - return function(t, r) { - if (t === r) return 0; - if (t.length > r.length) { - var n = t; - t = r, r = n; - } - for (var i = t.length, o = r.length; i > 0 && t.charCodeAt(i - 1) === r.charCodeAt(o - 1); ) i--, o--; - for (var s = 0; s < i && t.charCodeAt(s) === r.charCodeAt(s); ) s++; - if (i -= s, o -= s, i === 0 || o < 3) return o; - var a = 0, l, u, c, p, d, f, g, h, O, T, S, C, E = []; - for (l = 0; l < i; l++) E.push(l + 1), E.push(t.charCodeAt(s + l)); - for (var me = E.length - 1; a < o - 3; ) for (O = r.charCodeAt(s + (u = a)), T = r.charCodeAt(s + (c = a + 1)), S = r.charCodeAt(s + (p = a + 2)), C = r.charCodeAt(s + (d = a + 3)), f = a += 4, l = 0; l < me; l += 2) g = E[l], h = E[l + 1], u = e(g, u, c, O, h), c = e(u, c, p, T, h), p = e(c, p, d, S, h), f = e(p, d, f, C, h), E[l] = f, d = p, p = c, c = u, u = g; - for (; a < o; ) for (O = r.charCodeAt(s + (u = a)), f = ++a, l = 0; l < me; l += 2) g = E[l], E[l] = f = e(g, u, f, O, E[l + 1]), u = g; - return f; - }; - }(); - }); - var Nm = {}; - Ut(Nm, { Debug: () => Gn, Decimal: () => xe, Extensions: () => jn, MetricsClient: () => Dt, NotFoundError: () => Le, PrismaClientInitializationError: () => R, PrismaClientKnownRequestError: () => V, PrismaClientRustPanicError: () => le, PrismaClientUnknownRequestError: () => B, PrismaClientValidationError: () => J, Public: () => Vn, Sql: () => oe, defineDmmfProperty: () => ua, deserializeJsonResponse: () => wt, dmmfToRuntimeDataModel: () => la, empty: () => ma, getPrismaClient: () => Yl, getRuntime: () => In, join: () => da, makeStrictEnum: () => Zl, makeTypedQueryFactory: () => ca, objectEnumValues: () => yn, raw: () => ji, serializeJsonQuery: () => vn, skip: () => Pn, sqltag: () => Vi, warnEnvConflicts: () => Xl, warnOnce: () => tr }); - module.exports = ou(Nm); - var jn = {}; - Ut(jn, { defineExtension: () => yo, getExtensionContext: () => bo }); - function yo(e) { - return typeof e == "function" ? e : (t) => t.$extends(e); - } - function bo(e) { - return e; - } - var Vn = {}; - Ut(Vn, { validator: () => Eo }); - function Eo(...e) { - return (t) => t; - } - var Mr = {}; - Ut(Mr, { $: () => To, bgBlack: () => gu, bgBlue: () => Eu, bgCyan: () => xu, bgGreen: () => yu, bgMagenta: () => wu, bgRed: () => hu, bgWhite: () => Pu, bgYellow: () => bu, black: () => pu, blue: () => rt, bold: () => H, cyan: () => De, dim: () => Oe, gray: () => Gt, green: () => qe, grey: () => fu, hidden: () => uu, inverse: () => lu, italic: () => au, magenta: () => du, red: () => ce, reset: () => su, strikethrough: () => cu, underline: () => X, white: () => mu, yellow: () => ke }); - var Bn; - var wo; - var xo; - var Po; - var vo = true; - typeof process < "u" && ({ FORCE_COLOR: Bn, NODE_DISABLE_COLORS: wo, NO_COLOR: xo, TERM: Po } = process.env || {}, vo = process.stdout && process.stdout.isTTY); - var To = { enabled: !wo && xo == null && Po !== "dumb" && (Bn != null && Bn !== "0" || vo) }; - function M(e, t) { - let r = new RegExp(`\\x1b\\[${t}m`, "g"), n = `\x1B[${e}m`, i = `\x1B[${t}m`; - return function(o) { - return !To.enabled || o == null ? o : n + (~("" + o).indexOf(i) ? o.replace(r, i + n) : o) + i; - }; - } - var su = M(0, 0); - var H = M(1, 22); - var Oe = M(2, 22); - var au = M(3, 23); - var X = M(4, 24); - var lu = M(7, 27); - var uu = M(8, 28); - var cu = M(9, 29); - var pu = M(30, 39); - var ce = M(31, 39); - var qe = M(32, 39); - var ke = M(33, 39); - var rt = M(34, 39); - var du = M(35, 39); - var De = M(36, 39); - var mu = M(37, 39); - var Gt = M(90, 39); - var fu = M(90, 39); - var gu = M(40, 49); - var hu = M(41, 49); - var yu = M(42, 49); - var bu = M(43, 49); - var Eu = M(44, 49); - var wu = M(45, 49); - var xu = M(46, 49); - var Pu = M(47, 49); - var vu = 100; - var Ro = ["green", "yellow", "blue", "magenta", "cyan", "red"]; - var Qt = []; - var Co = Date.now(); - var Tu = 0; - var Un = typeof process < "u" ? process.env : {}; - globalThis.DEBUG ??= Un.DEBUG ?? ""; - globalThis.DEBUG_COLORS ??= Un.DEBUG_COLORS ? Un.DEBUG_COLORS === "true" : true; - var Jt = { enable(e) { - typeof e == "string" && (globalThis.DEBUG = e); - }, disable() { - let e = globalThis.DEBUG; - return globalThis.DEBUG = "", e; - }, enabled(e) { - let t = globalThis.DEBUG.split(",").map((i) => i.replace(/[.+?^${}()|[\]\\]/g, "\\$&")), r = t.some((i) => i === "" || i[0] === "-" ? false : e.match(RegExp(i.split("*").join(".*") + "$"))), n = t.some((i) => i === "" || i[0] !== "-" ? false : e.match(RegExp(i.slice(1).split("*").join(".*") + "$"))); - return r && !n; - }, log: (...e) => { - let [t, r, ...n] = e; - (console.warn ?? console.log)(`${t} ${r}`, ...n); - }, formatters: {} }; - function Ru(e) { - let t = { color: Ro[Tu++ % Ro.length], enabled: Jt.enabled(e), namespace: e, log: Jt.log, extend: () => { - } }, r = (...n) => { - let { enabled: i, namespace: o, color: s, log: a } = t; - if (n.length !== 0 && Qt.push([o, ...n]), Qt.length > vu && Qt.shift(), Jt.enabled(o) || i) { - let l = n.map((c) => typeof c == "string" ? c : Cu(c)), u = `+${Date.now() - Co}ms`; - Co = Date.now(), globalThis.DEBUG_COLORS ? a(Mr[s](H(o)), ...l, Mr[s](u)) : a(o, ...l, u); + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; } - }; - return new Proxy(r, { get: (n, i) => t[i], set: (n, i, o) => t[i] = o }); - } - var Gn = new Proxy(Ru, { get: (e, t) => Jt[t], set: (e, t, r) => Jt[t] = r }); - function Cu(e, t = 2) { - let r = /* @__PURE__ */ new Set(); - return JSON.stringify(e, (n, i) => { - if (typeof i == "object" && i !== null) { - if (r.has(i)) return "[Circular *]"; - r.add(i); - } else if (typeof i == "bigint") return i.toString(); - return i; - }, t); - } - function So(e = 7500) { - let t = Qt.map(([r, ...n]) => `${r} ${n.map((i) => typeof i == "string" ? i : JSON.stringify(i)).join(" ")}`).join(` -`); - return t.length < e ? t : t.slice(-e); - } - function Ao() { - Qt.length = 0; - } - var L = Gn; - var Io = k(__require("fs")); - function Qn() { - let e = process.env.PRISMA_QUERY_ENGINE_LIBRARY; - if (!(e && Io.default.existsSync(e)) && process.arch === "ia32") throw new Error('The default query engine type (Node-API, "library") is currently not supported for 32bit Node. Please set `engineType = "binary"` in the "generator" block of your "schema.prisma" file (or use the environment variables "PRISMA_CLIENT_ENGINE_TYPE=binary" and/or "PRISMA_CLI_QUERY_ENGINE_TYPE=binary".)'); - } - var Jn = ["darwin", "darwin-arm64", "debian-openssl-1.0.x", "debian-openssl-1.1.x", "debian-openssl-3.0.x", "rhel-openssl-1.0.x", "rhel-openssl-1.1.x", "rhel-openssl-3.0.x", "linux-arm64-openssl-1.1.x", "linux-arm64-openssl-1.0.x", "linux-arm64-openssl-3.0.x", "linux-arm-openssl-1.1.x", "linux-arm-openssl-1.0.x", "linux-arm-openssl-3.0.x", "linux-musl", "linux-musl-openssl-3.0.x", "linux-musl-arm64-openssl-1.1.x", "linux-musl-arm64-openssl-3.0.x", "linux-nixos", "linux-static-x64", "linux-static-arm64", "windows", "freebsd11", "freebsd12", "freebsd13", "freebsd14", "freebsd15", "openbsd", "netbsd", "arm"]; - var $r = "libquery_engine"; - function qr(e, t) { - let r = t === "url"; - return e.includes("windows") ? r ? "query_engine.dll.node" : `query_engine-${e}.dll.node` : e.includes("darwin") ? r ? `${$r}.dylib.node` : `${$r}-${e}.dylib.node` : r ? `${$r}.so.node` : `${$r}-${e}.so.node`; - } - var _o = k(__require("child_process")); - var zn = k(__require("fs/promises")); - var Gr = k(__require("os")); - var _e = Symbol.for("@ts-pattern/matcher"); - var Su = Symbol.for("@ts-pattern/isVariadic"); - var Vr = "@ts-pattern/anonymous-select-key"; - var Wn = (e) => !!(e && typeof e == "object"); - var jr = (e) => e && !!e[_e]; - var Ee = (e, t, r) => { - if (jr(e)) { - let n = e[_e](), { matched: i, selections: o } = n.match(t); - return i && o && Object.keys(o).forEach((s) => r(s, o[s])), i; } - if (Wn(e)) { - if (!Wn(t)) return false; - if (Array.isArray(e)) { - if (!Array.isArray(t)) return false; - let n = [], i = [], o = []; - for (let s of e.keys()) { - let a = e[s]; - jr(a) && a[Su] ? o.push(a) : o.length ? i.push(a) : n.push(a); - } - if (o.length) { - if (o.length > 1) throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed."); - if (t.length < n.length + i.length) return false; - let s = t.slice(0, n.length), a = i.length === 0 ? [] : t.slice(-i.length), l = t.slice(n.length, i.length === 0 ? 1 / 0 : -i.length); - return n.every((u, c) => Ee(u, s[c], r)) && i.every((u, c) => Ee(u, a[c], r)) && (o.length === 0 || Ee(o[0], l, r)); - } - return e.length === t.length && e.every((s, a) => Ee(s, t[a], r)); + var self2 = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self2._operationTimeoutCb(); + }, self2._operationTimeout); + } + this._operationStart = (/* @__PURE__ */ new Date()).getTime(); + this._fn(this._attempts); + }; + RetryOperation.prototype.try = function(fn2) { + console.log("Using RetryOperation.try() is deprecated"); + this.attempt(fn2); + }; + RetryOperation.prototype.start = function(fn2) { + console.log("Using RetryOperation.start() is deprecated"); + this.attempt(fn2); + }; + RetryOperation.prototype.start = RetryOperation.prototype.try; + RetryOperation.prototype.errors = function() { + return this._errors; + }; + RetryOperation.prototype.attempts = function() { + return this._attempts; + }; + RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; + counts[message] = count; + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; } - return Object.keys(e).every((n) => { - let i = e[n]; - return (n in t || jr(o = i) && o[_e]().matcherType === "optional") && Ee(i, t[n], r); - var o; - }); } - return Object.is(t, e); + return mainError; }; - var Ge = (e) => { - var t, r, n; - return Wn(e) ? jr(e) ? (t = (r = (n = e[_e]()).getSelectionKeys) == null ? void 0 : r.call(n)) != null ? t : [] : Array.isArray(e) ? Wt(e, Ge) : Wt(Object.values(e), Ge) : []; + } +}); + +// node_modules/retry/lib/retry.js +var require_retry = __commonJS({ + "node_modules/retry/lib/retry.js"(exports2) { + var RetryOperation = require_retry_operation(); + exports2.operation = function(options) { + var timeouts = exports2.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); }; - var Wt = (e, t) => e.reduce((r, n) => r.concat(t(n)), []); - function pe(e) { - return Object.assign(e, { optional: () => Au(e), and: (t) => j(e, t), or: (t) => Iu(e, t), select: (t) => t === void 0 ? Oo(e) : Oo(t, e) }); - } - function Au(e) { - return pe({ [_e]: () => ({ match: (t) => { - let r = {}, n = (i, o) => { - r[i] = o; - }; - return t === void 0 ? (Ge(e).forEach((i) => n(i, void 0)), { matched: true, selections: r }) : { matched: Ee(e, t, n), selections: r }; - }, getSelectionKeys: () => Ge(e), matcherType: "optional" }) }); - } - function j(...e) { - return pe({ [_e]: () => ({ match: (t) => { - let r = {}, n = (i, o) => { - r[i] = o; - }; - return { matched: e.every((i) => Ee(i, t, n)), selections: r }; - }, getSelectionKeys: () => Wt(e, Ge), matcherType: "and" }) }); - } - function Iu(...e) { - return pe({ [_e]: () => ({ match: (t) => { - let r = {}, n = (i, o) => { - r[i] = o; - }; - return Wt(e, Ge).forEach((i) => n(i, void 0)), { matched: e.some((i) => Ee(i, t, n)), selections: r }; - }, getSelectionKeys: () => Wt(e, Ge), matcherType: "or" }) }); - } - function I(e) { - return { [_e]: () => ({ match: (t) => ({ matched: !!e(t) }) }) }; - } - function Oo(...e) { - let t = typeof e[0] == "string" ? e[0] : void 0, r = e.length === 2 ? e[1] : typeof e[0] == "string" ? void 0 : e[0]; - return pe({ [_e]: () => ({ match: (n) => { - let i = { [t ?? Vr]: n }; - return { matched: r === void 0 || Ee(r, n, (o, s) => { - i[o] = s; - }), selections: i }; - }, getSelectionKeys: () => [t ?? Vr].concat(r === void 0 ? [] : Ge(r)) }) }); - } - function ye(e) { - return typeof e == "number"; - } - function je(e) { - return typeof e == "string"; - } - function Ve(e) { - return typeof e == "bigint"; - } - var Km = pe(I(function(e) { - return true; - })); - var Be = (e) => Object.assign(pe(e), { startsWith: (t) => { - return Be(j(e, (r = t, I((n) => je(n) && n.startsWith(r))))); - var r; - }, endsWith: (t) => { - return Be(j(e, (r = t, I((n) => je(n) && n.endsWith(r))))); - var r; - }, minLength: (t) => Be(j(e, ((r) => I((n) => je(n) && n.length >= r))(t))), length: (t) => Be(j(e, ((r) => I((n) => je(n) && n.length === r))(t))), maxLength: (t) => Be(j(e, ((r) => I((n) => je(n) && n.length <= r))(t))), includes: (t) => { - return Be(j(e, (r = t, I((n) => je(n) && n.includes(r))))); - var r; - }, regex: (t) => { - return Be(j(e, (r = t, I((n) => je(n) && !!n.match(r))))); - var r; - } }); - var zm = Be(I(je)); - var be = (e) => Object.assign(pe(e), { between: (t, r) => be(j(e, ((n, i) => I((o) => ye(o) && n <= o && i >= o))(t, r))), lt: (t) => be(j(e, ((r) => I((n) => ye(n) && n < r))(t))), gt: (t) => be(j(e, ((r) => I((n) => ye(n) && n > r))(t))), lte: (t) => be(j(e, ((r) => I((n) => ye(n) && n <= r))(t))), gte: (t) => be(j(e, ((r) => I((n) => ye(n) && n >= r))(t))), int: () => be(j(e, I((t) => ye(t) && Number.isInteger(t)))), finite: () => be(j(e, I((t) => ye(t) && Number.isFinite(t)))), positive: () => be(j(e, I((t) => ye(t) && t > 0))), negative: () => be(j(e, I((t) => ye(t) && t < 0))) }); - var Ym = be(I(ye)); - var Ue = (e) => Object.assign(pe(e), { between: (t, r) => Ue(j(e, ((n, i) => I((o) => Ve(o) && n <= o && i >= o))(t, r))), lt: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n < r))(t))), gt: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n > r))(t))), lte: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n <= r))(t))), gte: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n >= r))(t))), positive: () => Ue(j(e, I((t) => Ve(t) && t > 0))), negative: () => Ue(j(e, I((t) => Ve(t) && t < 0))) }); - var Zm = Ue(I(Ve)); - var Xm = pe(I(function(e) { - return typeof e == "boolean"; - })); - var ef = pe(I(function(e) { - return typeof e == "symbol"; - })); - var tf = pe(I(function(e) { - return e == null; - })); - var rf = pe(I(function(e) { - return e != null; - })); - var Hn = { matched: false, value: void 0 }; - function mt(e) { - return new Kn(e, Hn); - } - var Kn = class e { - constructor(t, r) { - this.input = void 0, this.state = void 0, this.input = t, this.state = r; + exports2.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); } - with(...t) { - if (this.state.matched) return this; - let r = t[t.length - 1], n = [t[0]], i; - t.length === 3 && typeof t[1] == "function" ? i = t[1] : t.length > 2 && n.push(...t.slice(1, t.length - 1)); - let o = false, s = {}, a = (u, c) => { - o = true, s[u] = c; - }, l = !n.some((u) => Ee(u, this.input, a)) || i && !i(this.input) ? Hn : { matched: true, value: r(o ? Vr in s ? s[Vr] : s : this.input, this.input) }; - return new e(this.input, l); + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1e3, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; } - when(t, r) { - if (this.state.matched) return this; - let n = !!t(this.input); - return new e(this.input, n ? { matched: true, value: r(this.input, this.input) } : Hn); + if (opts.minTimeout > opts.maxTimeout) { + throw new Error("minTimeout is greater than maxTimeout"); } - otherwise(t) { - return this.state.matched ? this.state.value : t(this.input); + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); } - exhaustive() { - if (this.state.matched) return this.state.value; - let t; - try { - t = JSON.stringify(this.input); - } catch { - t = this.input; - } - throw new Error(`Pattern matching error: no pattern matches value ${t}`); + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); } - run() { - return this.exhaustive(); + timeouts.sort(function(a, b2) { + return a - b2; + }); + return timeouts; + }; + exports2.createTimeout = function(attempt, opts) { + var random = opts.randomize ? Math.random() + 1 : 1; + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + return timeout; + }; + exports2.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; } - returnType() { - return this; + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === "function") { + methods.push(key); + } + } + } + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; + obj[method] = function retryWrapper(original2) { + var op2 = exports2.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + args.push(function(err) { + if (op2.retry(err)) { + return; + } + if (err) { + arguments[0] = op2.mainError(); + } + callback.apply(this, arguments); + }); + op2.attempt(function() { + original2.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; } }; - var Fo = __require("util"); - var Ou = { warn: ke("prisma:warn") }; - var ku = { warn: () => !process.env.PRISMA_DISABLE_WARNINGS }; - function Br(e, ...t) { - ku.warn() && console.warn(`${Ou.warn} ${e}`, ...t); - } - var Du = (0, Fo.promisify)(_o.default.exec); - var te = L("prisma:get-platform"); - var _u = ["1.0.x", "1.1.x", "3.0.x"]; - async function Lo() { - let e = Gr.default.platform(), t = process.arch; - if (e === "freebsd") { - let s = await Qr("freebsd-version"); - if (s && s.trim().length > 0) { - let l = /^(\d+)\.?/.exec(s); - if (l) return { platform: "freebsd", targetDistro: `freebsd${l[1]}`, arch: t }; + } +}); + +// node_modules/retry/index.js +var require_retry2 = __commonJS({ + "node_modules/retry/index.js"(exports2, module2) { + module2.exports = require_retry(); + } +}); + +// node_modules/p-retry/index.js +var require_p_retry = __commonJS({ + "node_modules/p-retry/index.js"(exports2, module2) { + "use strict"; + var retry = require_retry2(); + var networkErrorMsgs = [ + "Failed to fetch", + // Chrome + "NetworkError when attempting to fetch resource.", + // Firefox + "The Internet connection appears to be offline.", + // Safari + "Network request failed" + // `cross-fetch` + ]; + var AbortError = class extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({ message } = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; } + this.name = "AbortError"; + this.message = message; } - if (e !== "linux") return { platform: e, arch: t }; - let r = await Lu(), n = await Uu(), i = Mu({ arch: t, archFromUname: n, familyDistro: r.familyDistro }), { libssl: o } = await $u(i); - return { platform: "linux", libssl: o, arch: t, archFromUname: n, ...r }; - } - function Fu(e) { - let t = /^ID="?([^"\n]*)"?$/im, r = /^ID_LIKE="?([^"\n]*)"?$/im, n = t.exec(e), i = n && n[1] && n[1].toLowerCase() || "", o = r.exec(e), s = o && o[1] && o[1].toLowerCase() || "", a = mt({ id: i, idLike: s }).with({ id: "alpine" }, ({ id: l }) => ({ targetDistro: "musl", familyDistro: l, originalDistro: l })).with({ id: "raspbian" }, ({ id: l }) => ({ targetDistro: "arm", familyDistro: "debian", originalDistro: l })).with({ id: "nixos" }, ({ id: l }) => ({ targetDistro: "nixos", originalDistro: l, familyDistro: "nixos" })).with({ id: "debian" }, { id: "ubuntu" }, ({ id: l }) => ({ targetDistro: "debian", familyDistro: "debian", originalDistro: l })).with({ id: "rhel" }, { id: "centos" }, { id: "fedora" }, ({ id: l }) => ({ targetDistro: "rhel", familyDistro: "rhel", originalDistro: l })).when(({ idLike: l }) => l.includes("debian") || l.includes("ubuntu"), ({ id: l }) => ({ targetDistro: "debian", familyDistro: "debian", originalDistro: l })).when(({ idLike: l }) => i === "arch" || l.includes("arch"), ({ id: l }) => ({ targetDistro: "debian", familyDistro: "arch", originalDistro: l })).when(({ idLike: l }) => l.includes("centos") || l.includes("fedora") || l.includes("rhel") || l.includes("suse"), ({ id: l }) => ({ targetDistro: "rhel", familyDistro: "rhel", originalDistro: l })).otherwise(({ id: l }) => ({ targetDistro: void 0, familyDistro: void 0, originalDistro: l })); - return te(`Found distro info: -${JSON.stringify(a, null, 2)}`), a; + }; + var decorateErrorWithCounts = (error, attemptNumber, options) => { + const retriesLeft = options.retries - (attemptNumber - 1); + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; + }; + var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage); + var pRetry = (input, options) => new Promise((resolve, reject) => { + options = { + onFailedAttempt: () => { + }, + retries: 10, + ...options + }; + const operation = retry.operation(options); + operation.attempt(async (attemptNumber) => { + try { + resolve(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } + if (error instanceof AbortError) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); + try { + await options.onFailedAttempt(error); + } catch (error2) { + reject(error2); + return; + } + if (!operation.retry(error)) { + reject(operation.mainError()); + } + } + } + }); + }); + module2.exports = pRetry; + module2.exports.default = pRetry; + module2.exports.AbortError = AbortError; + } +}); + +// node_modules/@slack/web-api/dist/errors.js +var require_errors3 = __commonJS({ + "node_modules/@slack/web-api/dist/errors.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ErrorCode = void 0; + exports2.errorWithCode = errorWithCode; + exports2.requestErrorWithOriginal = requestErrorWithOriginal; + exports2.httpErrorFromResponse = httpErrorFromResponse; + exports2.platformErrorFromResult = platformErrorFromResult; + exports2.rateLimitedErrorWithDelay = rateLimitedErrorWithDelay; + var ErrorCode; + (function(ErrorCode2) { + ErrorCode2["RequestError"] = "slack_webapi_request_error"; + ErrorCode2["HTTPError"] = "slack_webapi_http_error"; + ErrorCode2["PlatformError"] = "slack_webapi_platform_error"; + ErrorCode2["RateLimitedError"] = "slack_webapi_rate_limited_error"; + ErrorCode2["FileUploadInvalidArgumentsError"] = "slack_webapi_file_upload_invalid_args_error"; + ErrorCode2["FileUploadReadFileDataError"] = "slack_webapi_file_upload_read_file_data_error"; + })(ErrorCode || (exports2.ErrorCode = ErrorCode = {})); + function errorWithCode(error, code) { + const codedError = error; + codedError.code = code; + return codedError; } - async function Lu() { - let e = "/etc/os-release"; - try { - let t = await zn.default.readFile(e, { encoding: "utf-8" }); - return Fu(t); - } catch { - return { targetDistro: void 0, familyDistro: void 0, originalDistro: void 0 }; + function requestErrorWithOriginal(original, attachOriginal) { + const error = errorWithCode(new Error(`A request error occurred: ${original.message}`), ErrorCode.RequestError); + if (attachOriginal) { + error.original = original; } + return error; } - function Nu(e) { - let t = /^OpenSSL\s(\d+\.\d+)\.\d+/.exec(e); - if (t) { - let r = `${t[1]}.x`; - return No(r); + function httpErrorFromResponse(response) { + const error = errorWithCode(new Error(`An HTTP protocol error occurred: statusCode = ${response.status}`), ErrorCode.HTTPError); + error.statusCode = response.status; + error.statusMessage = response.statusText; + const nonNullHeaders = {}; + for (const k2 of Object.keys(response.headers)) { + if (k2 && response.headers[k2]) { + nonNullHeaders[k2] = response.headers[k2]; + } } + error.headers = nonNullHeaders; + error.body = response.data; + return error; } - function ko(e) { - let t = /libssl\.so\.(\d)(\.\d)?/.exec(e); - if (t) { - let r = `${t[1]}${t[2] ?? ".0"}.x`; - return No(r); + function platformErrorFromResult(result) { + const error = errorWithCode(new Error(`An API error occurred: ${result.error}`), ErrorCode.PlatformError); + error.data = result; + return error; + } + function rateLimitedErrorWithDelay(retrySec) { + const error = errorWithCode(new Error(`A rate-limit has been reached, you may retry this request in ${retrySec} seconds`), ErrorCode.RateLimitedError); + error.retryAfter = retrySec; + return error; + } + } +}); + +// node_modules/@slack/web-api/dist/file-upload.js +var require_file_upload = __commonJS({ + "node_modules/@slack/web-api/dist/file-upload.js"(exports2) { + "use strict"; + var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.getFileUploadJob = getFileUploadJob; + exports2.getMultipleFileUploadJobs = getMultipleFileUploadJobs; + exports2.getFileData = getFileData; + exports2.getFileDataLength = getFileDataLength; + exports2.getFileDataAsStream = getFileDataAsStream; + exports2.getAllFileUploadsToComplete = getAllFileUploadsToComplete; + exports2.warnIfNotUsingFilesUploadV2 = warnIfNotUsingFilesUploadV2; + exports2.warnIfChannels = warnIfChannels; + exports2.errorIfChannelsCsv = errorIfChannelsCsv; + exports2.errorIfInvalidOrMissingFileData = errorIfInvalidOrMissingFileData; + exports2.warnIfMissingOrInvalidFileNameAndDefault = warnIfMissingOrInvalidFileNameAndDefault; + exports2.warnIfLegacyFileType = warnIfLegacyFileType; + exports2.buildMissingFileIdError = buildMissingFileIdError; + exports2.buildFileSizeErrorMsg = buildFileSizeErrorMsg; + exports2.buildLegacyFileTypeWarning = buildLegacyFileTypeWarning; + exports2.buildMissingFileNameWarning = buildMissingFileNameWarning; + exports2.buildMissingExtensionWarning = buildMissingExtensionWarning; + exports2.buildLegacyMethodWarning = buildLegacyMethodWarning; + exports2.buildGeneralFilesUploadWarning = buildGeneralFilesUploadWarning; + exports2.buildFilesUploadMissingMessage = buildFilesUploadMissingMessage; + exports2.buildChannelsWarning = buildChannelsWarning; + exports2.buildMultipleChannelsErrorMsg = buildMultipleChannelsErrorMsg; + exports2.buildInvalidFilesUploadParamError = buildInvalidFilesUploadParamError; + var node_fs_1 = __require("node:fs"); + var node_stream_1 = __require("node:stream"); + var errors_1 = require_errors3(); + function getFileUploadJob(options, logger) { + return __awaiter(this, void 0, void 0, function* () { + var _a2, _b, _c2, _d2; + warnIfLegacyFileType(options, logger); + warnIfChannels(options, logger); + errorIfChannelsCsv(options); + const fileName = warnIfMissingOrInvalidFileNameAndDefault(options, logger); + const fileData = yield getFileData(options); + const fileDataBytesLength = getFileDataLength(fileData); + const fileUploadJob = { + // supplied by user + alt_text: options.alt_text, + channel_id: (_a2 = options.channels) !== null && _a2 !== void 0 ? _a2 : options.channel_id, + filename: (_b = options.filename) !== null && _b !== void 0 ? _b : fileName, + initial_comment: options.initial_comment, + snippet_type: options.snippet_type, + title: (_d2 = (_c2 = options.title) !== null && _c2 !== void 0 ? _c2 : options.filename) !== null && _d2 !== void 0 ? _d2 : fileName, + // default title to filename unless otherwise specified + // calculated + data: fileData, + length: fileDataBytesLength + }; + if ("thread_ts" in options) { + fileUploadJob.thread_ts = options.thread_ts; + } + if ("token" in options) { + fileUploadJob.token = options.token; + } + if ("content" in options) { + return Object.assign({ content: options.content }, fileUploadJob); + } + if ("file" in options) { + return Object.assign({ file: options.file }, fileUploadJob); + } + throw (0, errors_1.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + }); } - function No(e) { - let t = (() => { - if ($o(e)) return e; - let r = e.split("."); - return r[1] = "0", r.join("."); - })(); - if (_u.includes(t)) return t; + function getMultipleFileUploadJobs(options, logger) { + return __awaiter(this, void 0, void 0, function* () { + if ("file_uploads" in options) { + return Promise.all(options.file_uploads.map((upload) => { + const { channel_id, channels, initial_comment, thread_ts } = upload; + if (channel_id || channels || initial_comment || thread_ts) { + throw (0, errors_1.errorWithCode)(new Error(buildInvalidFilesUploadParamError()), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } + const uploadJobArgs = Object.assign(Object.assign({}, upload), { channels: options.channels, channel_id: options.channel_id, initial_comment: options.initial_comment }); + if ("thread_ts" in options) { + uploadJobArgs.thread_ts = options.thread_ts; + } + if ("token" in options) { + uploadJobArgs.token = options.token; + } + if ("content" in upload) { + return getFileUploadJob(Object.assign({ content: upload.content }, uploadJobArgs), logger); + } + if ("file" in upload) { + return getFileUploadJob(Object.assign({ file: upload.file }, uploadJobArgs), logger); + } + throw (0, errors_1.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You must supply one"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + })); + } + throw new Error(buildFilesUploadMissingMessage()); + }); } - function Mu(e) { - return mt(e).with({ familyDistro: "musl" }, () => (te('Trying platform-specific paths for "alpine"'), ["/lib"])).with({ familyDistro: "debian" }, ({ archFromUname: t }) => (te('Trying platform-specific paths for "debian" (and "ubuntu")'), [`/usr/lib/${t}-linux-gnu`, `/lib/${t}-linux-gnu`])).with({ familyDistro: "rhel" }, () => (te('Trying platform-specific paths for "rhel"'), ["/lib64", "/usr/lib64"])).otherwise(({ familyDistro: t, arch: r, archFromUname: n }) => (te(`Don't know any platform-specific paths for "${t}" on ${r} (${n})`), [])); + function getFileData(options) { + return __awaiter(this, void 0, void 0, function* () { + errorIfInvalidOrMissingFileData(options); + if ("file" in options) { + const { file } = options; + if (Buffer.isBuffer(file)) + return file; + if (typeof file === "string") { + try { + const dataBuffer = (0, node_fs_1.readFileSync)(file); + return dataBuffer; + } catch (error) { + throw (0, errors_1.errorWithCode)(new Error(`Unable to resolve file data for ${file}. Please supply a filepath string, or binary data Buffer or String directly.`), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } + } + const data = yield getFileDataAsStream(file); + if (data) + return data; + } + if ("content" in options) + return Buffer.from(options.content); + throw (0, errors_1.errorWithCode)(new Error("There was an issue getting the file data for the file or content supplied"), errors_1.ErrorCode.FileUploadReadFileDataError); + }); } - async function $u(e) { - let t = 'grep -v "libssl.so.0"', r = await Do(e); - if (r) { - te(`Found libssl.so file using platform-specific paths: ${r}`); - let o = ko(r); - if (te(`The parsed libssl version is: ${o}`), o) return { libssl: o, strategy: "libssl-specific-path" }; - } - te('Falling back to "ldconfig" and other generic paths'); - let n = await Qr(`ldconfig -p | sed "s/.*=>s*//" | sed "s|.*/||" | grep libssl | sort | ${t}`); - if (n || (n = await Do(["/lib64", "/usr/lib64", "/lib"])), n) { - te(`Found libssl.so file using "ldconfig" or other generic paths: ${n}`); - let o = ko(n); - if (te(`The parsed libssl version is: ${o}`), o) return { libssl: o, strategy: "ldconfig" }; - } - let i = await Qr("openssl version -v"); - if (i) { - te(`Found openssl binary with version: ${i}`); - let o = Nu(i); - if (te(`The parsed openssl version is: ${o}`), o) return { libssl: o, strategy: "openssl-binary" }; + function getFileDataLength(data) { + if (data) { + return Buffer.byteLength(data, "utf8"); } - return te("Couldn't find any version of libssl or OpenSSL in the system"), {}; + throw (0, errors_1.errorWithCode)(new Error(buildFileSizeErrorMsg()), errors_1.ErrorCode.FileUploadReadFileDataError); } - async function Do(e) { - for (let t of e) { - let r = await qu(t); - if (r) return r; - } + function getFileDataAsStream(readable) { + return __awaiter(this, void 0, void 0, function* () { + const chunks = []; + return new Promise((resolve, reject) => { + readable.on("readable", () => { + let chunk = readable.read(); + while (chunk !== null) { + chunks.push(chunk); + chunk = readable.read(); + } + }); + readable.on("end", () => { + if (chunks.length > 0) { + const content = Buffer.concat(chunks); + resolve(content); + } else { + reject(Error("No data in supplied file")); + } + }); + }); + }); } - async function qu(e) { - try { - return (await zn.default.readdir(e)).find((r) => r.startsWith("libssl.so.") && !r.startsWith("libssl.so.0")); - } catch (t) { - if (t.code === "ENOENT") return; - throw t; + function getAllFileUploadsToComplete(fileUploads) { + const toComplete = {}; + for (const upload of fileUploads) { + const { channel_id, thread_ts, initial_comment, file_id, title } = upload; + if (file_id) { + const compareString = `:::${channel_id}:::${thread_ts}:::${initial_comment}`; + if (!Object.prototype.hasOwnProperty.call(toComplete, compareString)) { + toComplete[compareString] = { + files: [{ id: file_id, title }], + channel_id, + initial_comment + }; + if (thread_ts && channel_id) { + const fileThreadDestinationArgument = { + channel_id, + thread_ts + }; + toComplete[compareString] = Object.assign(Object.assign({}, toComplete[compareString]), fileThreadDestinationArgument); + } + if ("token" in upload) { + toComplete[compareString].token = upload.token; + } + } else { + toComplete[compareString].files.push({ + id: file_id, + title + }); + } + } else { + throw new Error(buildMissingFileIdError()); + } } + return toComplete; } - async function nt() { - let { binaryTarget: e } = await Mo(); - return e; - } - function ju(e) { - return e.binaryTarget !== void 0; + function warnIfNotUsingFilesUploadV2(method, logger) { + const targetMethods = ["files.upload"]; + const isTargetMethod = targetMethods.includes(method); + if (method === "files.upload") + logger.warn(buildLegacyMethodWarning(method)); + if (isTargetMethod) + logger.info(buildGeneralFilesUploadWarning()); } - async function Yn() { - let { memoized: e, ...t } = await Mo(); - return t; + function warnIfChannels(options, logger) { + if (options.channels) + logger.warn(buildChannelsWarning()); } - var Ur = {}; - async function Mo() { - if (ju(Ur)) return Promise.resolve({ ...Ur, memoized: true }); - let e = await Lo(), t = Vu(e); - return Ur = { ...e, binaryTarget: t }, { ...Ur, memoized: false }; + function errorIfChannelsCsv(options) { + const channels = options.channels ? options.channels.split(",") : []; + if (channels.length > 1) { + throw (0, errors_1.errorWithCode)(new Error(buildMultipleChannelsErrorMsg()), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } } - function Vu(e) { - let { platform: t, arch: r, archFromUname: n, libssl: i, targetDistro: o, familyDistro: s, originalDistro: a } = e; - t === "linux" && !["x64", "arm64"].includes(r) && Br(`Prisma only officially supports Linux on amd64 (x86_64) and arm64 (aarch64) system architectures (detected "${r}" instead). If you are using your own custom Prisma engines, you can ignore this warning, as long as you've compiled the engines for your system architecture "${n}".`); - let l = "1.1.x"; - if (t === "linux" && i === void 0) { - let c = mt({ familyDistro: s }).with({ familyDistro: "debian" }, () => "Please manually install OpenSSL via `apt-get update -y && apt-get install -y openssl` and try installing Prisma again. If you're running Prisma on Docker, add this command to your Dockerfile, or switch to an image that already has OpenSSL installed.").otherwise(() => "Please manually install OpenSSL and try installing Prisma again."); - Br(`Prisma failed to detect the libssl/openssl version to use, and may not work as expected. Defaulting to "openssl-${l}". -${c}`); + function errorIfInvalidOrMissingFileData(options) { + const hasFile = "file" in options; + const hasContent = "content" in options; + if (!(hasFile || hasContent) || hasFile && hasContent) { + throw (0, errors_1.errorWithCode)(new Error("Either a file or content field is required for valid file upload. You cannot supply both"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); } - let u = "debian"; - if (t === "linux" && o === void 0 && te(`Distro is "${a}". Falling back to Prisma engines built for "${u}".`), t === "darwin" && r === "arm64") return "darwin-arm64"; - if (t === "darwin") return "darwin"; - if (t === "win32") return "windows"; - if (t === "freebsd") return o; - if (t === "openbsd") return "openbsd"; - if (t === "netbsd") return "netbsd"; - if (t === "linux" && o === "nixos") return "linux-nixos"; - if (t === "linux" && r === "arm64") return `${o === "musl" ? "linux-musl-arm64" : "linux-arm64"}-openssl-${i || l}`; - if (t === "linux" && r === "arm") return `linux-arm-openssl-${i || l}`; - if (t === "linux" && o === "musl") { - let c = "linux-musl"; - return !i || $o(i) ? c : `${c}-openssl-${i}`; + if ("file" in options) { + const { file } = options; + if (file && !(typeof file === "string" || Buffer.isBuffer(file) || file instanceof node_stream_1.Readable)) { + throw (0, errors_1.errorWithCode)(new Error("file must be a valid string path, buffer or Readable"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); + } } - return t === "linux" && o && i ? `${o}-openssl-${i}` : (t !== "linux" && Br(`Prisma detected unknown OS "${t}" and may not work as expected. Defaulting to "linux".`), i ? `${u}-openssl-${i}` : o ? `${o}-openssl-${l}` : `${u}-openssl-${l}`); - } - async function Bu(e) { - try { - return await e(); - } catch { - return; + if ("content" in options && options.content && typeof options.content !== "string") { + throw (0, errors_1.errorWithCode)(new Error("content must be a string"), errors_1.ErrorCode.FileUploadInvalidArgumentsError); } } - function Qr(e) { - return Bu(async () => { - let t = await Du(e); - return te(`Command "${e}" successfully returned "${t.stdout}"`), t.stdout; - }); - } - async function Uu() { - return typeof Gr.default.machine == "function" ? Gr.default.machine() : (await Qr("uname -m"))?.trim(); - } - function $o(e) { - return e.startsWith("1."); - } - var zo = k(Ko()); - function ii(e) { - return (0, zo.default)(e, e, { fallback: X }); - } - var Ku = k(si()); - var $ = k(__require("path")); - var zu = k(si()); - var Lf = L("prisma:engines"); - function Yo() { - return $.default.join(__dirname, "../"); - } - var Nf = "libquery-engine"; - $.default.join(__dirname, "../query-engine-darwin"); - $.default.join(__dirname, "../query-engine-darwin-arm64"); - $.default.join(__dirname, "../query-engine-debian-openssl-1.0.x"); - $.default.join(__dirname, "../query-engine-debian-openssl-1.1.x"); - $.default.join(__dirname, "../query-engine-debian-openssl-3.0.x"); - $.default.join(__dirname, "../query-engine-linux-static-x64"); - $.default.join(__dirname, "../query-engine-linux-static-arm64"); - $.default.join(__dirname, "../query-engine-rhel-openssl-1.0.x"); - $.default.join(__dirname, "../query-engine-rhel-openssl-1.1.x"); - $.default.join(__dirname, "../query-engine-rhel-openssl-3.0.x"); - $.default.join(__dirname, "../libquery_engine-darwin.dylib.node"); - $.default.join(__dirname, "../libquery_engine-darwin-arm64.dylib.node"); - $.default.join(__dirname, "../libquery_engine-debian-openssl-1.0.x.so.node"); - $.default.join(__dirname, "../libquery_engine-debian-openssl-1.1.x.so.node"); - $.default.join(__dirname, "../libquery_engine-debian-openssl-3.0.x.so.node"); - $.default.join(__dirname, "../libquery_engine-linux-arm64-openssl-1.0.x.so.node"); - $.default.join(__dirname, "../libquery_engine-linux-arm64-openssl-1.1.x.so.node"); - $.default.join(__dirname, "../libquery_engine-linux-arm64-openssl-3.0.x.so.node"); - $.default.join(__dirname, "../libquery_engine-linux-musl.so.node"); - $.default.join(__dirname, "../libquery_engine-linux-musl-openssl-3.0.x.so.node"); - $.default.join(__dirname, "../libquery_engine-rhel-openssl-1.0.x.so.node"); - $.default.join(__dirname, "../libquery_engine-rhel-openssl-1.1.x.so.node"); - $.default.join(__dirname, "../libquery_engine-rhel-openssl-3.0.x.so.node"); - $.default.join(__dirname, "../query_engine-windows.dll.node"); - var ai = k(__require("fs")); - var Zo = L("chmodPlusX"); - function li(e) { - if (process.platform === "win32") return; - let t = ai.default.statSync(e), r = t.mode | 64 | 8 | 1; - if (t.mode === r) { - Zo(`Execution permissions of ${e} are fine`); - return; + function warnIfMissingOrInvalidFileNameAndDefault(options, logger) { + var _a2; + const DEFAULT_FILETYPE = "txt"; + const DEFAULT_FILENAME = `file.${(_a2 = options.filetype) !== null && _a2 !== void 0 ? _a2 : DEFAULT_FILETYPE}`; + const { filename } = options; + if (!filename) { + logger.warn(buildMissingFileNameWarning()); + return DEFAULT_FILENAME; } - let n = r.toString(8).slice(-3); - Zo(`Have to call chmodPlusX on ${e}`), ai.default.chmodSync(e, n); - } - function ui(e) { - let t = e.e, r = (a) => `Prisma cannot find the required \`${a}\` system library in your system`, n = t.message.includes("cannot open shared object file"), i = `Please refer to the documentation about Prisma's system requirements: ${ii("https://pris.ly/d/system-requirements")}`, o = `Unable to require(\`${Oe(e.id)}\`).`, s = mt({ message: t.message, code: t.code }).with({ code: "ENOENT" }, () => "File does not exist.").when(({ message: a }) => n && a.includes("libz"), () => `${r("libz")}. Please install it and try again.`).when(({ message: a }) => n && a.includes("libgcc_s"), () => `${r("libgcc_s")}. Please install it and try again.`).when(({ message: a }) => n && a.includes("libssl"), () => { - let a = e.platformInfo.libssl ? `openssl-${e.platformInfo.libssl}` : "openssl"; - return `${r("libssl")}. Please install ${a} and try again.`; - }).when(({ message: a }) => a.includes("GLIBC"), () => `Prisma has detected an incompatible version of the \`glibc\` C standard library installed in your system. This probably means your system may be too old to run Prisma. ${i}`).when(({ message: a }) => e.platformInfo.platform === "linux" && a.includes("symbol not found"), () => `The Prisma engines are not compatible with your system ${e.platformInfo.originalDistro} on (${e.platformInfo.archFromUname}) which uses the \`${e.platformInfo.binaryTarget}\` binaryTarget by default. ${i}`).otherwise(() => `The Prisma engines do not seem to be compatible with your system. ${i}`); - return `${o} -${s} - -Details: ${t.message}`; - } - var di = k(ts()); - var zr = k(__require("fs")); - var ht = k(__require("path")); - function rs(e) { - let t = e.ignoreProcessEnv ? {} : process.env, r = (n) => n.match(/(.?\${(?:[a-zA-Z0-9_]+)?})/g)?.reduce(function(o, s) { - let a = /(.?)\${([a-zA-Z0-9_]+)?}/g.exec(s); - if (!a) return o; - let l = a[1], u, c; - if (l === "\\") c = a[0], u = c.replace("\\$", "$"); - else { - let p = a[2]; - c = a[0].substring(l.length), u = Object.hasOwnProperty.call(t, p) ? t[p] : e.parsed[p] || "", u = r(u); - } - return o.replace(c, u); - }, n) ?? n; - for (let n in e.parsed) { - let i = Object.hasOwnProperty.call(t, n) ? t[n] : e.parsed[n]; - e.parsed[n] = r(i); + if (filename.split(".").length < 2) { + logger.warn(buildMissingExtensionWarning(filename)); } - for (let n in e.parsed) t[n] = e.parsed[n]; - return e; - } - var pi = L("prisma:tryLoadEnv"); - function zt({ rootEnvPath: e, schemaEnvPath: t }, r = { conflictCheck: "none" }) { - let n = ns(e); - r.conflictCheck !== "none" && sc(n, t, r.conflictCheck); - let i = null; - return is(n?.path, t) || (i = ns(t)), !n && !i && pi("No Environment variables loaded"), i?.dotenvResult.error ? console.error(ce(H("Schema Env Error: ")) + i.dotenvResult.error) : { message: [n?.message, i?.message].filter(Boolean).join(` -`), parsed: { ...n?.dotenvResult?.parsed, ...i?.dotenvResult?.parsed } }; + return filename; } - function sc(e, t, r) { - let n = e?.dotenvResult.parsed, i = !is(e?.path, t); - if (n && t && i && zr.default.existsSync(t)) { - let o = di.default.parse(zr.default.readFileSync(t)), s = []; - for (let a in o) n[a] === o[a] && s.push(a); - if (s.length > 0) { - let a = ht.default.relative(process.cwd(), e.path), l = ht.default.relative(process.cwd(), t); - if (r === "error") { - let u = `There is a conflict between env var${s.length > 1 ? "s" : ""} in ${X(a)} and ${X(l)} -Conflicting env vars: -${s.map((c) => ` ${H(c)}`).join(` -`)} - -We suggest to move the contents of ${X(l)} to ${X(a)} to consolidate your env vars. -`; - throw new Error(u); - } else if (r === "warn") { - let u = `Conflict for env var${s.length > 1 ? "s" : ""} ${s.map((c) => H(c)).join(", ")} in ${X(a)} and ${X(l)} -Env vars from ${X(l)} overwrite the ones from ${X(a)} - `; - console.warn(`${ke("warn(prisma)")} ${u}`); - } - } + function warnIfLegacyFileType(options, logger) { + if (options.filetype) { + logger.warn(buildLegacyFileTypeWarning()); } } - function ns(e) { - if (ac(e)) { - pi(`Environment variables loaded from ${e}`); - let t = di.default.config({ path: e, debug: process.env.DOTENV_CONFIG_DEBUG ? true : void 0 }); - return { dotenvResult: rs(t), message: Oe(`Environment variables loaded from ${ht.default.relative(process.cwd(), e)}`), path: e }; - } else pi(`Environment variables not found at ${e}`); - return null; - } - function is(e, t) { - return e && t && ht.default.resolve(e) === ht.default.resolve(t); - } - function ac(e) { - return !!(e && zr.default.existsSync(e)); - } - var os = "library"; - function Yt(e) { - let t = lc(); - return t || (e?.config.engineType === "library" ? "library" : e?.config.engineType === "binary" ? "binary" : os); - } - function lc() { - let e = process.env.PRISMA_CLIENT_ENGINE_TYPE; - return e === "library" ? "library" : e === "binary" ? "binary" : void 0; - } - var Je; - ((t) => { - let e; - ((E) => (E.findUnique = "findUnique", E.findUniqueOrThrow = "findUniqueOrThrow", E.findFirst = "findFirst", E.findFirstOrThrow = "findFirstOrThrow", E.findMany = "findMany", E.create = "create", E.createMany = "createMany", E.createManyAndReturn = "createManyAndReturn", E.update = "update", E.updateMany = "updateMany", E.upsert = "upsert", E.delete = "delete", E.deleteMany = "deleteMany", E.groupBy = "groupBy", E.count = "count", E.aggregate = "aggregate", E.findRaw = "findRaw", E.aggregateRaw = "aggregateRaw"))(e = t.ModelAction ||= {}); - })(Je ||= {}); - var Zt = k(__require("path")); - function mi(e) { - return Zt.default.sep === Zt.default.posix.sep ? e : e.split(Zt.default.sep).join(Zt.default.posix.sep); - } - var ps = k(fi()); - function hi(e) { - return String(new gi(e)); + function buildMissingFileIdError() { + return "Missing required file id for file upload completion"; } - var gi = class { - constructor(t) { - this.config = t; - } - toString() { - let { config: t } = this, r = t.provider.fromEnvVar ? `env("${t.provider.fromEnvVar}")` : t.provider.value, n = JSON.parse(JSON.stringify({ provider: r, binaryTargets: cc(t.binaryTargets) })); - return `generator ${t.name} { -${(0, ps.default)(pc(n), 2)} -}`; - } - }; - function cc(e) { - let t; - if (e.length > 0) { - let r = e.find((n) => n.fromEnvVar !== null); - r ? t = `env("${r.fromEnvVar}")` : t = e.map((n) => n.native ? "native" : n.value); - } else t = void 0; - return t; + function buildFileSizeErrorMsg() { + return "There was an issue calculating the size of your file"; } - function pc(e) { - let t = Object.keys(e).reduce((r, n) => Math.max(r, n.length), 0); - return Object.entries(e).map(([r, n]) => `${r.padEnd(t)} = ${dc(n)}`).join(` -`); + function buildLegacyFileTypeWarning() { + return "filetype is no longer a supported field in files.uploadV2. \nPlease remove this field. To indicate file type, please do so via the required filename property using the appropriate file extension, e.g. image.png, text.txt"; } - function dc(e) { - return JSON.parse(JSON.stringify(e, (t, r) => Array.isArray(r) ? `[${r.map((n) => JSON.stringify(n)).join(", ")}]` : JSON.stringify(r))); + function buildMissingFileNameWarning() { + return "filename is a required field for files.uploadV2. \n For backwards compatibility and ease of migration, defaulting the filename. For best experience and consistent unfurl behavior, you should set the filename property with correct file extension, e.g. image.png, text.txt"; } - var er = {}; - Ut(er, { error: () => gc, info: () => fc, log: () => mc, query: () => hc, should: () => ds, tags: () => Xt, warn: () => yi }); - var Xt = { error: ce("prisma:error"), warn: ke("prisma:warn"), info: De("prisma:info"), query: rt("prisma:query") }; - var ds = { warn: () => !process.env.PRISMA_DISABLE_WARNINGS }; - function mc(...e) { - console.log(...e); + function buildMissingExtensionWarning(filename) { + return `filename supplied '${filename}' may be missing a proper extension. Missing extenions may result in unexpected unfurl behavior when shared`; } - function yi(e, ...t) { - ds.warn() && console.warn(`${Xt.warn} ${e}`, ...t); + function buildLegacyMethodWarning(method) { + return `${method} may cause some issues like timeouts for relatively large files.`; } - function fc(e, ...t) { - console.info(`${Xt.info} ${e}`, ...t); + function buildGeneralFilesUploadWarning() { + return "Our latest recommendation is to use client.files.uploadV2() method, which is mostly compatible and much stabler, instead."; } - function gc(e, ...t) { - console.error(`${Xt.error} ${e}`, ...t); + function buildFilesUploadMissingMessage() { + return "Something went wrong with processing file_uploads"; } - function hc(e, ...t) { - console.log(`${Xt.query} ${e}`, ...t); + function buildChannelsWarning() { + return "Although the 'channels' parameter is still supported for smoother migration from legacy files.upload, we recommend using the new channel_id parameter with a single str value instead (e.g. 'C12345')."; } - function Yr(e, t) { - if (!e) throw new Error(`${t}. This should never happen. If you see this error, please, open an issue at https://pris.ly/prisma-prisma-bug-report`); + function buildMultipleChannelsErrorMsg() { + return "Sharing files with multiple channels is no longer supported in v2. Share files in each channel separately instead."; } - function Fe(e, t) { - throw new Error(t); + function buildInvalidFilesUploadParamError() { + return "You may supply file_uploads only for a single channel, comment, thread respectively. Therefore, please supply any channel_id, initial_comment, thread_ts in the top-layer."; } - function Ei(e, t) { - return Object.prototype.hasOwnProperty.call(e, t); + } +}); + +// node_modules/@slack/web-api/dist/helpers.js +var require_helpers = __commonJS({ + "node_modules/@slack/web-api/dist/helpers.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.default = delay; + function delay(ms) { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); } - var wi = (e, t) => e.reduce((r, n) => (r[t(n)] = n, r), {}); - function yt(e, t) { - let r = {}; - for (let n of Object.keys(e)) r[n] = t(e[n], n); - return r; + } +}); + +// node_modules/@slack/web-api/package.json +var require_package3 = __commonJS({ + "node_modules/@slack/web-api/package.json"(exports2, module2) { + module2.exports = { + name: "@slack/web-api", + version: "7.9.2", + description: "Official library for using the Slack Platform's Web API", + author: "Slack Technologies, LLC", + license: "MIT", + keywords: ["slack", "web-api", "bot", "client", "http", "api", "proxy", "rate-limiting", "pagination"], + main: "dist/index.js", + types: "./dist/index.d.ts", + files: ["dist/**/*"], + engines: { + node: ">= 18", + npm: ">= 8.6.0" + }, + repository: "slackapi/node-slack-sdk", + homepage: "https://tools.slack.dev/node-slack-sdk/web-api", + publishConfig: { + access: "public" + }, + bugs: { + url: "https://github.com/slackapi/node-slack-sdk/issues" + }, + scripts: { + prepare: "npm run build", + build: "npm run build:clean && tsc", + "build:clean": "shx rm -rf ./dist ./coverage", + lint: "npx @biomejs/biome check .", + "lint:fix": "npx @biomejs/biome check --write .", + mocha: 'mocha --config ./test/.mocharc.json "./src/**/*.spec.ts"', + test: "npm run lint && npm run test:types && npm run test:integration && npm run test:unit", + "test:integration": "npm run build && node test/integration/commonjs-project/index.js && node test/integration/esm-project/index.mjs && npm run test:integration:ts", + "test:integration:ts": "cd test/integration/ts-4.7-project && npm i && npm run build", + "test:unit": "npm run build && c8 --config ./test/.c8rc.json npm run mocha", + "test:types": "tsd", + watch: "npx nodemon --watch 'src' --ext 'ts' --exec npm run build" + }, + dependencies: { + "@slack/logger": "^4.0.0", + "@slack/types": "^2.9.0", + "@types/node": ">=18.0.0", + "@types/retry": "0.12.0", + axios: "^1.8.3", + eventemitter3: "^5.0.1", + "form-data": "^4.0.0", + "is-electron": "2.2.2", + "is-stream": "^2", + "p-queue": "^6", + "p-retry": "^4", + retry: "^0.13.1" + }, + devDependencies: { + "@biomejs/biome": "^1.8.3", + "@tsconfig/recommended": "^1", + "@types/busboy": "^1.5.4", + "@types/chai": "^4", + "@types/mocha": "^10", + "@types/sinon": "^17", + busboy: "^1", + c8: "^10.1.2", + chai: "^4", + mocha: "^11", + "mocha-junit-reporter": "^2.2.1", + "mocha-multi-reporters": "^1.5.1", + nock: "^14", + shx: "^0.4.0", + sinon: "^20", + "source-map-support": "^0.5.21", + "ts-node": "^10", + tsd: "^0.32.0", + typescript: "5.8.3" + }, + tsd: { + directory: "test/types" + } + }; + } +}); + +// node_modules/@slack/web-api/dist/instrument.js +var require_instrument = __commonJS({ + "node_modules/@slack/web-api/dist/instrument.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; + } + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar2 = []; + for (var k2 in o2) if (Object.prototype.hasOwnProperty.call(o2, k2)) ar2[ar2.length] = k2; + return ar2; + }; + return ownKeys(o); + }; + return function(mod2) { + if (mod2 && mod2.__esModule) return mod2; + var result = {}; + if (mod2 != null) { + for (var k2 = ownKeys(mod2), i = 0; i < k2.length; i++) if (k2[i] !== "default") __createBinding(result, mod2, k2[i]); + } + __setModuleDefault(result, mod2); + return result; + }; + }(); + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.addAppMetadata = addAppMetadata; + exports2.getUserAgent = getUserAgent; + var os2 = __importStar(__require("node:os")); + var node_path_1 = __require("node:path"); + var packageJson = require_package3(); + function replaceSlashes(s) { + return s.replace("/", ":"); } - function xi(e, t) { - if (e.length === 0) return; - let r = e[0]; - for (let n = 1; n < e.length; n++) t(r, e[n]) < 0 && (r = e[n]); - return r; + var baseUserAgent = `${replaceSlashes(packageJson.name)}/${packageJson.version} ${(0, node_path_1.basename)(process.title)}/${process.version.replace("v", "")} ${os2.platform()}/${os2.release()}`; + var appMetadata = {}; + function addAppMetadata({ name, version: version4 }) { + appMetadata[replaceSlashes(name)] = version4; } - function w(e, t) { - Object.defineProperty(e, "name", { value: t, configurable: true }); + function getUserAgent() { + const appIdentifier = Object.entries(appMetadata).map(([name, version4]) => `${name}/${version4}`).join(" "); + return (appIdentifier.length > 0 ? `${appIdentifier} ` : "") + baseUserAgent; } - var ys = /* @__PURE__ */ new Set(); - var tr = (e, t, ...r) => { - ys.has(e) || (ys.add(e), yi(t, ...r)); - }; - var V = class extends Error { - constructor(t, { code: r, clientVersion: n, meta: i, batchRequestIdx: o }) { - super(t), this.name = "PrismaClientKnownRequestError", this.code = r, this.clientVersion = n, this.meta = i, Object.defineProperty(this, "batchRequestIdx", { value: o, enumerable: false, writable: true }); - } - get [Symbol.toStringTag]() { - return "PrismaClientKnownRequestError"; - } - }; - w(V, "PrismaClientKnownRequestError"); - var Le = class extends V { - constructor(t, r) { - super(t, { code: "P2025", clientVersion: r }), this.name = "NotFoundError"; + } +}); + +// node_modules/@slack/logger/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/@slack/logger/dist/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.ConsoleLogger = exports2.LogLevel = void 0; + var LogLevel; + (function(LogLevel2) { + LogLevel2["ERROR"] = "error"; + LogLevel2["WARN"] = "warn"; + LogLevel2["INFO"] = "info"; + LogLevel2["DEBUG"] = "debug"; + })(LogLevel = exports2.LogLevel || (exports2.LogLevel = {})); + var ConsoleLogger = class _ConsoleLogger { + constructor() { + this.level = LogLevel.INFO; + this.name = ""; } - }; - w(Le, "NotFoundError"); - var R = class e extends Error { - constructor(t, r, n) { - super(t), this.name = "PrismaClientInitializationError", this.clientVersion = r, this.errorCode = n, Error.captureStackTrace(e); + getLevel() { + return this.level; } - get [Symbol.toStringTag]() { - return "PrismaClientInitializationError"; + /** + * Sets the instance's log level so that only messages which are equal or more severe are output to the console. + */ + setLevel(level) { + this.level = level; } - }; - w(R, "PrismaClientInitializationError"); - var le = class extends Error { - constructor(t, r) { - super(t), this.name = "PrismaClientRustPanicError", this.clientVersion = r; + /** + * Set the instance's name, which will appear on each log line before the message. + */ + setName(name) { + this.name = name; } - get [Symbol.toStringTag]() { - return "PrismaClientRustPanicError"; + /** + * Log a debug message + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + debug(...msg) { + if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.DEBUG, this.level)) { + console.debug(_ConsoleLogger.labels.get(LogLevel.DEBUG), this.name, ...msg); + } } - }; - w(le, "PrismaClientRustPanicError"); - var B = class extends Error { - constructor(t, { clientVersion: r, batchRequestIdx: n }) { - super(t), this.name = "PrismaClientUnknownRequestError", this.clientVersion = r, Object.defineProperty(this, "batchRequestIdx", { value: n, writable: true, enumerable: false }); + /** + * Log an info message + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + info(...msg) { + if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.INFO, this.level)) { + console.info(_ConsoleLogger.labels.get(LogLevel.INFO), this.name, ...msg); + } } - get [Symbol.toStringTag]() { - return "PrismaClientUnknownRequestError"; + /** + * Log a warning message + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + warn(...msg) { + if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.WARN, this.level)) { + console.warn(_ConsoleLogger.labels.get(LogLevel.WARN), this.name, ...msg); + } } - }; - w(B, "PrismaClientUnknownRequestError"); - var J = class extends Error { - constructor(r, { clientVersion: n }) { - super(r); - this.name = "PrismaClientValidationError"; - this.clientVersion = n; + /** + * Log an error message + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error(...msg) { + if (_ConsoleLogger.isMoreOrEqualSevere(LogLevel.ERROR, this.level)) { + console.error(_ConsoleLogger.labels.get(LogLevel.ERROR), this.name, ...msg); + } } - get [Symbol.toStringTag]() { - return "PrismaClientValidationError"; + /** + * Helper to compare two log levels and determine if a is equal or more severe than b + */ + static isMoreOrEqualSevere(a, b2) { + return _ConsoleLogger.severity[a] >= _ConsoleLogger.severity[b2]; } }; - w(J, "PrismaClientValidationError"); - var bt = 9e15; - var ze = 1e9; - var Pi = "0123456789abcdef"; - var tn = "2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058"; - var rn = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789"; - var vi = { precision: 20, rounding: 4, modulo: 1, toExpNeg: -7, toExpPos: 21, minE: -bt, maxE: bt, crypto: false }; - var xs; - var Ne; - var x = true; - var on = "[DecimalError] "; - var Ke = on + "Invalid argument: "; - var Ps = on + "Precision limit exceeded"; - var vs = on + "crypto unavailable"; - var Ts = "[object Decimal]"; - var ee = Math.floor; - var G = Math.pow; - var bc = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i; - var Ec = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i; - var wc = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i; - var Rs = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i; - var ge = 1e7; - var b = 7; - var xc = 9007199254740991; - var Pc = tn.length - 1; - var Ti = rn.length - 1; - var m = { toStringTag: Ts }; - m.absoluteValue = m.abs = function() { - var e = new this.constructor(this); - return e.s < 0 && (e.s = 1), y(e); - }; - m.ceil = function() { - return y(new this.constructor(this), this.e + 1, 2); - }; - m.clampedTo = m.clamp = function(e, t) { - var r, n = this, i = n.constructor; - if (e = new i(e), t = new i(t), !e.s || !t.s) return new i(NaN); - if (e.gt(t)) throw Error(Ke + t); - return r = n.cmp(e), r < 0 ? e : n.cmp(t) > 0 ? t : new i(n); - }; - m.comparedTo = m.cmp = function(e) { - var t, r, n, i, o = this, s = o.d, a = (e = new o.constructor(e)).d, l = o.s, u = e.s; - if (!s || !a) return !l || !u ? NaN : l !== u ? l : s === a ? 0 : !s ^ l < 0 ? 1 : -1; - if (!s[0] || !a[0]) return s[0] ? l : a[0] ? -u : 0; - if (l !== u) return l; - if (o.e !== e.e) return o.e > e.e ^ l < 0 ? 1 : -1; - for (n = s.length, i = a.length, t = 0, r = n < i ? n : i; t < r; ++t) if (s[t] !== a[t]) return s[t] > a[t] ^ l < 0 ? 1 : -1; - return n === i ? 0 : n > i ^ l < 0 ? 1 : -1; - }; - m.cosine = m.cos = function() { - var e, t, r = this, n = r.constructor; - return r.d ? r.d[0] ? (e = n.precision, t = n.rounding, n.precision = e + Math.max(r.e, r.sd()) + b, n.rounding = 1, r = vc(n, Os(n, r)), n.precision = e, n.rounding = t, y(Ne == 2 || Ne == 3 ? r.neg() : r, e, t, true)) : new n(1) : new n(NaN); + exports2.ConsoleLogger = ConsoleLogger; + ConsoleLogger.labels = (() => { + const entries = Object.entries(LogLevel); + const map = entries.map(([key, value]) => [value, `[${key}] `]); + return new Map(map); + })(); + ConsoleLogger.severity = { + [LogLevel.ERROR]: 400, + [LogLevel.WARN]: 300, + [LogLevel.INFO]: 200, + [LogLevel.DEBUG]: 100 }; - m.cubeRoot = m.cbrt = function() { - var e, t, r, n, i, o, s, a, l, u, c = this, p = c.constructor; - if (!c.isFinite() || c.isZero()) return new p(c); - for (x = false, o = c.s * G(c.s * c, 1 / 3), !o || Math.abs(o) == 1 / 0 ? (r = K(c.d), e = c.e, (o = (e - r.length + 1) % 3) && (r += o == 1 || o == -2 ? "0" : "00"), o = G(r, 1 / 3), e = ee((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)), o == 1 / 0 ? r = "5e" + e : (r = o.toExponential(), r = r.slice(0, r.indexOf("e") + 1) + e), n = new p(r), n.s = c.s) : n = new p(o.toString()), s = (e = p.precision) + 3; ; ) if (a = n, l = a.times(a).times(a), u = l.plus(c), n = N(u.plus(c).times(a), u.plus(l), s + 2, 1), K(a.d).slice(0, s) === (r = K(n.d)).slice(0, s)) if (r = r.slice(s - 3, s + 1), r == "9999" || !i && r == "4999") { - if (!i && (y(a, e + 1, 0), a.times(a).times(a).eq(c))) { - n = a; - break; + } +}); + +// node_modules/@slack/web-api/dist/logger.js +var require_logger2 = __commonJS({ + "node_modules/@slack/web-api/dist/logger.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.LogLevel = void 0; + exports2.getLogger = getLogger; + var logger_1 = require_dist2(); + var logger_2 = require_dist2(); + Object.defineProperty(exports2, "LogLevel", { enumerable: true, get: function() { + return logger_2.LogLevel; + } }); + var instanceCount = 0; + function getLogger(name, level, existingLogger) { + const instanceId = instanceCount; + instanceCount += 1; + const logger = (() => { + if (existingLogger !== void 0) { + return existingLogger; } - s += 4, i = 1; - } else { - (!+r || !+r.slice(1) && r.charAt(0) == "5") && (y(n, e + 1, 1), t = !n.times(n).times(n).eq(c)); - break; + return new logger_1.ConsoleLogger(); + })(); + logger.setName(`web-api:${name}:${instanceId}`); + if (level !== void 0) { + logger.setLevel(level); } - return x = true, y(n, e, p.rounding, t); - }; - m.decimalPlaces = m.dp = function() { - var e, t = this.d, r = NaN; - if (t) { - if (e = t.length - 1, r = (e - ee(this.e / b)) * b, e = t[e], e) for (; e % 10 == 0; e /= 10) r--; - r < 0 && (r = 0); + return logger; + } + } +}); + +// node_modules/eventemitter3/index.js +var require_eventemitter32 = __commonJS({ + "node_modules/eventemitter3/index.js"(exports2, module2) { + "use strict"; + var has = Object.prototype.hasOwnProperty; + var prefix = "~"; + function Events() { + } + if (Object.create) { + Events.prototype = /* @__PURE__ */ Object.create(null); + if (!new Events().__proto__) prefix = false; + } + function EE(fn2, context, once) { + this.fn = fn2; + this.context = context; + this.once = once || false; + } + function addListener(emitter, event, fn2, context, once) { + if (typeof fn2 !== "function") { + throw new TypeError("The listener must be a function"); } - return r; - }; - m.dividedBy = m.div = function(e) { - return N(this, new this.constructor(e)); - }; - m.dividedToIntegerBy = m.divToInt = function(e) { - var t = this, r = t.constructor; - return y(N(t, new r(e), 0, 1, 1), r.precision, r.rounding); - }; - m.equals = m.eq = function(e) { - return this.cmp(e) === 0; - }; - m.floor = function() { - return y(new this.constructor(this), this.e + 1, 3); - }; - m.greaterThan = m.gt = function(e) { - return this.cmp(e) > 0; - }; - m.greaterThanOrEqualTo = m.gte = function(e) { - var t = this.cmp(e); - return t == 1 || t === 0; - }; - m.hyperbolicCosine = m.cosh = function() { - var e, t, r, n, i, o = this, s = o.constructor, a = new s(1); - if (!o.isFinite()) return new s(o.s ? 1 / 0 : NaN); - if (o.isZero()) return a; - r = s.precision, n = s.rounding, s.precision = r + Math.max(o.e, o.sd()) + 4, s.rounding = 1, i = o.d.length, i < 32 ? (e = Math.ceil(i / 3), t = (1 / an(4, e)).toString()) : (e = 16, t = "2.3283064365386962890625e-10"), o = Et(s, 1, o.times(t), new s(1), true); - for (var l, u = e, c = new s(8); u--; ) l = o.times(o), o = a.minus(l.times(c.minus(l.times(c)))); - return y(o, s.precision = r, s.rounding = n, true); - }; - m.hyperbolicSine = m.sinh = function() { - var e, t, r, n, i = this, o = i.constructor; - if (!i.isFinite() || i.isZero()) return new o(i); - if (t = o.precision, r = o.rounding, o.precision = t + Math.max(i.e, i.sd()) + 4, o.rounding = 1, n = i.d.length, n < 3) i = Et(o, 2, i, i, true); - else { - e = 1.4 * Math.sqrt(n), e = e > 16 ? 16 : e | 0, i = i.times(1 / an(5, e)), i = Et(o, 2, i, i, true); - for (var s, a = new o(5), l = new o(16), u = new o(20); e--; ) s = i.times(i), i = i.times(a.plus(s.times(l.times(s).plus(u)))); + var listener = new EE(fn2, context || emitter, once), evt = prefix ? prefix + event : event; + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + return emitter; + } + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + function EventEmitter3() { + this._events = new Events(); + this._eventsCount = 0; + } + EventEmitter3.prototype.eventNames = function eventNames() { + var names = [], events, name; + if (this._eventsCount === 0) return names; + for (name in events = this._events) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } - return o.precision = t, o.rounding = r, y(i, t, r, true); - }; - m.hyperbolicTangent = m.tanh = function() { - var e, t, r = this, n = r.constructor; - return r.isFinite() ? r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + 7, n.rounding = 1, N(r.sinh(), r.cosh(), n.precision = e, n.rounding = t)) : new n(r.s); - }; - m.inverseCosine = m.acos = function() { - var e, t = this, r = t.constructor, n = t.abs().cmp(1), i = r.precision, o = r.rounding; - return n !== -1 ? n === 0 ? t.isNeg() ? fe(r, i, o) : new r(0) : new r(NaN) : t.isZero() ? fe(r, i + 4, o).times(0.5) : (r.precision = i + 6, r.rounding = 1, t = t.asin(), e = fe(r, i + 4, o).times(0.5), r.precision = i, r.rounding = o, e.minus(t)); - }; - m.inverseHyperbolicCosine = m.acosh = function() { - var e, t, r = this, n = r.constructor; - return r.lte(1) ? new n(r.eq(1) ? 0 : NaN) : r.isFinite() ? (e = n.precision, t = n.rounding, n.precision = e + Math.max(Math.abs(r.e), r.sd()) + 4, n.rounding = 1, x = false, r = r.times(r).minus(1).sqrt().plus(r), x = true, n.precision = e, n.rounding = t, r.ln()) : new n(r); - }; - m.inverseHyperbolicSine = m.asinh = function() { - var e, t, r = this, n = r.constructor; - return !r.isFinite() || r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + 2 * Math.max(Math.abs(r.e), r.sd()) + 6, n.rounding = 1, x = false, r = r.times(r).plus(1).sqrt().plus(r), x = true, n.precision = e, n.rounding = t, r.ln()); - }; - m.inverseHyperbolicTangent = m.atanh = function() { - var e, t, r, n, i = this, o = i.constructor; - return i.isFinite() ? i.e >= 0 ? new o(i.abs().eq(1) ? i.s / 0 : i.isZero() ? i : NaN) : (e = o.precision, t = o.rounding, n = i.sd(), Math.max(n, e) < 2 * -i.e - 1 ? y(new o(i), e, t, true) : (o.precision = r = n - i.e, i = N(i.plus(1), new o(1).minus(i), r + e, 1), o.precision = e + 4, o.rounding = 1, i = i.ln(), o.precision = e, o.rounding = t, i.times(0.5))) : new o(NaN); - }; - m.inverseSine = m.asin = function() { - var e, t, r, n, i = this, o = i.constructor; - return i.isZero() ? new o(i) : (t = i.abs().cmp(1), r = o.precision, n = o.rounding, t !== -1 ? t === 0 ? (e = fe(o, r + 4, n).times(0.5), e.s = i.s, e) : new o(NaN) : (o.precision = r + 6, o.rounding = 1, i = i.div(new o(1).minus(i.times(i)).sqrt().plus(1)).atan(), o.precision = r, o.rounding = n, i.times(2))); - }; - m.inverseTangent = m.atan = function() { - var e, t, r, n, i, o, s, a, l, u = this, c = u.constructor, p = c.precision, d = c.rounding; - if (u.isFinite()) { - if (u.isZero()) return new c(u); - if (u.abs().eq(1) && p + 4 <= Ti) return s = fe(c, p + 4, d).times(0.25), s.s = u.s, s; - } else { - if (!u.s) return new c(NaN); - if (p + 4 <= Ti) return s = fe(c, p + 4, d).times(0.5), s.s = u.s, s; + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); } - for (c.precision = a = p + 10, c.rounding = 1, r = Math.min(28, a / b + 2 | 0), e = r; e; --e) u = u.div(u.times(u).plus(1).sqrt().plus(1)); - for (x = false, t = Math.ceil(a / b), n = 1, l = u.times(u), s = new c(u), i = u; e !== -1; ) if (i = i.times(l), o = s.minus(i.div(n += 2)), i = i.times(l), s = o.plus(i.div(n += 2)), s.d[t] !== void 0) for (e = t; s.d[e] === o.d[e] && e--; ) ; - return r && (s = s.times(2 << r - 1)), x = true, y(s, c.precision = p, c.rounding = d, true); - }; - m.isFinite = function() { - return !!this.d; - }; - m.isInteger = m.isInt = function() { - return !!this.d && ee(this.e / b) > this.d.length - 2; - }; - m.isNaN = function() { - return !this.s; - }; - m.isNegative = m.isNeg = function() { - return this.s < 0; - }; - m.isPositive = m.isPos = function() { - return this.s > 0; - }; - m.isZero = function() { - return !!this.d && this.d[0] === 0; - }; - m.lessThan = m.lt = function(e) { - return this.cmp(e) < 0; - }; - m.lessThanOrEqualTo = m.lte = function(e) { - return this.cmp(e) < 1; + return names; }; - m.logarithm = m.log = function(e) { - var t, r, n, i, o, s, a, l, u = this, c = u.constructor, p = c.precision, d = c.rounding, f = 5; - if (e == null) e = new c(10), t = true; - else { - if (e = new c(e), r = e.d, e.s < 0 || !r || !r[0] || e.eq(1)) return new c(NaN); - t = e.eq(10); - } - if (r = u.d, u.s < 0 || !r || !r[0] || u.eq(1)) return new c(r && !r[0] ? -1 / 0 : u.s != 1 ? NaN : r ? 0 : 1 / 0); - if (t) if (r.length > 1) o = true; - else { - for (i = r[0]; i % 10 === 0; ) i /= 10; - o = i !== 1; + EventEmitter3.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event, handlers = this._events[evt]; + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + for (var i = 0, l = handlers.length, ee2 = new Array(l); i < l; i++) { + ee2[i] = handlers[i].fn; } - if (x = false, a = p + f, s = He(u, a), n = t ? nn(c, a + 10) : He(e, a), l = N(s, n, a, 1), rr(l.d, i = p, d)) do - if (a += 10, s = He(u, a), n = t ? nn(c, a + 10) : He(e, a), l = N(s, n, a, 1), !o) { - +K(l.d).slice(i + 1, i + 15) + 1 == 1e14 && (l = y(l, p + 1, 0)); - break; - } - while (rr(l.d, i += 10, d)); - return x = true, y(l, p, d); + return ee2; }; - m.minus = m.sub = function(e) { - var t, r, n, i, o, s, a, l, u, c, p, d, f = this, g = f.constructor; - if (e = new g(e), !f.d || !e.d) return !f.s || !e.s ? e = new g(NaN) : f.d ? e.s = -e.s : e = new g(e.d || f.s !== e.s ? f : NaN), e; - if (f.s != e.s) return e.s = -e.s, f.plus(e); - if (u = f.d, d = e.d, a = g.precision, l = g.rounding, !u[0] || !d[0]) { - if (d[0]) e.s = -e.s; - else if (u[0]) e = new g(f); - else return new g(l === 3 ? -0 : 0); - return x ? y(e, a, l) : e; - } - if (r = ee(e.e / b), c = ee(f.e / b), u = u.slice(), o = c - r, o) { - for (p = o < 0, p ? (t = u, o = -o, s = d.length) : (t = d, r = c, s = u.length), n = Math.max(Math.ceil(a / b), s) + 2, o > n && (o = n, t.length = 1), t.reverse(), n = o; n--; ) t.push(0); - t.reverse(); - } else { - for (n = u.length, s = d.length, p = n < s, p && (s = n), n = 0; n < s; n++) if (u[n] != d[n]) { - p = u[n] < d[n]; - break; + EventEmitter3.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event, listeners = this._events[evt]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + EventEmitter3.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return false; + var listeners = this._events[evt], len = arguments.length, args, i; + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); + switch (len) { + case 1: + return listeners.fn.call(listeners.context), true; + case 2: + return listeners.fn.call(listeners.context, a1), true; + case 3: + return listeners.fn.call(listeners.context, a1, a2), true; + case 4: + return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: + return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: + return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } - o = 0; - } - for (p && (t = u, u = d, d = t, e.s = -e.s), s = u.length, n = d.length - s; n > 0; --n) u[s++] = 0; - for (n = d.length; n > o; ) { - if (u[--n] < d[n]) { - for (i = n; i && u[--i] === 0; ) u[i] = ge - 1; - --u[i], u[n] += ge; + for (i = 1, args = new Array(len - 1); i < len; i++) { + args[i - 1] = arguments[i]; + } + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length, j2; + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); + switch (len) { + case 1: + listeners[i].fn.call(listeners[i].context); + break; + case 2: + listeners[i].fn.call(listeners[i].context, a1); + break; + case 3: + listeners[i].fn.call(listeners[i].context, a1, a2); + break; + case 4: + listeners[i].fn.call(listeners[i].context, a1, a2, a3); + break; + default: + if (!args) for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) { + args[j2 - 1] = arguments[j2]; + } + listeners[i].fn.apply(listeners[i].context, args); + } } - u[n] -= d[n]; } - for (; u[--s] === 0; ) u.pop(); - for (; u[0] === 0; u.shift()) --r; - return u[0] ? (e.d = u, e.e = sn(u, r), x ? y(e, a, l) : e) : new g(l === 3 ? -0 : 0); - }; - m.modulo = m.mod = function(e) { - var t, r = this, n = r.constructor; - return e = new n(e), !r.d || !e.s || e.d && !e.d[0] ? new n(NaN) : !e.d || r.d && !r.d[0] ? y(new n(r), n.precision, n.rounding) : (x = false, n.modulo == 9 ? (t = N(r, e.abs(), 0, 3, 1), t.s *= e.s) : t = N(r, e, 0, n.modulo, 1), t = t.times(e), x = true, r.minus(t)); - }; - m.naturalExponential = m.exp = function() { - return Ri(this); + return true; }; - m.naturalLogarithm = m.ln = function() { - return He(this); + EventEmitter3.prototype.on = function on2(event, fn2, context) { + return addListener(this, event, fn2, context, false); }; - m.negated = m.neg = function() { - var e = new this.constructor(this); - return e.s = -e.s, y(e); + EventEmitter3.prototype.once = function once(event, fn2, context) { + return addListener(this, event, fn2, context, true); }; - m.plus = m.add = function(e) { - var t, r, n, i, o, s, a, l, u, c, p = this, d = p.constructor; - if (e = new d(e), !p.d || !e.d) return !p.s || !e.s ? e = new d(NaN) : p.d || (e = new d(e.d || p.s === e.s ? p : NaN)), e; - if (p.s != e.s) return e.s = -e.s, p.minus(e); - if (u = p.d, c = e.d, a = d.precision, l = d.rounding, !u[0] || !c[0]) return c[0] || (e = new d(p)), x ? y(e, a, l) : e; - if (o = ee(p.e / b), n = ee(e.e / b), u = u.slice(), i = o - n, i) { - for (i < 0 ? (r = u, i = -i, s = c.length) : (r = c, n = o, s = u.length), o = Math.ceil(a / b), s = o > s ? o + 1 : s + 1, i > s && (i = s, r.length = 1), r.reverse(); i--; ) r.push(0); - r.reverse(); + EventEmitter3.prototype.removeListener = function removeListener(event, fn2, context, once) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return this; + if (!fn2) { + clearEvent(this, evt); + return this; } - for (s = u.length, i = c.length, s - i < 0 && (i = s, r = c, c = u, u = r), t = 0; i; ) t = (u[--i] = u[i] + c[i] + t) / ge | 0, u[i] %= ge; - for (t && (u.unshift(t), ++n), s = u.length; u[--s] == 0; ) u.pop(); - return e.d = u, e.e = sn(u, n), x ? y(e, a, l) : e; - }; - m.precision = m.sd = function(e) { - var t, r = this; - if (e !== void 0 && e !== !!e && e !== 1 && e !== 0) throw Error(Ke + e); - return r.d ? (t = Cs(r.d), e && r.e + 1 > t && (t = r.e + 1)) : t = NaN, t; - }; - m.round = function() { - var e = this, t = e.constructor; - return y(new t(e), e.e + 1, t.rounding); - }; - m.sine = m.sin = function() { - var e, t, r = this, n = r.constructor; - return r.isFinite() ? r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + Math.max(r.e, r.sd()) + b, n.rounding = 1, r = Rc(n, Os(n, r)), n.precision = e, n.rounding = t, y(Ne > 2 ? r.neg() : r, e, t, true)) : new n(NaN); - }; - m.squareRoot = m.sqrt = function() { - var e, t, r, n, i, o, s = this, a = s.d, l = s.e, u = s.s, c = s.constructor; - if (u !== 1 || !a || !a[0]) return new c(!u || u < 0 && (!a || a[0]) ? NaN : a ? s : 1 / 0); - for (x = false, u = Math.sqrt(+s), u == 0 || u == 1 / 0 ? (t = K(a), (t.length + l) % 2 == 0 && (t += "0"), u = Math.sqrt(t), l = ee((l + 1) / 2) - (l < 0 || l % 2), u == 1 / 0 ? t = "5e" + l : (t = u.toExponential(), t = t.slice(0, t.indexOf("e") + 1) + l), n = new c(t)) : n = new c(u.toString()), r = (l = c.precision) + 3; ; ) if (o = n, n = o.plus(N(s, o, r + 2, 1)).times(0.5), K(o.d).slice(0, r) === (t = K(n.d)).slice(0, r)) if (t = t.slice(r - 3, r + 1), t == "9999" || !i && t == "4999") { - if (!i && (y(o, l + 1, 0), o.times(o).eq(s))) { - n = o; - break; + var listeners = this._events[evt]; + if (listeners.fn) { + if (listeners.fn === fn2 && (!once || listeners.once) && (!context || listeners.context === context)) { + clearEvent(this, evt); } - r += 4, i = 1; } else { - (!+t || !+t.slice(1) && t.charAt(0) == "5") && (y(n, l + 1, 1), e = !n.times(n).eq(s)); - break; + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if (listeners[i].fn !== fn2 || once && !listeners[i].once || context && listeners[i].context !== context) { + events.push(listeners[i]); + } + } + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); } - return x = true, y(n, l, c.rounding, e); - }; - m.tangent = m.tan = function() { - var e, t, r = this, n = r.constructor; - return r.isFinite() ? r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + 10, n.rounding = 1, r = r.sin(), r.s = 1, r = N(r, new n(1).minus(r.times(r)).sqrt(), e + 10, 0), n.precision = e, n.rounding = t, y(Ne == 2 || Ne == 4 ? r.neg() : r, e, t, true)) : new n(NaN); + return this; }; - m.times = m.mul = function(e) { - var t, r, n, i, o, s, a, l, u, c = this, p = c.constructor, d = c.d, f = (e = new p(e)).d; - if (e.s *= c.s, !d || !d[0] || !f || !f[0]) return new p(!e.s || d && !d[0] && !f || f && !f[0] && !d ? NaN : !d || !f ? e.s / 0 : e.s * 0); - for (r = ee(c.e / b) + ee(e.e / b), l = d.length, u = f.length, l < u && (o = d, d = f, f = o, s = l, l = u, u = s), o = [], s = l + u, n = s; n--; ) o.push(0); - for (n = u; --n >= 0; ) { - for (t = 0, i = l + n; i > n; ) a = o[i] + f[n] * d[i - n - 1] + t, o[i--] = a % ge | 0, t = a / ge | 0; - o[i] = (o[i] + t) % ge | 0; + EventEmitter3.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; } - for (; !o[--s]; ) o.pop(); - return t ? ++r : o.shift(), e.d = o, e.e = sn(o, r), x ? y(e, p.precision, p.rounding) : e; - }; - m.toBinary = function(e, t) { - return Si(this, 2, e, t); - }; - m.toDecimalPlaces = m.toDP = function(e, t) { - var r = this, n = r.constructor; - return r = new n(r), e === void 0 ? r : (ie(e, 0, ze), t === void 0 ? t = n.rounding : ie(t, 0, 8), y(r, e + r.e + 1, t)); - }; - m.toExponential = function(e, t) { - var r, n = this, i = n.constructor; - return e === void 0 ? r = we(n, true) : (ie(e, 0, ze), t === void 0 ? t = i.rounding : ie(t, 0, 8), n = y(new i(n), e + 1, t), r = we(n, true, e + 1)), n.isNeg() && !n.isZero() ? "-" + r : r; - }; - m.toFixed = function(e, t) { - var r, n, i = this, o = i.constructor; - return e === void 0 ? r = we(i) : (ie(e, 0, ze), t === void 0 ? t = o.rounding : ie(t, 0, 8), n = y(new o(i), e + i.e + 1, t), r = we(n, false, e + n.e + 1)), i.isNeg() && !i.isZero() ? "-" + r : r; + return this; }; - m.toFraction = function(e) { - var t, r, n, i, o, s, a, l, u, c, p, d, f = this, g = f.d, h = f.constructor; - if (!g) return new h(f); - if (u = r = new h(1), n = l = new h(0), t = new h(n), o = t.e = Cs(g) - f.e - 1, s = o % b, t.d[0] = G(10, s < 0 ? b + s : s), e == null) e = o > 0 ? t : u; - else { - if (a = new h(e), !a.isInt() || a.lt(u)) throw Error(Ke + a); - e = a.gt(t) ? o > 0 ? t : u : a; + EventEmitter3.prototype.off = EventEmitter3.prototype.removeListener; + EventEmitter3.prototype.addListener = EventEmitter3.prototype.on; + EventEmitter3.prefixed = prefix; + EventEmitter3.EventEmitter = EventEmitter3; + if ("undefined" !== typeof module2) { + module2.exports = EventEmitter3; + } + } +}); + +// node_modules/@slack/types/dist/calls.js +var require_calls = __commonJS({ + "node_modules/@slack/types/dist/calls.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/dialog.js +var require_dialog = __commonJS({ + "node_modules/@slack/types/dist/dialog.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/app.js +var require_app = __commonJS({ + "node_modules/@slack/types/dist/events/app.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/assistant.js +var require_assistant = __commonJS({ + "node_modules/@slack/types/dist/events/assistant.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/call.js +var require_call = __commonJS({ + "node_modules/@slack/types/dist/events/call.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/channel.js +var require_channel = __commonJS({ + "node_modules/@slack/types/dist/events/channel.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/dnd.js +var require_dnd = __commonJS({ + "node_modules/@slack/types/dist/events/dnd.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/email.js +var require_email = __commonJS({ + "node_modules/@slack/types/dist/events/email.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/emoji.js +var require_emoji = __commonJS({ + "node_modules/@slack/types/dist/events/emoji.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/file.js +var require_file2 = __commonJS({ + "node_modules/@slack/types/dist/events/file.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/function.js +var require_function = __commonJS({ + "node_modules/@slack/types/dist/events/function.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/grid-migration.js +var require_grid_migration = __commonJS({ + "node_modules/@slack/types/dist/events/grid-migration.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/group.js +var require_group = __commonJS({ + "node_modules/@slack/types/dist/events/group.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/im.js +var require_im = __commonJS({ + "node_modules/@slack/types/dist/events/im.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/invite.js +var require_invite = __commonJS({ + "node_modules/@slack/types/dist/events/invite.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/link-shared.js +var require_link_shared = __commonJS({ + "node_modules/@slack/types/dist/events/link-shared.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/member.js +var require_member = __commonJS({ + "node_modules/@slack/types/dist/events/member.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/message.js +var require_message = __commonJS({ + "node_modules/@slack/types/dist/events/message.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/message-metadata.js +var require_message_metadata = __commonJS({ + "node_modules/@slack/types/dist/events/message-metadata.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/pin.js +var require_pin = __commonJS({ + "node_modules/@slack/types/dist/events/pin.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/reaction.js +var require_reaction = __commonJS({ + "node_modules/@slack/types/dist/events/reaction.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/shared-channel.js +var require_shared_channel = __commonJS({ + "node_modules/@slack/types/dist/events/shared-channel.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/star.js +var require_star = __commonJS({ + "node_modules/@slack/types/dist/events/star.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/subteam.js +var require_subteam = __commonJS({ + "node_modules/@slack/types/dist/events/subteam.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/team.js +var require_team = __commonJS({ + "node_modules/@slack/types/dist/events/team.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/token.js +var require_token = __commonJS({ + "node_modules/@slack/types/dist/events/token.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/user.js +var require_user = __commonJS({ + "node_modules/@slack/types/dist/events/user.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/steps-from-apps.js +var require_steps_from_apps = __commonJS({ + "node_modules/@slack/types/dist/events/steps-from-apps.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/events/index.js +var require_events = __commonJS({ + "node_modules/@slack/types/dist/events/index.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; } - for (x = false, a = new h(K(g)), c = h.precision, h.precision = o = g.length * b * 2; p = N(a, t, 0, 1, 1), i = r.plus(p.times(n)), i.cmp(e) != 1; ) r = n, n = i, i = u, u = l.plus(p.times(i)), l = i, i = t, t = a.minus(p.times(i)), a = i; - return i = N(e.minus(r), n, 0, 1, 1), l = l.plus(i.times(u)), r = r.plus(i.times(n)), l.s = u.s = f.s, d = N(u, n, o, 1).minus(f).abs().cmp(N(l, r, o, 1).minus(f).abs()) < 1 ? [u, n] : [l, r], h.precision = c, x = true, d; - }; - m.toHexadecimal = m.toHex = function(e, t) { - return Si(this, 16, e, t); + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { + for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); }; - m.toNearest = function(e, t) { - var r = this, n = r.constructor; - if (r = new n(r), e == null) { - if (!r.d) return r; - e = new n(1), t = n.rounding; - } else { - if (e = new n(e), t === void 0 ? t = n.rounding : ie(t, 0, 8), !r.d) return e.s ? r : e; - if (!e.d) return e.s && (e.s = r.s), e; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar(require_app(), exports2); + __exportStar(require_assistant(), exports2); + __exportStar(require_call(), exports2); + __exportStar(require_channel(), exports2); + __exportStar(require_dnd(), exports2); + __exportStar(require_email(), exports2); + __exportStar(require_emoji(), exports2); + __exportStar(require_file2(), exports2); + __exportStar(require_function(), exports2); + __exportStar(require_grid_migration(), exports2); + __exportStar(require_group(), exports2); + __exportStar(require_im(), exports2); + __exportStar(require_invite(), exports2); + __exportStar(require_link_shared(), exports2); + __exportStar(require_member(), exports2); + __exportStar(require_message(), exports2); + __exportStar(require_message_metadata(), exports2); + __exportStar(require_pin(), exports2); + __exportStar(require_reaction(), exports2); + __exportStar(require_shared_channel(), exports2); + __exportStar(require_star(), exports2); + __exportStar(require_subteam(), exports2); + __exportStar(require_team(), exports2); + __exportStar(require_token(), exports2); + __exportStar(require_user(), exports2); + __exportStar(require_steps_from_apps(), exports2); + } +}); + +// node_modules/@slack/types/dist/message-metadata.js +var require_message_metadata2 = __commonJS({ + "node_modules/@slack/types/dist/message-metadata.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/message-attachments.js +var require_message_attachments = __commonJS({ + "node_modules/@slack/types/dist/message-attachments.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/views.js +var require_views = __commonJS({ + "node_modules/@slack/types/dist/views.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/block-kit/blocks.js +var require_blocks = __commonJS({ + "node_modules/@slack/types/dist/block-kit/blocks.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/block-kit/composition-objects.js +var require_composition_objects = __commonJS({ + "node_modules/@slack/types/dist/block-kit/composition-objects.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/block-kit/block-elements.js +var require_block_elements = __commonJS({ + "node_modules/@slack/types/dist/block-kit/block-elements.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/block-kit/extensions.js +var require_extensions = __commonJS({ + "node_modules/@slack/types/dist/block-kit/extensions.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/types/dist/index.js +var require_dist3 = __commonJS({ + "node_modules/@slack/types/dist/index.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; } - return e.d[0] ? (x = false, r = N(r, e, 0, t, 1).times(e), x = true, y(r)) : (e.s = r.s, r = e), r; - }; - m.toNumber = function() { - return +this; - }; - m.toOctal = function(e, t) { - return Si(this, 8, e, t); + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { + for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); }; - m.toPower = m.pow = function(e) { - var t, r, n, i, o, s, a = this, l = a.constructor, u = +(e = new l(e)); - if (!a.d || !e.d || !a.d[0] || !e.d[0]) return new l(G(+a, u)); - if (a = new l(a), a.eq(1)) return a; - if (n = l.precision, o = l.rounding, e.eq(1)) return y(a, n, o); - if (t = ee(e.e / b), t >= e.d.length - 1 && (r = u < 0 ? -u : u) <= xc) return i = Ss(l, a, r, n), e.s < 0 ? new l(1).div(i) : y(i, n, o); - if (s = a.s, s < 0) { - if (t < e.d.length - 1) return new l(NaN); - if (e.d[t] & 1 || (s = 1), a.e == 0 && a.d[0] == 1 && a.d.length == 1) return a.s = s, a; + Object.defineProperty(exports2, "__esModule", { value: true }); + __exportStar(require_calls(), exports2); + __exportStar(require_dialog(), exports2); + __exportStar(require_events(), exports2); + __exportStar(require_message_metadata2(), exports2); + __exportStar(require_message_attachments(), exports2); + __exportStar(require_views(), exports2); + __exportStar(require_blocks(), exports2); + __exportStar(require_composition_objects(), exports2); + __exportStar(require_block_elements(), exports2); + __exportStar(require_extensions(), exports2); + } +}); + +// node_modules/@slack/web-api/dist/methods.js +var require_methods = __commonJS({ + "node_modules/@slack/web-api/dist/methods.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; } - return r = G(+a, u), t = r == 0 || !isFinite(r) ? ee(u * (Math.log("0." + K(a.d)) / Math.LN10 + a.e + 1)) : new l(r + "").e, t > l.maxE + 1 || t < l.minE - 1 ? new l(t > 0 ? s / 0 : 0) : (x = false, l.rounding = a.s = 1, r = Math.min(12, (t + "").length), i = Ri(e.times(He(a, n + r)), n), i.d && (i = y(i, n + 5, 1), rr(i.d, n, o) && (t = n + 10, i = y(Ri(e.times(He(a, t + r)), t), t + 5, 1), +K(i.d).slice(n + 1, n + 15) + 1 == 1e14 && (i = y(i, n + 1, 0)))), i.s = s, x = true, l.rounding = o, y(i, n, o)); - }; - m.toPrecision = function(e, t) { - var r, n = this, i = n.constructor; - return e === void 0 ? r = we(n, n.e <= i.toExpNeg || n.e >= i.toExpPos) : (ie(e, 1, ze), t === void 0 ? t = i.rounding : ie(t, 0, 8), n = y(new i(n), e, t), r = we(n, e <= n.e || n.e <= i.toExpNeg, e)), n.isNeg() && !n.isZero() ? "-" + r : r; - }; - m.toSignificantDigits = m.toSD = function(e, t) { - var r = this, n = r.constructor; - return e === void 0 ? (e = n.precision, t = n.rounding) : (ie(e, 1, ze), t === void 0 ? t = n.rounding : ie(t, 0, 8)), y(new n(r), e, t); - }; - m.toString = function() { - var e = this, t = e.constructor, r = we(e, e.e <= t.toExpNeg || e.e >= t.toExpPos); - return e.isNeg() && !e.isZero() ? "-" + r : r; - }; - m.truncated = m.trunc = function() { - return y(new this.constructor(this), this.e + 1, 1); - }; - m.valueOf = m.toJSON = function() { - var e = this, t = e.constructor, r = we(e, e.e <= t.toExpNeg || e.e >= t.toExpPos); - return e.isNeg() ? "-" + r : r; + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { + for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); }; - function K(e) { - var t, r, n, i = e.length - 1, o = "", s = e[0]; - if (i > 0) { - for (o += s, t = 1; t < i; t++) n = e[t] + "", r = b - n.length, r && (o += We(r)), o += n; - s = e[t], n = s + "", r = b - n.length, r && (o += We(r)); - } else if (s === 0) return "0"; - for (; s % 10 === 0; ) s /= 10; - return o + s; - } - function ie(e, t, r) { - if (e !== ~~e || e < t || e > r) throw Error(Ke + e); - } - function rr(e, t, r, n) { - var i, o, s, a; - for (o = e[0]; o >= 10; o /= 10) --t; - return --t < 0 ? (t += b, i = 0) : (i = Math.ceil((t + 1) / b), t %= b), o = G(10, b - t), a = e[i] % o | 0, n == null ? t < 3 ? (t == 0 ? a = a / 100 | 0 : t == 1 && (a = a / 10 | 0), s = r < 4 && a == 99999 || r > 3 && a == 49999 || a == 5e4 || a == 0) : s = (r < 4 && a + 1 == o || r > 3 && a + 1 == o / 2) && (e[i + 1] / o / 100 | 0) == G(10, t - 2) - 1 || (a == o / 2 || a == 0) && (e[i + 1] / o / 100 | 0) == 0 : t < 4 ? (t == 0 ? a = a / 1e3 | 0 : t == 1 ? a = a / 100 | 0 : t == 2 && (a = a / 10 | 0), s = (n || r < 4) && a == 9999 || !n && r > 3 && a == 4999) : s = ((n || r < 4) && a + 1 == o || !n && r > 3 && a + 1 == o / 2) && (e[i + 1] / o / 1e3 | 0) == G(10, t - 3) - 1, s; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Methods = void 0; + var eventemitter3_1 = require_eventemitter32(); + var WebClient_1 = require_WebClient(); + function bindApiCall(self2, method) { + const apiMethod = self2.apiCall.bind(self2, method); + return apiMethod; } - function en(e, t, r) { - for (var n, i = [0], o, s = 0, a = e.length; s < a; ) { - for (o = i.length; o--; ) i[o] *= t; - for (i[0] += Pi.indexOf(e.charAt(s++)), n = 0; n < i.length; n++) i[n] > r - 1 && (i[n + 1] === void 0 && (i[n + 1] = 0), i[n + 1] += i[n] / r | 0, i[n] %= r); - } - return i.reverse(); + function bindApiCallWithOptionalArgument(self2, method) { + const apiMethod = self2.apiCall.bind(self2, method); + return apiMethod; } - function vc(e, t) { - var r, n, i; - if (t.isZero()) return t; - n = t.d.length, n < 32 ? (r = Math.ceil(n / 3), i = (1 / an(4, r)).toString()) : (r = 16, i = "2.3283064365386962890625e-10"), e.precision += r, t = Et(e, 1, t.times(i), new e(1)); - for (var o = r; o--; ) { - var s = t.times(t); - t = s.times(s).minus(s).times(8).plus(1); - } - return e.precision -= r, t; + function bindFilesUploadV2(self2) { + return self2.filesUploadV2.bind(self2); } - var N = /* @__PURE__ */ function() { - function e(n, i, o) { - var s, a = 0, l = n.length; - for (n = n.slice(); l--; ) s = n[l] * i + a, n[l] = s % o | 0, a = s / o | 0; - return a && n.unshift(a), n; - } - function t(n, i, o, s) { - var a, l; - if (o != s) l = o > s ? 1 : -1; - else for (a = l = 0; a < o; a++) if (n[a] != i[a]) { - l = n[a] > i[a] ? 1 : -1; - break; - } - return l; - } - function r(n, i, o, s) { - for (var a = 0; o--; ) n[o] -= a, a = n[o] < i[o] ? 1 : 0, n[o] = a * s + n[o] - i[o]; - for (; !n[0] && n.length > 1; ) n.shift(); - } - return function(n, i, o, s, a, l) { - var u, c, p, d, f, g, h, O, T, S, C, E, me, ae, Bt, U, ne, Ie, z, dt, Lr = n.constructor, qn = n.s == i.s ? 1 : -1, Y = n.d, _ = i.d; - if (!Y || !Y[0] || !_ || !_[0]) return new Lr(!n.s || !i.s || (Y ? _ && Y[0] == _[0] : !_) ? NaN : Y && Y[0] == 0 || !_ ? qn * 0 : qn / 0); - for (l ? (f = 1, c = n.e - i.e) : (l = ge, f = b, c = ee(n.e / f) - ee(i.e / f)), z = _.length, ne = Y.length, T = new Lr(qn), S = T.d = [], p = 0; _[p] == (Y[p] || 0); p++) ; - if (_[p] > (Y[p] || 0) && c--, o == null ? (ae = o = Lr.precision, s = Lr.rounding) : a ? ae = o + (n.e - i.e) + 1 : ae = o, ae < 0) S.push(1), g = true; - else { - if (ae = ae / f + 2 | 0, p = 0, z == 1) { - for (d = 0, _ = _[0], ae++; (p < ne || d) && ae--; p++) Bt = d * l + (Y[p] || 0), S[p] = Bt / _ | 0, d = Bt % _ | 0; - g = d || p < ne; - } else { - for (d = l / (_[0] + 1) | 0, d > 1 && (_ = e(_, d, l), Y = e(Y, d, l), z = _.length, ne = Y.length), U = z, C = Y.slice(0, z), E = C.length; E < z; ) C[E++] = 0; - dt = _.slice(), dt.unshift(0), Ie = _[0], _[1] >= l / 2 && ++Ie; - do - d = 0, u = t(_, C, z, E), u < 0 ? (me = C[0], z != E && (me = me * l + (C[1] || 0)), d = me / Ie | 0, d > 1 ? (d >= l && (d = l - 1), h = e(_, d, l), O = h.length, E = C.length, u = t(h, C, O, E), u == 1 && (d--, r(h, z < O ? dt : _, O, l))) : (d == 0 && (u = d = 1), h = _.slice()), O = h.length, O < E && h.unshift(0), r(C, h, E, l), u == -1 && (E = C.length, u = t(_, C, z, E), u < 1 && (d++, r(C, z < E ? dt : _, E, l))), E = C.length) : u === 0 && (d++, C = [0]), S[p++] = d, u && C[0] ? C[E++] = Y[U] || 0 : (C = [Y[U]], E = 1); - while ((U++ < ne || C[0] !== void 0) && ae--); - g = C[0] !== void 0; + var Methods = class extends eventemitter3_1.EventEmitter { + constructor() { + super(); + this.admin = { + analytics: { + /** + * @description Retrieve analytics data for a given date, presented as a compressed JSON file. + * @see {@link https://api.slack.com/methods/api.test `api.test` API reference}. + */ + getFile: bindApiCall(this, "admin.analytics.getFile") + }, + apps: { + activities: { + /** + * @description Get logs for a specified team/org. + * @see {@link https://api.slack.com/methods/admin.apps.activities.list `admin.apps.activities.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.apps.activities.list") + }, + /** + * @description Approve an app for installation on a workspace. + * @see {@link https://api.slack.com/methods/admin.apps.approve `admin.apps.approve` API reference}. + */ + approve: bindApiCall(this, "admin.apps.approve"), + approved: { + /** + * @description List approved apps for an org or workspace. + * @see {@link https://api.slack.com/methods/admin.apps.approved.list `admin.apps.approved.list` API reference}. + */ + list: bindApiCall(this, "admin.apps.approved.list") + }, + /** + * @description Clear an app resolution. + * @see {@link https://api.slack.com/methods/admin.apps.clearResolution `admin.apps.clearResolution` API reference}. + */ + clearResolution: bindApiCall(this, "admin.apps.clearResolution"), + config: { + /** + * @description Look up the app config for connectors by their IDs. + * @see {@link https://api.slack.com/methods/admin.apps.config.lookup `admin.apps.config.lookup` API reference}. + */ + lookup: bindApiCall(this, "admin.apps.config.lookup"), + /** + * @description Set the app config for a connector. + * @see {@link https://api.slack.com/methods/admin.apps.config.set `admin.apps.config.set` API reference}. + */ + set: bindApiCall(this, "admin.apps.config.set") + }, + requests: { + /** + * @description Cancel app request for team. + * @see {@link https://api.slack.com/methods/admin.apps.requests.cancel `admin.apps.requests.cancel` API reference}. + */ + cancel: bindApiCall(this, "admin.apps.requests.cancel"), + /** + * @description List app requests for a team/workspace. + * @see {@link https://api.slack.com/methods/admin.apps.requests.list `admin.apps.requests.list` API reference}. + */ + list: bindApiCall(this, "admin.apps.requests.list") + }, + /** + * @description Restrict an app for installation on a workspace. + * @see {@link https://api.slack.com/methods/admin.apps.restrict `admin.apps.restrict` API reference}. + */ + restrict: bindApiCall(this, "admin.apps.restrict"), + restricted: { + /** + * @description List restricted apps for an org or workspace. + * @see {@link https://api.slack.com/methods/admin.apps.restricted.list `admin.apps.restricted.list` API reference}. + */ + list: bindApiCall(this, "admin.apps.restricted.list") + }, + /** + * @description Uninstall an app from one or many workspaces, or an entire enterprise organization. + * @see {@link https://api.slack.com/methods/admin.apps.uninstall `admin.apps.uninstall` API reference}. + */ + uninstall: bindApiCall(this, "admin.apps.uninstall") + }, + auth: { + policy: { + /** + * @description Assign entities to a particular authentication policy. + * @see {@link https://api.slack.com/methods/admin.auth.policy.assignEntities `admin.auth.policy.assignEntities` API reference}. + */ + assignEntities: bindApiCall(this, "admin.auth.policy.assignEntities"), + /** + * @description Fetch all the entities assigned to a particular authentication policy by name. + * @see {@link https://api.slack.com/methods/admin.auth.policy.getEntities `admin.auth.policy.getEntities` API reference}. + */ + getEntities: bindApiCall(this, "admin.auth.policy.getEntities"), + /** + * @description Remove specified entities from a specified authentication policy. + * @see {@link https://api.slack.com/methods/admin.auth.policy.removeEntities `admin.auth.policy.removeEntities` API reference}. + */ + removeEntities: bindApiCall(this, "admin.auth.policy.removeEntities") + } + }, + barriers: { + /** + * @description Create an Information Barrier. + * @see {@link https://api.slack.com/methods/admin.barriers.create `admin.barriers.create` API reference}. + */ + create: bindApiCall(this, "admin.barriers.create"), + /** + * @description Delete an existing Information Barrier. + * @see {@link https://api.slack.com/methods/admin.barriers.delete `admin.barriers.delete` API reference}. + */ + delete: bindApiCall(this, "admin.barriers.delete"), + /** + * @description Get all Information Barriers for your organization. + * @see {@link https://api.slack.com/methods/admin.barriers.list `admin.barriers.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.barriers.list"), + /** + * @description Update an existing Information Barrier. + * @see {@link https://api.slack.com/methods/admin.barriers.update `admin.barriers.update` API reference}. + */ + update: bindApiCall(this, "admin.barriers.update") + }, + conversations: { + /** + * @description Archive a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.archive `admin.conversations.archive` API reference}. + */ + archive: bindApiCall(this, "admin.conversations.archive"), + /** + * @description Archive public or private channels in bulk. + * @see {@link https://api.slack.com/methods/admin.conversations.bulkArchive `admin.conversations.bulkArchive` API reference}. + */ + bulkArchive: bindApiCall(this, "admin.conversations.bulkArchive"), + /** + * @description Delete public or private channels in bulk. + * @see {@link https://api.slack.com/methods/admin.conversations.bulkDelet `admin.conversations.bulkDelete` API reference}. + */ + bulkDelete: bindApiCall(this, "admin.conversations.bulkDelete"), + /** + * @description Move public or private channels in bulk. + * @see {@link https://api.slack.com/methods/admin.conversations.bulkMove `admin.conversations.bulkMove` API reference}. + */ + bulkMove: bindApiCall(this, "admin.conversations.bulkMove"), + /** + * @description Convert a public channel to a private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.convertToPrivate `admin.conversations.convertToPrivate` API reference}. + */ + convertToPrivate: bindApiCall(this, "admin.conversations.convertToPrivate"), + /** + * @description Convert a private channel to a public channel. + * @see {@link https://api.slack.com/methods/admin.conversations.convertToPublic `admin.conversations.convertToPublic` API reference}. + */ + convertToPublic: bindApiCall(this, "admin.conversations.convertToPublic"), + /** + * @description Create a public or private channel-based conversation. + * @see {@link https://api.slack.com/methods/admin.conversations.create `admin.conversations.create` API reference}. + */ + create: bindApiCall(this, "admin.conversations.create"), + /** + * @description Delete a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.delete `admin.conversations.delete` API reference}. + */ + delete: bindApiCall(this, "admin.conversations.delete"), + /** + * @description Disconnect a connected channel from one or more workspaces. + * @see {@link https://api.slack.com/methods/admin.conversations.disconnectShared `admin.conversations.disconnectShared` API reference}. + */ + disconnectShared: bindApiCall(this, "admin.conversations.disconnectShared"), + ekm: { + /** + * @description List all disconnected channels — i.e., channels that were once connected to other workspaces + * and then disconnected — and the corresponding original channel IDs for key revocation with EKM. + * @see {@link https://api.slack.com/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo `admin.conversations.ekm.listOriginalConnectedChannelInfo` API reference}. + */ + listOriginalConnectedChannelInfo: bindApiCallWithOptionalArgument(this, "admin.conversations.ekm.listOriginalConnectedChannelInfo") + }, + /** + * @description Get conversation preferences for a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.getConversationPrefs `admin.conversations.getConversationPrefs` API reference}. + */ + getConversationPrefs: bindApiCall(this, "admin.conversations.getConversationPrefs"), + /** + * @description Get a conversation's retention policy. + * @see {@link https://api.slack.com/methods/admin.conversations.getCustomRetention `admin.conversations.getCustomRetention` API reference}. + */ + getCustomRetention: bindApiCall(this, "admin.conversations.getCustomRetention"), + /** + * @description Get all the workspaces a given public or private channel is connected to within + * this Enterprise org. + * @see {@link https://api.slack.com/methods/admin.conversations.getTeams `admin.conversations.getTeams` API reference}. + */ + getTeams: bindApiCall(this, "admin.conversations.getTeams"), + /** + * @description Invite a user to a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.invite `admin.conversations.invite` API reference}. + */ + invite: bindApiCall(this, "admin.conversations.invite"), + /** + * @description Returns channels on the given team using the filters. + * @see {@link https://api.slack.com/methods/admin.conversations.lookup `admin.conversations.lookup` API reference}. + */ + lookup: bindApiCall(this, "admin.conversations.lookup"), + /** + * @description Remove a conversation's retention policy. + * @see {@link https://api.slack.com/methods/admin.conversations.removeCustomRetention `admin.conversations.removeCustomRetention` API reference}. + */ + removeCustomRetention: bindApiCall(this, "admin.conversations.removeCustomRetention"), + /** + * @description Rename a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.rename `admin.conversations.rename` API reference}. + */ + rename: bindApiCall(this, "admin.conversations.rename"), + restrictAccess: { + /** + * @description Add an allowlist of IDP groups for accessing a channel. + * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.addGroup `admin.conversations.restrictAccess.addGroup` API reference}. + */ + addGroup: bindApiCall(this, "admin.conversations.restrictAccess.addGroup"), + /** + * @description List all IDP Groups linked to a channel. + * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.listGroups `admin.conversations.restrictAccess.listGroups` API reference}. + */ + listGroups: bindApiCall(this, "admin.conversations.restrictAccess.listGroups"), + /** + * @description Remove a linked IDP group linked from a private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.restrictAccess.removeGroup `admin.conversations.restrictAccess.removeGroup` API reference}. + */ + removeGroup: bindApiCall(this, "admin.conversations.restrictAccess.removeGroup") + }, + /** + * @description Search for public or private channels in an Enterprise organization. + * @see {@link https://api.slack.com/methods/admin.conversations.search `admin.conversations.search` API reference}. + */ + search: bindApiCallWithOptionalArgument(this, "admin.conversations.search"), + /** + * @description Set the posting permissions for a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.setConversationPrefs `admin.conversations.setConversationPrefs` API reference}. + */ + setConversationPrefs: bindApiCall(this, "admin.conversations.setConversationPrefs"), + /** + * @description Set a conversation's retention policy. + * @see {@link https://api.slack.com/methods/admin.conversations.setCustomRetention `admin.conversations.setCustomRetention` API reference}. + */ + setCustomRetention: bindApiCall(this, "admin.conversations.setCustomRetention"), + /** + * @description Set the workspaces in an Enterprise grid org that connect to a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.setTeams `admin.conversations.setTeams` API reference}. + */ + setTeams: bindApiCall(this, "admin.conversations.setTeams"), + /** + * @description Unarchive a public or private channel. + * @see {@link https://api.slack.com/methods/admin.conversations.unarchive `admin.conversations.unarchive` API reference}. + */ + unarchive: bindApiCall(this, "admin.conversations.unarchive") + }, + emoji: { + /** + * @description Add an emoji. + * @see {@link https://api.slack.com/methods/admin.emoji.add `admin.emoji.add` API reference}. + */ + add: bindApiCall(this, "admin.emoji.add"), + /** + * @description Add an emoji alias. + * @see {@link https://api.slack.com/methods/admin.emoji.addAlias `admin.emoji.addAlias` API reference}. + */ + addAlias: bindApiCall(this, "admin.emoji.addAlias"), + /** + * @description List emoji for an Enterprise Grid organization. + * @see {@link https://api.slack.com/methods/admin.emoji.list `admin.emoji.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.emoji.list"), + /** + * @description Remove an emoji across an Enterprise Grid organization. + * @see {@link https://api.slack.com/methods/admin.emoji.remove `admin.emoji.remove` API reference}. + */ + remove: bindApiCall(this, "admin.emoji.remove"), + /** + * @description Rename an emoji. + * @see {@link https://api.slack.com/methods/admin.emoji.rename `admin.emoji.rename` API reference}. + */ + rename: bindApiCall(this, "admin.emoji.rename") + }, + functions: { + /** + * @description Look up functions by a set of apps. + * @see {@link https://api.slack.com/methods/admin.functions.list `admin.functions.list` API reference}. + */ + list: bindApiCall(this, "admin.functions.list"), + permissions: { + /** + * @description Lookup the visibility of multiple Slack functions and include the users if + * it is limited to particular named entities. + * @see {@link https://api.slack.com/methods/admin.functions.permissions.lookup `admin.functions.permissions.lookup` API reference}. + */ + lookup: bindApiCall(this, "admin.functions.permissions.lookup"), + /** + * @description Set the visibility of a Slack function and define the users or workspaces if + * it is set to named_entities. + * @see {@link https://api.slack.com/methods/admin.functions.permissions.set `admin.functions.permissions.set` API reference}. + */ + set: bindApiCall(this, "admin.functions.permissions.set") + } + }, + inviteRequests: { + /** + * @description Approve a workspace invite request. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.approve `admin.inviteRequests.approve` API reference}. + */ + approve: bindApiCall(this, "admin.inviteRequests.approve"), + approved: { + /** + * @description List all approved workspace invite requests. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.approved.list `admin.inviteRequests.approved.list` API reference}. + */ + list: bindApiCall(this, "admin.inviteRequests.approved.list") + }, + denied: { + /** + * @description List all denied workspace invite requests. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.denied.list `admin.inviteRequests.denied.list` API reference}. + */ + list: bindApiCall(this, "admin.inviteRequests.denied.list") + }, + /** + * @description Deny a workspace invite request. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.deny `admin.inviteRequests.deny` API reference}. + */ + deny: bindApiCall(this, "admin.inviteRequests.deny"), + /** + * @description List all pending workspace invite requests. + * @see {@link https://api.slack.com/methods/admin.inviteRequests.list `admin.inviteRequests.list` API reference}. + */ + list: bindApiCall(this, "admin.inviteRequests.list") + }, + roles: { + /** + * @description Adds members to the specified role with the specified scopes. + * @see {@link https://api.slack.com/methods/admin.roles.addAssignments `admin.roles.addAssignments` API reference}. + */ + addAssignments: bindApiCall(this, "admin.roles.addAssignments"), + /** + * @description Lists assignments for all roles across entities. + * Options to scope results by any combination of roles or entities. + * @see {@link https://api.slack.com/methods/admin.roles.listAssignments `admin.roles.listAssignments` API reference}. + */ + listAssignments: bindApiCallWithOptionalArgument(this, "admin.roles.listAssignments"), + /** + * @description Removes a set of users from a role for the given scopes and entities. + * @see {@link https://api.slack.com/methods/admin.roles.removeAssignments `admin.roles.removeAssignments` API reference}. + */ + removeAssignments: bindApiCall(this, "admin.roles.removeAssignments") + }, + teams: { + admins: { + /** + * @description List all of the admins on a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.admins.list `admin.teams.admins.list` API reference}. + */ + list: bindApiCall(this, "admin.teams.admins.list") + }, + /** + * @description Create an Enterprise team. + * @see {@link https://api.slack.com/methods/admin.teams.create `admin.teams.create` API reference}. + */ + create: bindApiCall(this, "admin.teams.create"), + /** + * @description List all teams on an Enterprise organization. + * @see {@link https://api.slack.com/methods/admin.teams.list `admin.teams.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.teams.list"), + owners: { + /** + * @description List all of the owners on a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.owners.list `admin.teams.owners.list` API reference}. + */ + list: bindApiCall(this, "admin.teams.owners.list") + }, + settings: { + /** + * @description Fetch information about settings in a workspace. + * @see {@link https://api.slack.com/methods/admin.teams.owners.list `admin.teams.owners.list` API reference}. + */ + info: bindApiCall(this, "admin.teams.settings.info"), + /** + * @description Set the default channels of a workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setDefaultChannels `admin.teams.settings.setDefaultChannels` API reference}. + */ + setDefaultChannels: bindApiCall(this, "admin.teams.settings.setDefaultChannels"), + /** + * @description Set the description of a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setDescription `admin.teams.settings.setDescription` API reference}. + */ + setDescription: bindApiCall(this, "admin.teams.settings.setDescription"), + /** + * @description Set the discoverability of a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setDiscoverability `admin.teams.settings.setDiscoverability` API reference}. + */ + setDiscoverability: bindApiCall(this, "admin.teams.settings.setDiscoverability"), + /** + * @description Sets the icon of a workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setIcon `admin.teams.settings.setIcon` API reference}. + */ + setIcon: bindApiCall(this, "admin.teams.settings.setIcon"), + /** + * @description Set the name of a given workspace. + * @see {@link https://api.slack.com/methods/admin.teams.settings.setName `admin.teams.settings.setName` API reference}. + */ + setName: bindApiCall(this, "admin.teams.settings.setName") + } + }, + usergroups: { + /** + * @description Add up to one hundred default channels to an IDP group. + * @see {@link https://api.slack.com/methods/admin.usergroups.addChannels `admin.teams.usergroups.addChannels` API reference}. + */ + addChannels: bindApiCall(this, "admin.usergroups.addChannels"), + /** + * @description Associate one or more default workspaces with an organization-wide IDP group. + * @see {@link https://api.slack.com/methods/admin.usergroups.addTeams `admin.teams.usergroups.addTeams` API reference}. + */ + addTeams: bindApiCall(this, "admin.usergroups.addTeams"), + /** + * @description List the channels linked to an org-level IDP group (user group). + * @see {@link https://api.slack.com/methods/admin.usergroups.listChannels `admin.teams.usergroups.listChannels` API reference}. + */ + listChannels: bindApiCall(this, "admin.usergroups.listChannels"), + /** + * @description Remove one or more default channels from an org-level IDP group (user group). + * @see {@link https://api.slack.com/methods/admin.usergroups.removeChannels `admin.teams.usergroups.removeChannels` API reference}. + */ + removeChannels: bindApiCall(this, "admin.usergroups.removeChannels") + }, + users: { + /** + * @description Add an Enterprise user to a workspace. + * @see {@link https://api.slack.com/methods/admin.users.assign `admin.users.assign` API reference}. + */ + assign: bindApiCall(this, "admin.users.assign"), + /** + * @description Invite a user to a workspace. + * @see {@link https://api.slack.com/methods/admin.users.invite `admin.users.invite` API reference}. + */ + invite: bindApiCall(this, "admin.users.invite"), + /** + * @description List users on a workspace. + * @see {@link https://api.slack.com/methods/admin.users.list `admin.users.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.users.list"), + /** + * @description Remove a user from a workspace. + * @see {@link https://api.slack.com/methods/admin.users.remove `admin.users.remove` API reference}. + */ + remove: bindApiCall(this, "admin.users.remove"), + session: { + /** + * @description Clear user-specific session settings—the session duration and what happens when the client + * closes—for a list of users. + * @see {@link https://api.slack.com/methods/admin.users.session.clearSettings `admin.users.session.clearSettings` API reference}. + */ + clearSettings: bindApiCall(this, "admin.users.session.clearSettings"), + /** + * @description Get user-specific session settings—the session duration and what happens when the client + * closes—given a list of users. + * @see {@link https://api.slack.com/methods/admin.users.session.getSettings `admin.users.session.getSettings` API reference}. + */ + getSettings: bindApiCall(this, "admin.users.session.getSettings"), + /** + * @description Revoke a single session for a user. The user will be forced to login to Slack. + * @see {@link https://api.slack.com/methods/admin.users.session.invalidate `admin.users.session.invalidate` API reference}. + */ + invalidate: bindApiCall(this, "admin.users.session.invalidate"), + /** + * @description List active user sessions for an organization. + * @see {@link https://api.slack.com/methods/admin.users.session.list `admin.users.session.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "admin.users.session.list"), + /** + * @description Wipes all valid sessions on all devices for a given user. + * @see {@link https://api.slack.com/methods/admin.users.session.reset `admin.users.session.reset` API reference}. + */ + reset: bindApiCall(this, "admin.users.session.reset"), + /** + * @description Enqueues an asynchronous job to wipe all valid sessions on all devices for a given user list. + * @see {@link https://api.slack.com/methods/admin.users.session.resetBulk `admin.users.session.resetBulk` API reference}. + */ + resetBulk: bindApiCall(this, "admin.users.session.resetBulk"), + /** + * @description Configure the user-level session settings—the session duration and what happens when the client + * closes—for one or more users. + * @see {@link https://api.slack.com/methods/admin.users.session.setSettings `admin.users.session.setSettings` API reference}. + */ + setSettings: bindApiCall(this, "admin.users.session.setSettings") + }, + /** + * @description Set an existing guest, regular user, or owner to be an admin user. + * @see {@link https://api.slack.com/methods/admin.users.setAdmin `admin.users.setAdmin` API reference}. + */ + setAdmin: bindApiCall(this, "admin.users.setAdmin"), + /** + * @description Set an expiration for a guest user. + * @see {@link https://api.slack.com/methods/admin.users.setExpiration `admin.users.setExpiration` API reference}. + */ + setExpiration: bindApiCall(this, "admin.users.setExpiration"), + /** + * @description Set an existing guest, regular user, or admin user to be a workspace owner. + * @see {@link https://api.slack.com/methods/admin.users.setOwner `admin.users.setOwner` API reference}. + */ + setOwner: bindApiCall(this, "admin.users.setOwner"), + /** + * @description Set an existing guest user, admin user, or owner to be a regular user. + * @see {@link https://api.slack.com/methods/admin.users.setRegular `admin.users.setRegular` API reference}. + */ + setRegular: bindApiCall(this, "admin.users.setRegular"), + unsupportedVersions: { + /** + * @description Ask Slackbot to send you an export listing all workspace members using unsupported software, + * presented as a zipped CSV file. + * @see {@link https://api.slack.com/methods/admin.users.unsupportedVersions.export `admin.users.unsupportedVersions.export` API reference}. + */ + export: bindApiCall(this, "admin.users.unsupportedVersions.export") + } + }, + workflows: { + collaborators: { + /** + * @description Add collaborators to workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.collaborators.add `admin.workflows.collaborators.add` API reference}. + */ + add: bindApiCall(this, "admin.workflows.collaborators.add"), + /** + * @description Remove collaborators from workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.collaborators.remove `admin.workflows.collaborators.remove` API reference}. + */ + remove: bindApiCall(this, "admin.workflows.collaborators.remove") + }, + permissions: { + /** + * @description Look up the permissions for a set of workflows. + * @see {@link https://api.slack.com/methods/admin.workflows.permissions.lookup `admin.workflows.permissions.lookup` API reference}. + */ + lookup: bindApiCall(this, "admin.workflows.permissions.lookup") + }, + /** + * @description Search workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.search `admin.workflows.search` API reference}. + */ + search: bindApiCallWithOptionalArgument(this, "admin.workflows.search"), + /** + * @description Unpublish workflows within the team or enterprise. + * @see {@link https://api.slack.com/methods/admin.workflows.unpublish `admin.workflows.unpublish` API reference}. + */ + unpublish: bindApiCall(this, "admin.workflows.unpublish") + } + }; + this.api = { + /** + * @description Checks API calling code. + * @see {@link https://api.slack.com/methods/api.test `api.test` API reference}. + */ + test: bindApiCallWithOptionalArgument(this, "api.test") + }; + this.assistant = { + threads: { + /** + * @description Set loading status to indicate that the app is building a response. + * @see {@link https://api.slack.com/methods/assistant.threads.setStatus `assistant.threads.setStatus` API reference}. + */ + setStatus: bindApiCall(this, "assistant.threads.setStatus"), + /** + * @description Set suggested prompts for the user. Can suggest up to four prompts. + * @see {@link https://api.slack.com/methods/assistant.threads.setSuggestedPrompts `assistant.threads.setSuggestedPrompts` API reference}. + */ + setSuggestedPrompts: bindApiCall(this, "assistant.threads.setSuggestedPrompts"), + /** + * @description Set the title of the thread. This is shown when a user views the app's chat history. + * @see {@link https://api.slack.com/methods/assistant.threads.setTitle `assistant.threads.setTitle` API reference}. + */ + setTitle: bindApiCall(this, "assistant.threads.setTitle") + } + }; + this.apps = { + connections: { + /** + * @description Generate a temporary Socket Mode WebSocket URL that your app can connect to in order to receive + * events and interactive payloads over. + * @see {@link https://api.slack.com/methods/apps.connections.open `apps.connections.open` API reference}. + */ + open: bindApiCallWithOptionalArgument(this, "apps.connections.open") + }, + event: { + authorizations: { + /** + * @description Get a list of authorizations for the given event context. + * Each authorization represents an app installation that the event is visible to. + * @see {@link https://api.slack.com/methods/apps.event.authorizations.list `apps.event.authorizations.list` API reference}. + */ + list: bindApiCall(this, "apps.event.authorizations.list") + } + }, + manifest: { + /** + * @description Create an app from an app manifest. + * @see {@link https://api.slack.com/methods/apps.manifest.create `apps.manifest.create` API reference}. + */ + create: bindApiCall(this, "apps.manifest.create"), + /** + * @description Permanently deletes an app created through app manifests. + * @see {@link https://api.slack.com/methods/apps.manifest.delete `apps.manifest.delete` API reference}. + */ + delete: bindApiCall(this, "apps.manifest.delete"), + /** + * @description Export an app manifest from an existing app. + * @see {@link https://api.slack.com/methods/apps.manifest.export `apps.manifest.export` API reference}. + */ + export: bindApiCall(this, "apps.manifest.export"), + /** + * @description Update an app from an app manifest. + * @see {@link https://api.slack.com/methods/apps.manifest.update `apps.manifest.update` API reference}. + */ + update: bindApiCall(this, "apps.manifest.update"), + /** + * @description Validate an app manifest. + * @see {@link https://api.slack.com/methods/apps.manifest.validate `apps.manifest.validate` API reference}. + */ + validate: bindApiCall(this, "apps.manifest.validate") + }, + /** + * @description Uninstalls your app from a workspace. + * @see {@link https://api.slack.com/methods/apps.uninstall `apps.uninstall` API reference}. + */ + uninstall: bindApiCall(this, "apps.uninstall") + }; + this.auth = { + /** + * @description Revokes a token. + * @see {@link https://api.slack.com/methods/auth.revoke `auth.revoke` API reference}. + */ + revoke: bindApiCallWithOptionalArgument(this, "auth.revoke"), + teams: { + /** + * @description Obtain a full list of workspaces your org-wide app has been approved for. + * @see {@link https://api.slack.com/methods/auth.teams.list `auth.teams.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "auth.teams.list") + }, + test: bindApiCallWithOptionalArgument(this, "auth.test") + }; + this.bookmarks = { + /** + * @description Add bookmark to a channel. + * @see {@link https://api.slack.com/methods/bookmarks.add `bookmarks.add` API reference}. + */ + add: bindApiCall(this, "bookmarks.add"), + /** + * @description Edit bookmark. + * @see {@link https://api.slack.com/methods/bookmarks.edit `bookmarks.edit` API reference}. + */ + edit: bindApiCall(this, "bookmarks.edit"), + /** + * @description List bookmarks for a channel. + * @see {@link https://api.slack.com/methods/bookmarks.list `bookmarks.list` API reference}. + */ + list: bindApiCall(this, "bookmarks.list"), + /** + * @description Remove bookmark from a channel. + * @see {@link https://api.slack.com/methods/bookmarks.remove `bookmarks.remove` API reference}. + */ + remove: bindApiCall(this, "bookmarks.remove") + }; + this.bots = { + /** + * @description Gets information about a bot user. + * @see {@link https://api.slack.com/methods/bots.info `bots.info` API reference}. + */ + info: bindApiCallWithOptionalArgument(this, "bots.info") + }; + this.calls = { + /** + * @description Registers a new Call. + * @see {@link https://api.slack.com/methods/calls.add `calls.add` API reference}. + */ + add: bindApiCall(this, "calls.add"), + /** + * @description Ends a Call. + * @see {@link https://api.slack.com/methods/calls.end `calls.end` API reference}. + */ + end: bindApiCall(this, "calls.end"), + /** + * @description Returns information about a Call. + * @see {@link https://api.slack.com/methods/calls.info `calls.info` API reference}. + */ + info: bindApiCall(this, "calls.info"), + /** + * @description Updates information about a Call. + * @see {@link https://api.slack.com/methods/calls.info `calls.info` API reference}. + */ + update: bindApiCall(this, "calls.update"), + participants: { + /** + * @description Registers new participants added to a Call. + * @see {@link https://api.slack.com/methods/calls.participants.add `calls.participants.add` API reference}. + */ + add: bindApiCall(this, "calls.participants.add"), + remove: bindApiCall(this, "calls.participants.remove") + } + }; + this.canvases = { + access: { + /** + * @description Remove access to a canvas for specified entities. + * @see {@link https://api.slack.com/methods/canvases.access.delete `canvases.access.delete` API reference}. + */ + delete: bindApiCall(this, "canvases.access.delete"), + /** + * @description Sets the access level to a canvas for specified entities. + * @see {@link https://api.slack.com/methods/canvases.access.set `canvases.access.set` API reference}. + */ + set: bindApiCall(this, "canvases.access.set") + }, + /** + * @description Create Canvas for a user. + * @see {@link https://api.slack.com/methods/canvases.create `canvases.create` API reference}. + */ + create: bindApiCallWithOptionalArgument(this, "canvases.create"), + /** + * @description Deletes a canvas. + * @see {@link https://api.slack.com/methods/canvases.delete `canvases.delete` API reference}. + */ + delete: bindApiCall(this, "canvases.delete"), + /** + * @description Update an existing canvas. + * @see {@link https://api.slack.com/methods/canvases.edit `canvases.edit` API reference}. + */ + edit: bindApiCall(this, "canvases.edit"), + sections: { + /** + * @description Find sections matching the provided criteria. + * @see {@link https://api.slack.com/methods/canvases.sections.lookup `canvases.sections.lookup` API reference}. + */ + lookup: bindApiCall(this, "canvases.sections.lookup") + } + }; + this.chat = { + /** + * @description Deletes a message. + * @see {@link https://api.slack.com/methods/chat.delete `chat.delete` API reference}. + */ + delete: bindApiCall(this, "chat.delete"), + /** + * @description Deletes a pending scheduled message from the queue. + * @see {@link https://api.slack.com/methods/chat.deleteScheduledMessage `chat.deleteScheduledMessage` API reference}. + */ + deleteScheduledMessage: bindApiCall(this, "chat.deleteScheduledMessage"), + /** + * @description Retrieve a permalink URL for a specific extant message. + * @see {@link https://api.slack.com/methods/chat.getPermalink `chat.getPermalink` API reference}. + */ + getPermalink: bindApiCall(this, "chat.getPermalink"), + /** + * @description Share a me message into a channel. + * @see {@link https://api.slack.com/methods/chat.meMessage `chat.meMessage` API reference}. + */ + meMessage: bindApiCall(this, "chat.meMessage"), + /** + * @description Sends an ephemeral message to a user in a channel. + * @see {@link https://api.slack.com/methods/chat.postEphemeral `chat.postEphemeral` API reference}. + */ + postEphemeral: bindApiCall(this, "chat.postEphemeral"), + /** + * @description Sends a message to a channel. + * @see {@link https://api.slack.com/methods/chat.postMessage `chat.postMessage` API reference}. + */ + postMessage: bindApiCall(this, "chat.postMessage"), + /** + * @description Schedules a message to be sent to a channel. + * @see {@link https://api.slack.com/methods/chat.scheduleMessage `chat.scheduleMessage` API reference}. + */ + scheduleMessage: bindApiCall(this, "chat.scheduleMessage"), + scheduledMessages: { + /** + * @description Returns a list of scheduled messages. + * @see {@link https://api.slack.com/methods/chat.scheduledMessages.list `chat.scheduledMessages.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "chat.scheduledMessages.list") + }, + /** + * @description Provide custom unfurl behavior for user-posted URLs. + * @see {@link https://api.slack.com/methods/chat.unfurl `chat.unfurl` API reference}. + */ + unfurl: bindApiCall(this, "chat.unfurl"), + /** + * @description Updates a message. + * @see {@link https://api.slack.com/methods/chat.update `chat.update` API reference}. + */ + update: bindApiCall(this, "chat.update") + }; + this.conversations = { + /** + * @description Accepts an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.acceptSharedInvite `conversations.acceptSharedInvite` API reference}. + */ + acceptSharedInvite: bindApiCall(this, "conversations.acceptSharedInvite"), + /** + * @description Approves an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.approveSharedInvite `conversations.approveSharedInvite` API reference}. + */ + approveSharedInvite: bindApiCall(this, "conversations.approveSharedInvite"), + /** + * @description Archives a conversation. + * @see {@link https://api.slack.com/methods/conversations.archive `conversations.archive` API reference}. + */ + archive: bindApiCall(this, "conversations.archive"), + canvases: { + /** + * @description Create a Channel Canvas for a channel. + * @see {@link https://api.slack.com/methods/conversations.canvases.create `conversations.canvases.create` API reference}. + */ + create: bindApiCall(this, "conversations.canvases.create") + }, + /** + * @description Closes a direct message or multi-person direct message. + * @see {@link https://api.slack.com/methods/conversations.close `conversations.close` API reference}. + */ + close: bindApiCall(this, "conversations.close"), + /** + * @description Initiates a public or private channel-based conversation. + * @see {@link https://api.slack.com/methods/conversations.create `conversations.create` API reference}. + */ + create: bindApiCall(this, "conversations.create"), + /** + * @description Declines an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.declineSharedInvite `conversations.declineSharedInvite` API reference}. + */ + declineSharedInvite: bindApiCall(this, "conversations.declineSharedInvite"), + externalInvitePermissions: { + /** + * @description Convert a team in a shared channel from an External Limited channel to a fully shared Slack + * Connect channel or vice versa. + * @see {@link https://api.slack.com/methods/conversations.externalInvitePermissions.set `conversations.externalInvitePermissions.set` API reference}. + */ + set: bindApiCall(this, "conversations.externalInvitePermissions.set") + }, + /** + * @description Fetches a conversation's history of messages and events. + * @see {@link https://api.slack.com/methods/conversations.history `conversations.history` API reference}. + */ + history: bindApiCall(this, "conversations.history"), + /** + * @description Retrieve information about a conversation. + * @see {@link https://api.slack.com/methods/conversations.info `conversations.info` API reference}. + */ + info: bindApiCall(this, "conversations.info"), + /** + * @description Invites users to a channel. + * @see {@link https://api.slack.com/methods/conversations.invite `conversations.invite` API reference}. + */ + invite: bindApiCall(this, "conversations.invite"), + /** + * @description Sends an invitation to a Slack Connect channel. + * @see {@link https://api.slack.com/methods/conversations.inviteShared `conversations.inviteShared` API reference}. + */ + inviteShared: bindApiCall(this, "conversations.inviteShared"), + /** + * @description Joins an existing conversation. + * @see {@link https://api.slack.com/methods/conversations.join `conversations.join` API reference}. + */ + join: bindApiCall(this, "conversations.join"), + /** + * @description Removes a user from a conversation. + * @see {@link https://api.slack.com/methods/conversations.kick `conversations.kick` API reference}. + */ + kick: bindApiCall(this, "conversations.kick"), + /** + * @description Leaves a conversation. + * @see {@link https://api.slack.com/methods/conversations.leave `conversations.leave` API reference}. + */ + leave: bindApiCall(this, "conversations.leave"), + /** + * @description List all channels in a Slack team. + * @see {@link https://api.slack.com/methods/conversations.list `conversations.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "conversations.list"), + /** + * @description Lists shared channel invites that have been generated or received but have not been approved by + * all parties. + * @see {@link https://api.slack.com/methods/conversations.listConnectInvites `conversations.listConnectInvites` API reference}. + */ + listConnectInvites: bindApiCallWithOptionalArgument(this, "conversations.listConnectInvites"), + /** + * @description Sets the read cursor in a channel. + * @see {@link https://api.slack.com/methods/conversations.mark `conversations.mark` API reference}. + */ + mark: bindApiCall(this, "conversations.mark"), + /** + * @description Retrieve members of a conversation. + * @see {@link https://api.slack.com/methods/conversations.members `conversations.members` API reference}. + */ + members: bindApiCall(this, "conversations.members"), + /** + * @description Opens or resumes a direct message or multi-person direct message. + * @see {@link https://api.slack.com/methods/conversations.open `conversations.open` API reference}. + */ + open: bindApiCall(this, "conversations.open"), + /** + * @description Renames a conversation. + * @see {@link https://api.slack.com/methods/conversations.rename `conversations.rename` API reference}. + */ + rename: bindApiCall(this, "conversations.rename"), + /** + * @description Retrieve a thread of messages posted to a conversation. + * @see {@link https://api.slack.com/methods/conversations.replies `conversations.replies` API reference}. + */ + replies: bindApiCall(this, "conversations.replies"), + requestSharedInvite: { + /** + * @description Approves a request to add an external user to a channel and sends them a Slack Connect invite. + * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.approve `conversations.requestSharedInvite.approve` API reference}. + */ + approve: bindApiCall(this, "conversations.requestSharedInvite.approve"), + /** + * @description Denies a request to invite an external user to a channel. + * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.deny `conversations.requestSharedInvite.deny` API reference}. + */ + deny: bindApiCall(this, "conversations.requestSharedInvite.deny"), + /** + * @description Lists requests to add external users to channels with ability to filter. + * @see {@link https://api.slack.com/methods/conversations.requestSharedInvite.list `conversations.requestSharedInvite.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "conversations.requestSharedInvite.list") + }, + /** + * @description Sets the purpose for a conversation. + * @see {@link https://api.slack.com/methods/conversations.setPurpose `conversations.setPurpose` API reference}. + */ + setPurpose: bindApiCall(this, "conversations.setPurpose"), + /** + * @description Sets the topic for a conversation. + * @see {@link https://api.slack.com/methods/conversations.setTopic `conversations.setTopic` API reference}. + */ + setTopic: bindApiCall(this, "conversations.setTopic"), + /** + * @description Reverses conversation archival. + * @see {@link https://api.slack.com/methods/conversations.unarchive `conversations.unarchive` API reference}. + */ + unarchive: bindApiCall(this, "conversations.unarchive") + }; + this.dialog = { + /** + * @description Open a dialog with a user. + * @see {@link https://api.slack.com/methods/dialog.open `dialog.open` API reference}. + */ + open: bindApiCall(this, "dialog.open") + }; + this.dnd = { + /** + * @description Ends the current user's Do Not Disturb session immediately. + * @see {@link https://api.slack.com/methods/dnd.endDnd `dnd.endDnd` API reference}. + */ + endDnd: bindApiCallWithOptionalArgument(this, "dnd.endDnd"), + /** + * @description Ends the current user's snooze mode immediately. + * @see {@link https://api.slack.com/methods/dnd.endSnooze `dnd.endSnooze` API reference}. + */ + endSnooze: bindApiCallWithOptionalArgument(this, "dnd.endSnooze"), + /** + * @description Retrieves a user's current Do Not Disturb status. + * @see {@link https://api.slack.com/methods/dnd.info `dnd.info` API reference}. + */ + info: bindApiCallWithOptionalArgument(this, "dnd.info"), + /** + * @description Turns on Do Not Disturb mode for the current user, or changes its duration. + * @see {@link https://api.slack.com/methods/dnd.setSnooze `dnd.setSnooze` API reference}. + */ + setSnooze: bindApiCall(this, "dnd.setSnooze"), + /** + * @description Retrieves the Do Not Disturb status for up to 50 users on a team. + * @see {@link https://api.slack.com/methods/dnd.teamInfo `dnd.teamInfo` API reference}. + */ + teamInfo: bindApiCall(this, "dnd.teamInfo") + }; + this.emoji = { + /** + * @description Lists custom emoji for a team. + * @see {@link https://api.slack.com/methods/emoji.list `emoji.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "emoji.list") + }; + this.files = { + /** + * @description Finishes an upload started with {@link https://api.slack.com/methods/files.getUploadURLExternal `files.getUploadURLExternal`}. + * @see {@link https://api.slack.com/methods/files.completeUploadExternal `files.completeUploadExternal` API reference}. + */ + completeUploadExternal: bindApiCall(this, "files.completeUploadExternal"), + /** + * @description Deletes a file. + * @see {@link https://api.slack.com/methods/files.delete `files.delete` API reference}. + */ + delete: bindApiCall(this, "files.delete"), + /** + * @description Gets a URL for an edge external file upload. + * @see {@link https://api.slack.com/methods/files.getUploadURLExternal `files.getUploadURLExternal` API reference}. + */ + getUploadURLExternal: bindApiCall(this, "files.getUploadURLExternal"), + /** + * @description Gets information about a file. + * @see {@link https://api.slack.com/methods/files.info `files.info` API reference}. + */ + info: bindApiCall(this, "files.info"), + /** + * @description List files for a team, in a channel, or from a user with applied filters. + * @see {@link https://api.slack.com/methods/files.list `files.list` API reference}. + */ + list: bindApiCall(this, "files.list"), + /** + * @description Revokes public/external sharing access for a file. + * @see {@link https://api.slack.com/methods/files.revokePublicURL `files.revokePublicURL` API reference}. + */ + revokePublicURL: bindApiCall(this, "files.revokePublicURL"), + /** + * @description Enables a file for public/external sharing. + * @see {@link https://api.slack.com/methods/files.revokePublicURL `files.revokePublicURL` API reference}. + */ + sharedPublicURL: bindApiCall(this, "files.sharedPublicURL"), + /** + * @description Uploads or creates a file. + * @deprecated Use `uploadV2` instead. See {@link https://api.slack.com/changelog/2024-04-a-better-way-to-upload-files-is-here-to-stay our post on retiring `files.upload`}. + * @see {@link https://api.slack.com/methods/files.upload `files.upload` API reference}. + */ + upload: bindApiCall(this, "files.upload"), + /** + * @description Custom method to support a new way of uploading files to Slack. + * Supports a single file upload + * Supply: + * - (required) single file or content + * - (optional) channel, alt_text, snippet_type, + * Supports multiple file uploads + * Supply: + * - multiple upload_files + * Will try to honor both single file or content data supplied as well + * as multiple file uploads property. + * @see {@link https://tools.slack.dev/node-slack-sdk/web-api#upload-a-file `@slack/web-api` Upload a file documentation}. + */ + uploadV2: bindFilesUploadV2(this), + comments: { + /** + * @description Deletes an existing comment on a file. + * @see {@link https://api.slack.com/methods/files.comments.delete `files.comments.delete` API reference}. + */ + delete: bindApiCall(this, "files.comments.delete") + }, + remote: { + /** + * @description Adds a file from a remote service. + * @see {@link https://api.slack.com/methods/files.remote.add `files.remote.add` API reference}. + */ + add: bindApiCall(this, "files.remote.add"), + /** + * @description Retrieve information about a remote file added to Slack. + * @see {@link https://api.slack.com/methods/files.remote.info `files.remote.info` API reference}. + */ + info: bindApiCall(this, "files.remote.info"), + /** + * @description List remote files added to Slack. + * @see {@link https://api.slack.com/methods/files.remote.list `files.remote.list` API reference}. + */ + list: bindApiCall(this, "files.remote.list"), + /** + * @description Remove a remote file. + * @see {@link https://api.slack.com/methods/files.remote.remove `files.remote.remove` API reference}. + */ + remove: bindApiCall(this, "files.remote.remove"), + /** + * @description Share a remote file into a channel. + * @see {@link https://api.slack.com/methods/files.remote.share `files.remote.share` API reference}. + */ + share: bindApiCall(this, "files.remote.share"), + /** + * @description Updates an existing remote file. + * @see {@link https://api.slack.com/methods/files.remote.update `files.remote.update` API reference}. + */ + update: bindApiCall(this, "files.remote.update") } - S[0] || S.shift(); - } - if (f == 1) T.e = c, xs = g; - else { - for (p = 1, d = S[0]; d >= 10; d /= 10) p++; - T.e = p + c * f - 1, y(T, a ? o + T.e + 1 : o, s, g); - } - return T; - }; - }(); - function y(e, t, r, n) { - var i, o, s, a, l, u, c, p, d, f = e.constructor; - e: if (t != null) { - if (p = e.d, !p) return e; - for (i = 1, a = p[0]; a >= 10; a /= 10) i++; - if (o = t - i, o < 0) o += b, s = t, c = p[d = 0], l = c / G(10, i - s - 1) % 10 | 0; - else if (d = Math.ceil((o + 1) / b), a = p.length, d >= a) if (n) { - for (; a++ <= d; ) p.push(0); - c = l = 0, i = 1, o %= b, s = o - b + 1; - } else break e; - else { - for (c = a = p[d], i = 1; a >= 10; a /= 10) i++; - o %= b, s = o - b + i, l = s < 0 ? 0 : c / G(10, i - s - 1) % 10 | 0; - } - if (n = n || t < 0 || p[d + 1] !== void 0 || (s < 0 ? c : c % G(10, i - s - 1)), u = r < 4 ? (l || n) && (r == 0 || r == (e.s < 0 ? 3 : 2)) : l > 5 || l == 5 && (r == 4 || n || r == 6 && (o > 0 ? s > 0 ? c / G(10, i - s) : 0 : p[d - 1]) % 10 & 1 || r == (e.s < 0 ? 8 : 7)), t < 1 || !p[0]) return p.length = 0, u ? (t -= e.e + 1, p[0] = G(10, (b - t % b) % b), e.e = -t || 0) : p[0] = e.e = 0, e; - if (o == 0 ? (p.length = d, a = 1, d--) : (p.length = d + 1, a = G(10, b - o), p[d] = s > 0 ? (c / G(10, i - s) % G(10, s) | 0) * a : 0), u) for (; ; ) if (d == 0) { - for (o = 1, s = p[0]; s >= 10; s /= 10) o++; - for (s = p[0] += a, a = 1; s >= 10; s /= 10) a++; - o != a && (e.e++, p[0] == ge && (p[0] = 1)); - break; - } else { - if (p[d] += a, p[d] != ge) break; - p[d--] = 0, a = 1; - } - for (o = p.length; p[--o] === 0; ) p.pop(); - } - return x && (e.e > f.maxE ? (e.d = null, e.e = NaN) : e.e < f.minE && (e.e = 0, e.d = [0])), e; - } - function we(e, t, r) { - if (!e.isFinite()) return Is(e); - var n, i = e.e, o = K(e.d), s = o.length; - return t ? (r && (n = r - s) > 0 ? o = o.charAt(0) + "." + o.slice(1) + We(n) : s > 1 && (o = o.charAt(0) + "." + o.slice(1)), o = o + (e.e < 0 ? "e" : "e+") + e.e) : i < 0 ? (o = "0." + We(-i - 1) + o, r && (n = r - s) > 0 && (o += We(n))) : i >= s ? (o += We(i + 1 - s), r && (n = r - i - 1) > 0 && (o = o + "." + We(n))) : ((n = i + 1) < s && (o = o.slice(0, n) + "." + o.slice(n)), r && (n = r - s) > 0 && (i + 1 === s && (o += "."), o += We(n))), o; - } - function sn(e, t) { - var r = e[0]; - for (t *= b; r >= 10; r /= 10) t++; - return t; - } - function nn(e, t, r) { - if (t > Pc) throw x = true, r && (e.precision = r), Error(Ps); - return y(new e(tn), t, 1, true); - } - function fe(e, t, r) { - if (t > Ti) throw Error(Ps); - return y(new e(rn), t, r, true); - } - function Cs(e) { - var t = e.length - 1, r = t * b + 1; - if (t = e[t], t) { - for (; t % 10 == 0; t /= 10) r--; - for (t = e[0]; t >= 10; t /= 10) r++; - } - return r; - } - function We(e) { - for (var t = ""; e--; ) t += "0"; - return t; - } - function Ss(e, t, r, n) { - var i, o = new e(1), s = Math.ceil(n / b + 4); - for (x = false; ; ) { - if (r % 2 && (o = o.times(t), Es(o.d, s) && (i = true)), r = ee(r / 2), r === 0) { - r = o.d.length - 1, i && o.d[r] === 0 && ++o.d[r]; - break; - } - t = t.times(t), Es(t.d, s); - } - return x = true, o; - } - function bs(e) { - return e.d[e.d.length - 1] & 1; - } - function As(e, t, r) { - for (var n, i = new e(t[0]), o = 0; ++o < t.length; ) if (n = new e(t[o]), n.s) i[r](n) && (i = n); - else { - i = n; - break; - } - return i; - } - function Ri(e, t) { - var r, n, i, o, s, a, l, u = 0, c = 0, p = 0, d = e.constructor, f = d.rounding, g = d.precision; - if (!e.d || !e.d[0] || e.e > 17) return new d(e.d ? e.d[0] ? e.s < 0 ? 0 : 1 / 0 : 1 : e.s ? e.s < 0 ? 0 : e : NaN); - for (t == null ? (x = false, l = g) : l = t, a = new d(0.03125); e.e > -2; ) e = e.times(a), p += 5; - for (n = Math.log(G(2, p)) / Math.LN10 * 2 + 5 | 0, l += n, r = o = s = new d(1), d.precision = l; ; ) { - if (o = y(o.times(e), l, 1), r = r.times(++c), a = s.plus(N(o, r, l, 1)), K(a.d).slice(0, l) === K(s.d).slice(0, l)) { - for (i = p; i--; ) s = y(s.times(s), l, 1); - if (t == null) if (u < 3 && rr(s.d, l - n, f, u)) d.precision = l += 10, r = o = a = new d(1), c = 0, u++; - else return y(s, d.precision = g, f, x = true); - else return d.precision = g, s; - } - s = a; - } - } - function He(e, t) { - var r, n, i, o, s, a, l, u, c, p, d, f = 1, g = 10, h = e, O = h.d, T = h.constructor, S = T.rounding, C = T.precision; - if (h.s < 0 || !O || !O[0] || !h.e && O[0] == 1 && O.length == 1) return new T(O && !O[0] ? -1 / 0 : h.s != 1 ? NaN : O ? 0 : h); - if (t == null ? (x = false, c = C) : c = t, T.precision = c += g, r = K(O), n = r.charAt(0), Math.abs(o = h.e) < 15e14) { - for (; n < 7 && n != 1 || n == 1 && r.charAt(1) > 3; ) h = h.times(e), r = K(h.d), n = r.charAt(0), f++; - o = h.e, n > 1 ? (h = new T("0." + r), o++) : h = new T(n + "." + r.slice(1)); - } else return u = nn(T, c + 2, C).times(o + ""), h = He(new T(n + "." + r.slice(1)), c - g).plus(u), T.precision = C, t == null ? y(h, C, S, x = true) : h; - for (p = h, l = s = h = N(h.minus(1), h.plus(1), c, 1), d = y(h.times(h), c, 1), i = 3; ; ) { - if (s = y(s.times(d), c, 1), u = l.plus(N(s, new T(i), c, 1)), K(u.d).slice(0, c) === K(l.d).slice(0, c)) if (l = l.times(2), o !== 0 && (l = l.plus(nn(T, c + 2, C).times(o + ""))), l = N(l, new T(f), c, 1), t == null) if (rr(l.d, c - g, S, a)) T.precision = c += g, u = s = h = N(p.minus(1), p.plus(1), c, 1), d = y(h.times(h), c, 1), i = a = 1; - else return y(l, T.precision = C, S, x = true); - else return T.precision = C, l; - l = u, i += 2; - } - } - function Is(e) { - return String(e.s * e.s / 0); - } - function Ci(e, t) { - var r, n, i; - for ((r = t.indexOf(".")) > -1 && (t = t.replace(".", "")), (n = t.search(/e/i)) > 0 ? (r < 0 && (r = n), r += +t.slice(n + 1), t = t.substring(0, n)) : r < 0 && (r = t.length), n = 0; t.charCodeAt(n) === 48; n++) ; - for (i = t.length; t.charCodeAt(i - 1) === 48; --i) ; - if (t = t.slice(n, i), t) { - if (i -= n, e.e = r = r - n - 1, e.d = [], n = (r + 1) % b, r < 0 && (n += b), n < i) { - for (n && e.d.push(+t.slice(0, n)), i -= b; n < i; ) e.d.push(+t.slice(n, n += b)); - t = t.slice(n), n = b - t.length; - } else n -= i; - for (; n--; ) t += "0"; - e.d.push(+t), x && (e.e > e.constructor.maxE ? (e.d = null, e.e = NaN) : e.e < e.constructor.minE && (e.e = 0, e.d = [0])); - } else e.e = 0, e.d = [0]; - return e; - } - function Tc(e, t) { - var r, n, i, o, s, a, l, u, c; - if (t.indexOf("_") > -1) { - if (t = t.replace(/(\d)_(?=\d)/g, "$1"), Rs.test(t)) return Ci(e, t); - } else if (t === "Infinity" || t === "NaN") return +t || (e.s = NaN), e.e = NaN, e.d = null, e; - if (Ec.test(t)) r = 16, t = t.toLowerCase(); - else if (bc.test(t)) r = 2; - else if (wc.test(t)) r = 8; - else throw Error(Ke + t); - for (o = t.search(/p/i), o > 0 ? (l = +t.slice(o + 1), t = t.substring(2, o)) : t = t.slice(2), o = t.indexOf("."), s = o >= 0, n = e.constructor, s && (t = t.replace(".", ""), a = t.length, o = a - o, i = Ss(n, new n(r), o, o * 2)), u = en(t, r, ge), c = u.length - 1, o = c; u[o] === 0; --o) u.pop(); - return o < 0 ? new n(e.s * 0) : (e.e = sn(u, c), e.d = u, x = false, s && (e = N(e, i, a * 4)), l && (e = e.times(Math.abs(l) < 54 ? G(2, l) : it.pow(2, l))), x = true, e); - } - function Rc(e, t) { - var r, n = t.d.length; - if (n < 3) return t.isZero() ? t : Et(e, 2, t, t); - r = 1.4 * Math.sqrt(n), r = r > 16 ? 16 : r | 0, t = t.times(1 / an(5, r)), t = Et(e, 2, t, t); - for (var i, o = new e(5), s = new e(16), a = new e(20); r--; ) i = t.times(t), t = t.times(o.plus(i.times(s.times(i).minus(a)))); - return t; - } - function Et(e, t, r, n, i) { - var o, s, a, l, u = 1, c = e.precision, p = Math.ceil(c / b); - for (x = false, l = r.times(r), a = new e(n); ; ) { - if (s = N(a.times(l), new e(t++ * t++), c, 1), a = i ? n.plus(s) : n.minus(s), n = N(s.times(l), new e(t++ * t++), c, 1), s = a.plus(n), s.d[p] !== void 0) { - for (o = p; s.d[o] === a.d[o] && o--; ) ; - if (o == -1) break; - } - o = a, a = n, n = s, s = o, u++; - } - return x = true, s.d.length = p + 1, s; - } - function an(e, t) { - for (var r = e; --t; ) r *= e; - return r; - } - function Os(e, t) { - var r, n = t.s < 0, i = fe(e, e.precision, 1), o = i.times(0.5); - if (t = t.abs(), t.lte(o)) return Ne = n ? 4 : 1, t; - if (r = t.divToInt(i), r.isZero()) Ne = n ? 3 : 2; - else { - if (t = t.minus(r.times(i)), t.lte(o)) return Ne = bs(r) ? n ? 2 : 3 : n ? 4 : 1, t; - Ne = bs(r) ? n ? 1 : 4 : n ? 3 : 2; - } - return t.minus(i).abs(); - } - function Si(e, t, r, n) { - var i, o, s, a, l, u, c, p, d, f = e.constructor, g = r !== void 0; - if (g ? (ie(r, 1, ze), n === void 0 ? n = f.rounding : ie(n, 0, 8)) : (r = f.precision, n = f.rounding), !e.isFinite()) c = Is(e); - else { - for (c = we(e), s = c.indexOf("."), g ? (i = 2, t == 16 ? r = r * 4 - 3 : t == 8 && (r = r * 3 - 2)) : i = t, s >= 0 && (c = c.replace(".", ""), d = new f(1), d.e = c.length - s, d.d = en(we(d), 10, i), d.e = d.d.length), p = en(c, 10, i), o = l = p.length; p[--l] == 0; ) p.pop(); - if (!p[0]) c = g ? "0p+0" : "0"; - else { - if (s < 0 ? o-- : (e = new f(e), e.d = p, e.e = o, e = N(e, d, r, n, 0, i), p = e.d, o = e.e, u = xs), s = p[r], a = i / 2, u = u || p[r + 1] !== void 0, u = n < 4 ? (s !== void 0 || u) && (n === 0 || n === (e.s < 0 ? 3 : 2)) : s > a || s === a && (n === 4 || u || n === 6 && p[r - 1] & 1 || n === (e.s < 0 ? 8 : 7)), p.length = r, u) for (; ++p[--r] > i - 1; ) p[r] = 0, r || (++o, p.unshift(1)); - for (l = p.length; !p[l - 1]; --l) ; - for (s = 0, c = ""; s < l; s++) c += Pi.charAt(p[s]); - if (g) { - if (l > 1) if (t == 16 || t == 8) { - for (s = t == 16 ? 4 : 3, --l; l % s; l++) c += "0"; - for (p = en(c, i, t), l = p.length; !p[l - 1]; --l) ; - for (s = 1, c = "1."; s < l; s++) c += Pi.charAt(p[s]); - } else c = c.charAt(0) + "." + c.slice(1); - c = c + (o < 0 ? "p" : "p+") + o; - } else if (o < 0) { - for (; ++o; ) c = "0" + c; - c = "0." + c; - } else if (++o > l) for (o -= l; o--; ) c += "0"; - else o < l && (c = c.slice(0, o) + "." + c.slice(o)); - } - c = (t == 16 ? "0x" : t == 2 ? "0b" : t == 8 ? "0o" : "") + c; - } - return e.s < 0 ? "-" + c : c; - } - function Es(e, t) { - if (e.length > t) return e.length = t, true; - } - function Cc(e) { - return new this(e).abs(); - } - function Sc(e) { - return new this(e).acos(); - } - function Ac(e) { - return new this(e).acosh(); - } - function Ic(e, t) { - return new this(e).plus(t); - } - function Oc(e) { - return new this(e).asin(); - } - function kc(e) { - return new this(e).asinh(); - } - function Dc(e) { - return new this(e).atan(); - } - function _c(e) { - return new this(e).atanh(); - } - function Fc(e, t) { - e = new this(e), t = new this(t); - var r, n = this.precision, i = this.rounding, o = n + 4; - return !e.s || !t.s ? r = new this(NaN) : !e.d && !t.d ? (r = fe(this, o, 1).times(t.s > 0 ? 0.25 : 0.75), r.s = e.s) : !t.d || e.isZero() ? (r = t.s < 0 ? fe(this, n, i) : new this(0), r.s = e.s) : !e.d || t.isZero() ? (r = fe(this, o, 1).times(0.5), r.s = e.s) : t.s < 0 ? (this.precision = o, this.rounding = 1, r = this.atan(N(e, t, o, 1)), t = fe(this, o, 1), this.precision = n, this.rounding = i, r = e.s < 0 ? r.minus(t) : r.plus(t)) : r = this.atan(N(e, t, o, 1)), r; - } - function Lc(e) { - return new this(e).cbrt(); - } - function Nc(e) { - return y(e = new this(e), e.e + 1, 2); - } - function Mc(e, t, r) { - return new this(e).clamp(t, r); - } - function $c(e) { - if (!e || typeof e != "object") throw Error(on + "Object expected"); - var t, r, n, i = e.defaults === true, o = ["precision", 1, ze, "rounding", 0, 8, "toExpNeg", -bt, 0, "toExpPos", 0, bt, "maxE", 0, bt, "minE", -bt, 0, "modulo", 0, 9]; - for (t = 0; t < o.length; t += 3) if (r = o[t], i && (this[r] = vi[r]), (n = e[r]) !== void 0) if (ee(n) === n && n >= o[t + 1] && n <= o[t + 2]) this[r] = n; - else throw Error(Ke + r + ": " + n); - if (r = "crypto", i && (this[r] = vi[r]), (n = e[r]) !== void 0) if (n === true || n === false || n === 0 || n === 1) if (n) if (typeof crypto < "u" && crypto && (crypto.getRandomValues || crypto.randomBytes)) this[r] = true; - else throw Error(vs); - else this[r] = false; - else throw Error(Ke + r + ": " + n); - return this; - } - function qc(e) { - return new this(e).cos(); - } - function jc(e) { - return new this(e).cosh(); - } - function ks(e) { - var t, r, n; - function i(o) { - var s, a, l, u = this; - if (!(u instanceof i)) return new i(o); - if (u.constructor = i, ws(o)) { - u.s = o.s, x ? !o.d || o.e > i.maxE ? (u.e = NaN, u.d = null) : o.e < i.minE ? (u.e = 0, u.d = [0]) : (u.e = o.e, u.d = o.d.slice()) : (u.e = o.e, u.d = o.d ? o.d.slice() : o.d); - return; - } - if (l = typeof o, l === "number") { - if (o === 0) { - u.s = 1 / o < 0 ? -1 : 1, u.e = 0, u.d = [0]; - return; + }; + this.functions = { + /** + * @description Signal the failure to execute a Custom Function. + * @see {@link https://api.slack.com/methods/functions.completeError `functions.completeError` API reference}. + */ + completeError: bindApiCall(this, "functions.completeError"), + /** + * @description Signal the successful completion of a Custom Function. + * @see {@link https://api.slack.com/methods/functions.completeSuccess `functions.completeSuccess` API reference}. + */ + completeSuccess: bindApiCall(this, "functions.completeSuccess") + }; + this.migration = { + /** + * @description For Enterprise Grid workspaces, map local user IDs to global user IDs. + * @see {@link https://api.slack.com/methods/migration.exchange `migration.exchange` API reference}. + */ + exchange: bindApiCall(this, "migration.exchange") + }; + this.oauth = { + /** + * @description Exchanges a temporary OAuth verifier code for an access token. + * @deprecated This is a legacy method only used by classic Slack apps. Use `oauth.v2.access` for new Slack apps. + * @see {@link https://api.slack.com/methods/oauth.access `oauth.access` API reference}. + */ + access: bindApiCall(this, "oauth.access"), + v2: { + /** + * @description Exchanges a temporary OAuth verifier code for an access token. + * @see {@link https://api.slack.com/methods/oauth.v2.access `oauth.v2.access` API reference}. + */ + access: bindApiCall(this, "oauth.v2.access"), + /** + * @description Exchanges a legacy access token for a new expiring access token and refresh token. + * @see {@link https://api.slack.com/methods/oauth.v2.exchange `oauth.v2.exchange` API reference}. + */ + exchange: bindApiCall(this, "oauth.v2.exchange") } - if (o < 0 ? (o = -o, u.s = -1) : u.s = 1, o === ~~o && o < 1e7) { - for (s = 0, a = o; a >= 10; a /= 10) s++; - x ? s > i.maxE ? (u.e = NaN, u.d = null) : s < i.minE ? (u.e = 0, u.d = [0]) : (u.e = s, u.d = [o]) : (u.e = s, u.d = [o]); - return; - } else if (o * 0 !== 0) { - o || (u.s = NaN), u.e = NaN, u.d = null; - return; + }; + this.openid = { + connect: { + /** + * @description Exchanges a temporary OAuth verifier code for an access token for {@link https://api.slack.com/authentication/sign-in-with-slack Sign in with Slack}. + * @see {@link https://api.slack.com/methods/openid.connect.token `openid.connect.token` API reference}. + */ + token: bindApiCall(this, "openid.connect.token"), + /** + * @description Get the identity of a user who has authorized {@link https://api.slack.com/authentication/sign-in-with-slack Sign in with Slack}. + * @see {@link https://api.slack.com/methods/openid.connect.userInfo `openid.connect.userInfo` API reference}. + */ + userInfo: bindApiCallWithOptionalArgument(this, "openid.connect.userInfo") } - return Ci(u, o.toString()); - } else if (l !== "string") throw Error(Ke + o); - return (a = o.charCodeAt(0)) === 45 ? (o = o.slice(1), u.s = -1) : (a === 43 && (o = o.slice(1)), u.s = 1), Rs.test(o) ? Ci(u, o) : Tc(u, o); - } - if (i.prototype = m, i.ROUND_UP = 0, i.ROUND_DOWN = 1, i.ROUND_CEIL = 2, i.ROUND_FLOOR = 3, i.ROUND_HALF_UP = 4, i.ROUND_HALF_DOWN = 5, i.ROUND_HALF_EVEN = 6, i.ROUND_HALF_CEIL = 7, i.ROUND_HALF_FLOOR = 8, i.EUCLID = 9, i.config = i.set = $c, i.clone = ks, i.isDecimal = ws, i.abs = Cc, i.acos = Sc, i.acosh = Ac, i.add = Ic, i.asin = Oc, i.asinh = kc, i.atan = Dc, i.atanh = _c, i.atan2 = Fc, i.cbrt = Lc, i.ceil = Nc, i.clamp = Mc, i.cos = qc, i.cosh = jc, i.div = Vc, i.exp = Bc, i.floor = Uc, i.hypot = Gc, i.ln = Qc, i.log = Jc, i.log10 = Hc, i.log2 = Wc, i.max = Kc, i.min = zc, i.mod = Yc, i.mul = Zc, i.pow = Xc, i.random = ep, i.round = tp, i.sign = rp, i.sin = np, i.sinh = ip, i.sqrt = op, i.sub = sp, i.sum = ap, i.tan = lp, i.tanh = up, i.trunc = cp, e === void 0 && (e = {}), e && e.defaults !== true) for (n = ["precision", "rounding", "toExpNeg", "toExpPos", "maxE", "minE", "modulo", "crypto"], t = 0; t < n.length; ) e.hasOwnProperty(r = n[t++]) || (e[r] = this[r]); - return i.config(e), i; - } - function Vc(e, t) { - return new this(e).div(t); - } - function Bc(e) { - return new this(e).exp(); - } - function Uc(e) { - return y(e = new this(e), e.e + 1, 3); - } - function Gc() { - var e, t, r = new this(0); - for (x = false, e = 0; e < arguments.length; ) if (t = new this(arguments[e++]), t.d) r.d && (r = r.plus(t.times(t))); - else { - if (t.s) return x = true, new this(1 / 0); - r = t; - } - return x = true, r.sqrt(); - } - function ws(e) { - return e instanceof it || e && e.toStringTag === Ts || false; - } - function Qc(e) { - return new this(e).ln(); - } - function Jc(e, t) { - return new this(e).log(t); - } - function Wc(e) { - return new this(e).log(2); - } - function Hc(e) { - return new this(e).log(10); - } - function Kc() { - return As(this, arguments, "lt"); - } - function zc() { - return As(this, arguments, "gt"); - } - function Yc(e, t) { - return new this(e).mod(t); - } - function Zc(e, t) { - return new this(e).mul(t); - } - function Xc(e, t) { - return new this(e).pow(t); - } - function ep(e) { - var t, r, n, i, o = 0, s = new this(1), a = []; - if (e === void 0 ? e = this.precision : ie(e, 1, ze), n = Math.ceil(e / b), this.crypto) if (crypto.getRandomValues) for (t = crypto.getRandomValues(new Uint32Array(n)); o < n; ) i = t[o], i >= 429e7 ? t[o] = crypto.getRandomValues(new Uint32Array(1))[0] : a[o++] = i % 1e7; - else if (crypto.randomBytes) { - for (t = crypto.randomBytes(n *= 4); o < n; ) i = t[o] + (t[o + 1] << 8) + (t[o + 2] << 16) + ((t[o + 3] & 127) << 24), i >= 214e7 ? crypto.randomBytes(4).copy(t, o) : (a.push(i % 1e7), o += 4); - o = n / 4; - } else throw Error(vs); - else for (; o < n; ) a[o++] = Math.random() * 1e7 | 0; - for (n = a[--o], e %= b, n && e && (i = G(10, b - e), a[o] = (n / i | 0) * i); a[o] === 0; o--) a.pop(); - if (o < 0) r = 0, a = [0]; - else { - for (r = -1; a[0] === 0; r -= b) a.shift(); - for (n = 1, i = a[0]; i >= 10; i /= 10) n++; - n < b && (r -= b - n); - } - return s.e = r, s.d = a, s; - } - function tp(e) { - return y(e = new this(e), e.e + 1, this.rounding); - } - function rp(e) { - return e = new this(e), e.d ? e.d[0] ? e.s : 0 * e.s : e.s || NaN; - } - function np(e) { - return new this(e).sin(); - } - function ip(e) { - return new this(e).sinh(); - } - function op(e) { - return new this(e).sqrt(); - } - function sp(e, t) { - return new this(e).sub(t); - } - function ap() { - var e = 0, t = arguments, r = new this(t[e]); - for (x = false; r.s && ++e < t.length; ) r = r.plus(t[e]); - return x = true, y(r, this.precision, this.rounding); - } - function lp(e) { - return new this(e).tan(); - } - function up(e) { - return new this(e).tanh(); - } - function cp(e) { - return y(e = new this(e), e.e + 1, 1); - } - m[Symbol.for("nodejs.util.inspect.custom")] = m.toString; - m[Symbol.toStringTag] = "Decimal"; - var it = m.constructor = ks(vi); - tn = new it(tn); - rn = new it(rn); - var xe = it; - function wt(e) { - return e === null ? e : Array.isArray(e) ? e.map(wt) : typeof e == "object" ? pp(e) ? dp(e) : yt(e, wt) : e; - } - function pp(e) { - return e !== null && typeof e == "object" && typeof e.$type == "string"; - } - function dp({ $type: e, value: t }) { - switch (e) { - case "BigInt": - return BigInt(t); - case "Bytes": - return Buffer.from(t, "base64"); - case "DateTime": - return new Date(t); - case "Decimal": - return new xe(t); - case "Json": - return JSON.parse(t); - default: - Fe(t, "Unknown tagged value"); - } - } - function xt(e) { - return e.substring(0, 1).toLowerCase() + e.substring(1); - } - function Pt(e) { - return e instanceof Date || Object.prototype.toString.call(e) === "[object Date]"; - } - function ln(e) { - return e.toString() !== "Invalid Date"; - } - function vt(e) { - return it.isDecimal(e) ? true : e !== null && typeof e == "object" && typeof e.s == "number" && typeof e.e == "number" && typeof e.toFixed == "function" && Array.isArray(e.d); - } - var Ms = k(fi()); - var Ns = k(__require("fs")); - var Ds = { keyword: De, entity: De, value: (e) => H(rt(e)), punctuation: rt, directive: De, function: De, variable: (e) => H(rt(e)), string: (e) => H(qe(e)), boolean: ke, number: De, comment: Gt }; - var mp = (e) => e; - var un = {}; - var fp = 0; - var P = { manual: un.Prism && un.Prism.manual, disableWorkerMessageHandler: un.Prism && un.Prism.disableWorkerMessageHandler, util: { encode: function(e) { - if (e instanceof he) { - let t = e; - return new he(t.type, P.util.encode(t.content), t.alias); - } else return Array.isArray(e) ? e.map(P.util.encode) : e.replace(/&/g, "&").replace(/ e.length) return; - if (Ie instanceof he) continue; - if (me && U != t.length - 1) { - S.lastIndex = ne; - var p = S.exec(e); - if (!p) break; - var c = p.index + (E ? p[1].length : 0), d = p.index + p[0].length, a = U, l = ne; - for (let _ = t.length; a < _ && (l < d || !t[a].type && !t[a - 1].greedy); ++a) l += t[a].length, c >= l && (++U, ne = l); - if (t[U] instanceof he) continue; - u = a - U, Ie = e.slice(ne, l), p.index -= ne; - } else { - S.lastIndex = 0; - var p = S.exec(Ie), u = 1; - } - if (!p) { - if (o) break; - continue; - } - E && (ae = p[1] ? p[1].length : 0); - var c = p.index + ae, p = p[0].slice(ae), d = c + p.length, f = Ie.slice(0, c), g = Ie.slice(d); - let z = [U, u]; - f && (++U, ne += f.length, z.push(f)); - let dt = new he(h, C ? P.tokenize(p, C) : p, Bt, p, me); - if (z.push(dt), g && z.push(g), Array.prototype.splice.apply(t, z), u != 1 && P.matchGrammar(e, t, r, U, ne, true, h), o) break; + }; + this.tooling = { + tokens: { + /** + * @description Exchanges a refresh token for a new app configuration token. + * @see {@link https://api.slack.com/methods/tooling.tokens.rotate `tooling.tokens.rotate` API reference}. + */ + rotate: bindApiCall(this, "tooling.tokens.rotate") + } + }; + this.usergroups = { + /** + * @description Create a User Group. + * @see {@link https://api.slack.com/methods/usergroups.create `usergroups.create` API reference}. + */ + create: bindApiCall(this, "usergroups.create"), + /** + * @description Disable an existing User Group. + * @see {@link https://api.slack.com/methods/usergroups.disable `usergroups.disable` API reference}. + */ + disable: bindApiCall(this, "usergroups.disable"), + /** + * @description Enable an existing User Group. + * @see {@link https://api.slack.com/methods/usergroups.enable `usergroups.enable` API reference}. + */ + enable: bindApiCall(this, "usergroups.enable"), + /** + * @description List all User Groups for a team. + * @see {@link https://api.slack.com/methods/usergroups.list `usergroups.list` API reference}. + */ + list: bindApiCallWithOptionalArgument(this, "usergroups.list"), + /** + * @description Update an existing User Group. + * @see {@link https://api.slack.com/methods/usergroups.update `usergroups.update` API reference}. + */ + update: bindApiCall(this, "usergroups.update"), + users: { + /** + * @description List all users in a User Group. + * @see {@link https://api.slack.com/methods/usergroups.users.list `usergroups.users.list` API reference}. + */ + list: bindApiCall(this, "usergroups.users.list"), + /** + * @description Update the list of users in a User Group. + * @see {@link https://api.slack.com/methods/usergroups.users.update `usergroups.users.update` API reference}. + */ + update: bindApiCall(this, "usergroups.users.update") + } + }; + this.users = { + /** + * @description List conversations the calling user may access. + * @see {@link https://api.slack.com/methods/users.conversations `users.conversations` API reference}. + */ + conversations: bindApiCall(this, "users.conversations"), + /** + * @description Delete the user profile photo. + * @see {@link https://api.slack.com/methods/users.deletePhoto `users.deletePhoto` API reference}. + */ + deletePhoto: bindApiCall(this, "users.deletePhoto"), + discoverableContacts: { + /** + * @description Lookup an email address to see if someone is on Slack. + * @see {@link https://api.slack.com/methods/users.discoverableContacts.lookup `users.discoverableContacts.lookup` API reference}. + */ + lookup: bindApiCall(this, "users.discoverableContacts.lookup") + }, + /** + * @description Gets user presence information. + * @see {@link https://api.slack.com/methods/users.getPresence `users.getPresence` API reference}. + */ + getPresence: bindApiCall(this, "users.getPresence"), + /** + * @description Get a user's identity. + * @see {@link https://api.slack.com/methods/users.identity `users.identity` API reference}. + */ + identity: bindApiCall(this, "users.identity"), + /** + * @description Gets information about a user. + * @see {@link https://api.slack.com/methods/users.info `users.info` API reference}. + */ + info: bindApiCall(this, "users.info"), + /** + * @description Lists all users in a Slack team. + * @see {@link https://api.slack.com/methods/users.list `users.list` API reference}. + */ + list: bindApiCall(this, "users.list"), + /** + * @description Find a user with an email address. + * @see {@link https://api.slack.com/methods/users.lookupByEmail `users.lookupByEmail` API reference}. + */ + lookupByEmail: bindApiCall(this, "users.lookupByEmail"), + /** + * @description Set the user profile photo. + * @see {@link https://api.slack.com/methods/users.setPhoto `users.setPhoto` API reference}. + */ + setPhoto: bindApiCall(this, "users.setPhoto"), + /** + * @description Manually sets user presence. + * @see {@link https://api.slack.com/methods/users.setPresence `users.setPresence` API reference}. + */ + setPresence: bindApiCall(this, "users.setPresence"), + profile: { + /** + * @description Retrieve a user's profile information, including their custom status. + * @see {@link https://api.slack.com/methods/users.profile.get `users.profile.get` API reference}. + */ + get: bindApiCall(this, "users.profile.get"), + /** + * @description Set a user's profile information, including custom status. + * @see {@link https://api.slack.com/methods/users.profile.set `users.profile.set` API reference}. + */ + set: bindApiCall(this, "users.profile.set") } + }; + this.views = { + /** + * @description Open a view for a user. + * @see {@link https://api.slack.com/methods/views.open `views.open` API reference}. + */ + open: bindApiCall(this, "views.open"), + /** + * @description Publish a static view for a user. + * @see {@link https://api.slack.com/methods/views.publish `views.publish` API reference}. + */ + publish: bindApiCall(this, "views.publish"), + /** + * @description Push a view onto the stack of a root view. + * @see {@link https://api.slack.com/methods/views.push `views.push` API reference}. + */ + push: bindApiCall(this, "views.push"), + /** + * @description Update an existing view. + * @see {@link https://api.slack.com/methods/views.update `views.update` API reference}. + */ + update: bindApiCall(this, "views.update") + }; + this.stars = { + /** + * @description Save an item for later. Formerly known as adding a star. + * @deprecated Stars can still be added but they can no longer be viewed or interacted with by end-users. + * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. + * @see {@link https://api.slack.com/methods/stars.add `stars.add` API reference}. + */ + add: bindApiCall(this, "stars.add"), + /** + * @description List a user's saved items, formerly known as stars. + * @deprecated Stars can still be listed but they can no longer be viewed or interacted with by end-users. + * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. + * @see {@link https://api.slack.com/methods/stars.list `stars.list` API reference}. + */ + list: bindApiCall(this, "stars.list"), + /** + * @description Remove a saved item from a user's saved items, formerly known as stars. + * @deprecated Stars can still be removed but they can no longer be viewed or interacted with by end-users. + * See {@link https://api.slack.com/changelog/2023-07-its-later-already-for-stars-and-reminders our post on stars and the Later list}. + * @see {@link https://api.slack.com/methods/stars.remove `stars.remove` API reference}. + */ + remove: bindApiCall(this, "stars.remove") + }; + this.workflows = { + /** + * @description Indicate that an app's step in a workflow completed execution. + * @deprecated Steps from Apps is deprecated. + * We're retiring all Slack app functionality around Steps from Apps in September 2024. + * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. + * @see {@link https://api.slack.com/methods/workflows.stepCompleted `workflows.stepCompleted` API reference}. + */ + stepCompleted: bindApiCall(this, "workflows.stepCompleted"), + /** + * @description Indicate that an app's step in a workflow failed to execute. + * @deprecated Steps from Apps is deprecated. + * We're retiring all Slack app functionality around Steps from Apps in September 2024. + * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. + * @see {@link https://api.slack.com/methods/workflows.stepFailed `workflows.stepFailed` API reference}. + */ + stepFailed: bindApiCall(this, "workflows.stepFailed"), + /** + * @description Update the configuration for a workflow step. + * @deprecated Steps from Apps is deprecated. + * We're retiring all Slack app functionality around Steps from Apps in September 2024. + * See {@link https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back our post on deprecating Steps from Apps}. + * @see {@link https://api.slack.com/methods/workflows.updateStep `workflows.updateStep` API reference}. + */ + updateStep: bindApiCall(this, "workflows.updateStep") + }; + if (new.target !== WebClient_1.WebClient && !(new.target.prototype instanceof WebClient_1.WebClient)) { + throw new Error("Attempt to inherit from WebClient methods without inheriting from WebClient"); } } - }, tokenize: function(e, t) { - let r = [e], n = t.rest; - if (n) { - for (let i in n) t[i] = n[i]; - delete t.rest; - } - return P.matchGrammar(e, r, t, 0, 0, false), r; - }, hooks: { all: {}, add: function(e, t) { - let r = P.hooks.all; - r[e] = r[e] || [], r[e].push(t); - }, run: function(e, t) { - let r = P.hooks.all[e]; - if (!(!r || !r.length)) for (var n = 0, i; i = r[n++]; ) i(t); - } }, Token: he }; - P.languages.clike = { comment: [{ pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/, lookbehind: true }, { pattern: /(^|[^\\:])\/\/.*/, lookbehind: true, greedy: true }], string: { pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, greedy: true }, "class-name": { pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i, lookbehind: true, inside: { punctuation: /[.\\]/ } }, keyword: /\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/, boolean: /\b(?:true|false)\b/, function: /\w+(?=\()/, number: /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i, operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/, punctuation: /[{}[\];(),.:]/ }; - P.languages.javascript = P.languages.extend("clike", { "class-name": [P.languages.clike["class-name"], { pattern: /(^|[^$\w\xA0-\uFFFF])[_$A-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\.(?:prototype|constructor))/, lookbehind: true }], keyword: [{ pattern: /((?:^|})\s*)(?:catch|finally)\b/, lookbehind: true }, { pattern: /(^|[^.])\b(?:as|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/, lookbehind: true }], number: /\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/, function: /[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/, operator: /-[-=]?|\+[+=]?|!=?=?|<>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3}/ }); - P.languages.javascript["class-name"][0].pattern = /(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/; - P.languages.insertBefore("javascript", "keyword", { regex: { pattern: /((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^/\\\[\r\n])+\/[gimyus]{0,6}(?=\s*($|[\r\n,.;})\]]))/, lookbehind: true, greedy: true }, "function-variable": { pattern: /[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/, alias: "function" }, parameter: [{ pattern: /(function(?:\s+[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)?\s*\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\))/, lookbehind: true, inside: P.languages.javascript }, { pattern: /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=>)/i, inside: P.languages.javascript }, { pattern: /(\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*=>)/, lookbehind: true, inside: P.languages.javascript }, { pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*\s*)\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*\{)/, lookbehind: true, inside: P.languages.javascript }], constant: /\b[A-Z](?:[A-Z_]|\dx?)*\b/ }); - P.languages.markup && P.languages.markup.tag.addInlined("script", "javascript"); - P.languages.js = P.languages.javascript; - P.languages.typescript = P.languages.extend("javascript", { keyword: /\b(?:abstract|as|async|await|break|case|catch|class|const|constructor|continue|debugger|declare|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|module|namespace|new|null|of|package|private|protected|public|readonly|return|require|set|static|super|switch|this|throw|try|type|typeof|var|void|while|with|yield)\b/, builtin: /\b(?:string|Function|any|number|boolean|Array|symbol|console|Promise|unknown|never)\b/ }); - P.languages.ts = P.languages.typescript; - function he(e, t, r, n, i) { - this.type = e, this.content = t, this.alias = r, this.length = (n || "").length | 0, this.greedy = !!i; - } - he.stringify = function(e, t) { - return typeof e == "string" ? e : Array.isArray(e) ? e.map(function(r) { - return he.stringify(r, t); - }).join("") : gp(e.type)(e.content); }; - function gp(e) { - return Ds[e] || mp; - } - function _s(e) { - return hp(e, P.languages.javascript); - } - function hp(e, t) { - return P.tokenize(e, t).map((n) => he.stringify(n)).join(""); - } - var Fs = k(us()); - function Ls(e) { - return (0, Fs.default)(e); - } - var cn = class e { - static read(t) { - let r; - try { - r = Ns.default.readFileSync(t, "utf-8"); - } catch { - return null; - } - return e.fromContent(r); - } - static fromContent(t) { - let r = t.split(/\r?\n/); - return new e(1, r); - } - constructor(t, r) { - this.firstLineNumber = t, this.lines = r; - } - get lastLineNumber() { - return this.firstLineNumber + this.lines.length - 1; - } - mapLineAt(t, r) { - if (t < this.firstLineNumber || t > this.lines.length + this.firstLineNumber) return this; - let n = t - this.firstLineNumber, i = [...this.lines]; - return i[n] = r(i[n]), new e(this.firstLineNumber, i); - } - mapLines(t) { - return new e(this.firstLineNumber, this.lines.map((r, n) => t(r, this.firstLineNumber + n))); - } - lineAt(t) { - return this.lines[t - this.firstLineNumber]; - } - prependSymbolAt(t, r) { - return this.mapLines((n, i) => i === t ? `${r} ${n}` : ` ${n}`); - } - slice(t, r) { - let n = this.lines.slice(t - 1, r).join(` -`); - return new e(t, Ls(n).split(` -`)); - } - highlight() { - let t = _s(this.toString()); - return new e(this.firstLineNumber, t.split(` -`)); - } - toString() { - return this.lines.join(` -`); - } + exports2.Methods = Methods; + __exportStar(require_dist3(), exports2); + } +}); + +// node_modules/@slack/web-api/dist/retry-policies.js +var require_retry_policies = __commonJS({ + "node_modules/@slack/web-api/dist/retry-policies.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.rapidRetryPolicy = exports2.fiveRetriesInFiveMinutes = exports2.tenRetriesInAboutThirtyMinutes = void 0; + exports2.tenRetriesInAboutThirtyMinutes = { + retries: 10, + factor: 1.96821, + randomize: true }; - var yp = { red: ce, gray: Gt, dim: Oe, bold: H, underline: X, highlightSource: (e) => e.highlight() }; - var bp = { red: (e) => e, gray: (e) => e, dim: (e) => e, bold: (e) => e, underline: (e) => e, highlightSource: (e) => e }; - function Ep({ message: e, originalMethod: t, isPanic: r, callArguments: n }) { - return { functionName: `prisma.${t}()`, message: e, isPanic: r ?? false, callArguments: n }; - } - function wp({ callsite: e, message: t, originalMethod: r, isPanic: n, callArguments: i }, o) { - let s = Ep({ message: t, originalMethod: r, isPanic: n, callArguments: i }); - if (!e || typeof window < "u" || process.env.NODE_ENV === "production") return s; - let a = e.getLocation(); - if (!a || !a.lineNumber || !a.columnNumber) return s; - let l = Math.max(1, a.lineNumber - 3), u = cn.read(a.fileName)?.slice(l, a.lineNumber), c = u?.lineAt(a.lineNumber); - if (u && c) { - let p = Pp(c), d = xp(c); - if (!d) return s; - s.functionName = `${d.code})`, s.location = a, n || (u = u.mapLineAt(a.lineNumber, (g) => g.slice(0, d.openingBraceIndex))), u = o.highlightSource(u); - let f = String(u.lastLineNumber).length; - if (s.contextLines = u.mapLines((g, h) => o.gray(String(h).padStart(f)) + " " + g).mapLines((g) => o.dim(g)).prependSymbolAt(a.lineNumber, o.bold(o.red("\u2192"))), i) { - let g = p + f + 1; - g += 2, s.callArguments = (0, Ms.default)(i, g).slice(g); - } - } - return s; - } - function xp(e) { - let t = Object.keys(Je.ModelAction).join("|"), n = new RegExp(String.raw`\.(${t})\(`).exec(e); - if (n) { - let i = n.index + n[0].length, o = e.lastIndexOf(" ", n.index) + 1; - return { code: e.slice(o, i), openingBraceIndex: i }; - } - return null; - } - function Pp(e) { - let t = 0; - for (let r = 0; r < e.length; r++) { - if (e.charAt(r) !== " ") return t; - t++; + exports2.fiveRetriesInFiveMinutes = { + retries: 5, + factor: 3.86 + }; + exports2.rapidRetryPolicy = { + minTimeout: 0, + maxTimeout: 1 + }; + var policies = { + tenRetriesInAboutThirtyMinutes: exports2.tenRetriesInAboutThirtyMinutes, + fiveRetriesInFiveMinutes: exports2.fiveRetriesInFiveMinutes, + rapidRetryPolicy: exports2.rapidRetryPolicy + }; + exports2.default = policies; + } +}); + +// node_modules/@slack/web-api/dist/WebClient.js +var require_WebClient = __commonJS({ + "node_modules/@slack/web-api/dist/WebClient.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; } - return t; - } - function vp({ functionName: e, location: t, message: r, isPanic: n, contextLines: i, callArguments: o }, s) { - let a = [""], l = t ? " in" : ":"; - if (n ? (a.push(s.red(`Oops, an unknown error occurred! This is ${s.bold("on us")}, you did nothing wrong.`)), a.push(s.red(`It occurred in the ${s.bold(`\`${e}\``)} invocation${l}`))) : a.push(s.red(`Invalid ${s.bold(`\`${e}\``)} invocation${l}`)), t && a.push(s.underline(Tp(t))), i) { - a.push(""); - let u = [i.toString()]; - o && (u.push(o), u.push(s.dim(")"))), a.push(u.join("")), o && a.push(""); - } else a.push(""), o && a.push(o), a.push(""); - return a.push(r), a.join(` -`); - } - function Tp(e) { - let t = [e.fileName]; - return e.lineNumber && t.push(String(e.lineNumber)), e.columnNumber && t.push(String(e.columnNumber)), t.join(":"); - } - function Tt(e) { - let t = e.showColors ? yp : bp, r; - return r = wp(e, t), vp(r, t); - } - var Gs = k(Ai()); - function Vs(e, t, r) { - let n = Bs(e), i = Rp(n), o = Sp(i); - o ? pn(o, t, r) : t.addErrorMessage(() => "Unknown error"); - } - function Bs(e) { - return e.errors.flatMap((t) => t.kind === "Union" ? Bs(t) : [t]); - } - function Rp(e) { - let t = /* @__PURE__ */ new Map(), r = []; - for (let n of e) { - if (n.kind !== "InvalidArgumentType") { - r.push(n); - continue; + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar2 = []; + for (var k2 in o2) if (Object.prototype.hasOwnProperty.call(o2, k2)) ar2[ar2.length] = k2; + return ar2; + }; + return ownKeys(o); + }; + return function(mod2) { + if (mod2 && mod2.__esModule) return mod2; + var result = {}; + if (mod2 != null) { + for (var k2 = ownKeys(mod2), i = 0; i < k2.length; i++) if (k2[i] !== "default") __createBinding(result, mod2, k2[i]); } - let i = `${n.selectionPath.join(".")}:${n.argumentPath.join(".")}`, o = t.get(i); - o ? t.set(i, { ...n, argument: { ...n.argument, typeNames: Cp(o.argument.typeNames, n.argument.typeNames) } }) : t.set(i, n); + __setModuleDefault(result, mod2); + return result; + }; + }(); + var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); } - return r.push(...t.values()), r; - } - function Cp(e, t) { - return [...new Set(e.concat(t))]; - } - function Sp(e) { - return xi(e, (t, r) => { - let n = qs(t), i = qs(r); - return n !== i ? n - i : js(t) - js(r); + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - } - function qs(e) { - let t = 0; - return Array.isArray(e.selectionPath) && (t += e.selectionPath.length), Array.isArray(e.argumentPath) && (t += e.argumentPath.length), t; - } - function js(e) { - switch (e.kind) { - case "InvalidArgumentValue": - case "ValueTooLarge": - return 20; - case "InvalidArgumentType": - return 10; - case "RequiredArgumentMissing": - return -10; - default: - return 0; - } - } - var ue = class { - constructor(t, r) { - this.name = t; - this.value = r; - this.isRequired = false; - } - makeRequired() { - return this.isRequired = true, this; - } - write(t) { - let { colors: { green: r } } = t.context; - t.addMarginSymbol(r(this.isRequired ? "+" : "?")), t.write(r(this.name)), this.isRequired || t.write(r("?")), t.write(r(": ")), typeof this.value == "string" ? t.write(r(this.value)) : t.write(this.value); - } }; - var Rt = class { - constructor(t = 0, r) { - this.context = r; - this.lines = []; - this.currentLine = ""; - this.currentIndent = 0; - this.currentIndent = t; - } - write(t) { - return typeof t == "string" ? this.currentLine += t : t.write(this), this; - } - writeJoined(t, r, n = (i, o) => o.write(i)) { - let i = r.length - 1; - for (let o = 0; o < r.length; o++) n(r[o], this), o !== i && this.write(t); + var __await = exports2 && exports2.__await || function(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + var __asyncGenerator = exports2 && exports2.__asyncGenerator || function(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q2 = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { return this; + }, i; + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; } - writeLine(t) { - return this.write(t).newLine(); - } - newLine() { - this.lines.push(this.indentedCurrentLine()), this.currentLine = "", this.marginSymbol = void 0; - let t = this.afterNextNewLineCallback; - return this.afterNextNewLineCallback = void 0, t?.(), this; - } - withIndent(t) { - return this.indent(), t(this), this.unindent(), this; - } - afterNextNewline(t) { - return this.afterNextNewLineCallback = t, this; - } - indent() { - return this.currentIndent++, this; - } - unindent() { - return this.currentIndent > 0 && this.currentIndent--, this; - } - addMarginSymbol(t) { - return this.marginSymbol = t, this; - } - toString() { - return this.lines.concat(this.indentedCurrentLine()).join(` -`); + function verb(n, f) { + if (g[n]) { + i[n] = function(v) { + return new Promise(function(a, b2) { + q2.push([n, v, a, b2]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } } - getCurrentLineLength() { - return this.currentLine.length; + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle2(q2[0][3], e); + } } - indentedCurrentLine() { - let t = this.currentLine.padStart(this.currentLine.length + 2 * this.currentIndent); - return this.marginSymbol ? this.marginSymbol + t.slice(1) : t; + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle2(q2[0][2], r); } - }; - var dn = class { - constructor(t) { - this.value = t; + function fulfill(value) { + resume("next", value); } - write(t) { - t.write(this.value); + function reject(value) { + resume("throw", value); } - markAsError() { - this.value.markAsError(); + function settle2(f, v) { + if (f(v), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]); } }; - var mn = (e) => e; - var fn = { bold: mn, red: mn, green: mn, dim: mn, enabled: false }; - var Us = { bold: H, red: ce, green: qe, dim: Oe, enabled: true }; - var Ct = { write(e) { - e.writeLine(","); - } }; - var Pe = class { - constructor(t) { - this.contents = t; - this.isUnderlined = false; - this.color = (t2) => t2; + var __asyncValues = exports2 && exports2.__asyncValues || function(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m2 = o[Symbol.asyncIterator], i; + return m2 ? m2.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve, reject) { + v = o[n](v), settle2(resolve, reject, v.done, v.value); + }); + }; } - underline() { - return this.isUnderlined = true, this; + function settle2(resolve, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve({ value: v2, done: d }); + }, reject); } - setColor(t) { - return this.color = t, this; + }; + var __importDefault = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.WebClient = exports2.WebClientEvent = void 0; + exports2.buildThreadTsWarningMessage = buildThreadTsWarningMessage; + var node_path_1 = __require("node:path"); + var node_querystring_1 = __require("node:querystring"); + var node_util_1 = __require("node:util"); + var node_zlib_1 = __importDefault(__require("node:zlib")); + var axios_1 = __importDefault(require_axios()); + var form_data_1 = __importDefault(require_form_data()); + var is_electron_1 = __importDefault(require_is_electron()); + var is_stream_1 = __importDefault(require_is_stream()); + var p_queue_1 = __importDefault(require_dist()); + var p_retry_1 = __importStar(require_p_retry()); + var errors_1 = require_errors3(); + var file_upload_1 = require_file_upload(); + var helpers_1 = __importDefault(require_helpers()); + var instrument_1 = require_instrument(); + var logger_1 = require_logger2(); + var methods_1 = require_methods(); + var retry_policies_1 = require_retry_policies(); + var axiosHeaderPropsToIgnore = [ + "delete", + "common", + "get", + "put", + "head", + "post", + "link", + "patch", + "purge", + "unlink", + "options" + ]; + var defaultFilename = "Untitled"; + var defaultPageSize = 200; + var noopPageReducer = () => void 0; + var WebClientEvent; + (function(WebClientEvent2) { + WebClientEvent2["RATE_LIMITED"] = "rate_limited"; + })(WebClientEvent || (exports2.WebClientEvent = WebClientEvent = {})); + var WebClient2 = class _WebClient extends methods_1.Methods { + /** + * @param token - An API token to authenticate/authorize with Slack (usually start with `xoxp`, `xoxb`) + * @param {Object} [webClientOptions] - Configuration options. + * @param {Function} [webClientOptions.requestInterceptor] - An interceptor to mutate outgoing requests. See {@link https://axios-http.com/docs/interceptors Axios interceptors} + * @param {Function} [webClientOptions.adapter] - An adapter to allow custom handling of requests. Useful if you would like to use a pre-configured http client. See {@link https://github.com/axios/axios/blob/v1.x/README.md?plain=1#L586 Axios adapter} + */ + constructor(token, { slackApiUrl = "https://slack.com/api/", logger = void 0, logLevel = void 0, maxRequestConcurrency = 100, retryConfig = retry_policies_1.tenRetriesInAboutThirtyMinutes, agent = void 0, tls = void 0, timeout = 0, rejectRateLimitedCalls = false, headers = {}, teamId = void 0, allowAbsoluteUrls = true, attachOriginalToWebAPIRequestError = true, requestInterceptor = void 0, adapter = void 0 } = {}) { + super(); + this.token = token; + this.slackApiUrl = slackApiUrl; + if (!this.slackApiUrl.endsWith("/")) { + this.slackApiUrl += "/"; + } + this.retryConfig = retryConfig; + this.requestQueue = new p_queue_1.default({ concurrency: maxRequestConcurrency }); + this.tlsConfig = tls !== void 0 ? tls : {}; + this.rejectRateLimitedCalls = rejectRateLimitedCalls; + this.teamId = teamId; + this.allowAbsoluteUrls = allowAbsoluteUrls; + this.attachOriginalToWebAPIRequestError = attachOriginalToWebAPIRequestError; + if (typeof logger !== "undefined") { + this.logger = logger; + if (typeof logLevel !== "undefined") { + this.logger.debug("The logLevel given to WebClient was ignored as you also gave logger"); + } + } else { + this.logger = (0, logger_1.getLogger)(_WebClient.loggerName, logLevel !== null && logLevel !== void 0 ? logLevel : logger_1.LogLevel.INFO, logger); + } + if (this.token && !headers.Authorization) + headers.Authorization = `Bearer ${this.token}`; + this.axios = axios_1.default.create({ + adapter: adapter ? (config3) => adapter(Object.assign(Object.assign({}, config3), { adapter: void 0 })) : void 0, + timeout, + baseURL: this.slackApiUrl, + headers: (0, is_electron_1.default)() ? headers : Object.assign({ "User-Agent": (0, instrument_1.getUserAgent)() }, headers), + httpAgent: agent, + httpsAgent: agent, + validateStatus: () => true, + // all HTTP status codes should result in a resolved promise (as opposed to only 2xx) + maxRedirects: 0, + // disabling axios' automatic proxy support: + // axios would read from envvars to configure a proxy automatically, but it doesn't support TLS destinations. + // for compatibility with https://api.slack.com, and for a larger set of possible proxies (SOCKS or other + // protocols), users of this package should use the `agent` option to configure a proxy. + proxy: false + }); + this.axios.defaults.headers.post["Content-Type"] = void 0; + if (requestInterceptor) { + this.axios.interceptors.request.use(requestInterceptor, null); + } + this.axios.interceptors.request.use(this.serializeApiCallData.bind(this), null); + this.logger.debug("initialized"); } - write(t) { - let r = t.getCurrentLineLength(); - t.write(this.color(this.contents)), this.isUnderlined && t.afterNextNewline(() => { - t.write(" ".repeat(r)).writeLine(this.color("~".repeat(this.contents.length))); + /** + * Generic method for calling a Web API method + * @param method - the Web API method to call {@link https://api.slack.com/methods} + * @param options - options + */ + apiCall(method_1) { + return __awaiter(this, arguments, void 0, function* (method, options = {}) { + this.logger.debug(`apiCall('${method}') start`); + warnDeprecations(method, this.logger); + warnIfFallbackIsMissing(method, this.logger, options); + warnIfThreadTsIsNotString(method, this.logger, options); + if (typeof options === "string" || typeof options === "number" || typeof options === "boolean") { + throw new TypeError(`Expected an options argument but instead received a ${typeof options}`); + } + (0, file_upload_1.warnIfNotUsingFilesUploadV2)(method, this.logger); + if (method === "files.uploadV2") + return this.filesUploadV2(options); + const headers = {}; + if (options.token) + headers.Authorization = `Bearer ${options.token}`; + const url2 = this.deriveRequestUrl(method); + const response = yield this.makeRequest(url2, Object.assign({ team_id: this.teamId }, options), headers); + const result = yield this.buildResult(response); + this.logger.debug(`http request result: ${JSON.stringify(result)}`); + if (result.response_metadata !== void 0 && result.response_metadata.warnings !== void 0) { + result.response_metadata.warnings.forEach(this.logger.warn.bind(this.logger)); + } + if (result.response_metadata !== void 0 && result.response_metadata.messages !== void 0) { + for (const msg of result.response_metadata.messages) { + const errReg = /\[ERROR\](.*)/; + const warnReg = /\[WARN\](.*)/; + if (errReg.test(msg)) { + const errMatch = msg.match(errReg); + if (errMatch != null) { + this.logger.error(errMatch[1].trim()); + } + } else if (warnReg.test(msg)) { + const warnMatch = msg.match(warnReg); + if (warnMatch != null) { + this.logger.warn(warnMatch[1].trim()); + } + } + } + } + if (!result.ok && response.headers["content-type"] !== "application/gzip") { + throw (0, errors_1.platformErrorFromResult)(result); + } + if ("ok" in result && result.ok === false) { + throw (0, errors_1.platformErrorFromResult)(result); + } + this.logger.debug(`apiCall('${method}') end`); + return result; }); } - }; - var Ye = class { - constructor() { - this.hasError = false; + paginate(method, options, shouldStop, reduce) { + const pageSize = (() => { + if (options !== void 0 && typeof options.limit === "number") { + const { limit } = options; + options.limit = void 0; + return limit; + } + return defaultPageSize; + })(); + function generatePages() { + return __asyncGenerator(this, arguments, function* generatePages_1() { + let result; + let paginationOptions = { + limit: pageSize + }; + if (options !== void 0 && options.cursor !== void 0) { + paginationOptions.cursor = options.cursor; + } + while (result === void 0 || paginationOptions !== void 0) { + result = yield __await(this.apiCall(method, Object.assign(options !== void 0 ? options : {}, paginationOptions))); + yield yield __await(result); + paginationOptions = paginationOptionsForNextPage(result, pageSize); + } + }); + } + if (shouldStop === void 0) { + return generatePages.call(this); + } + const pageReducer = reduce !== void 0 ? reduce : noopPageReducer; + let index2 = 0; + return (() => __awaiter(this, void 0, void 0, function* () { + var _a2, e_1, _b, _c2; + const pageIterator = generatePages.call(this); + const firstIteratorResult = yield pageIterator.next(void 0); + const firstPage = firstIteratorResult.value; + let accumulator = pageReducer(void 0, firstPage, index2); + index2 += 1; + if (shouldStop(firstPage)) { + return accumulator; + } + try { + for (var _d2 = true, pageIterator_1 = __asyncValues(pageIterator), pageIterator_1_1; pageIterator_1_1 = yield pageIterator_1.next(), _a2 = pageIterator_1_1.done, !_a2; _d2 = true) { + _c2 = pageIterator_1_1.value; + _d2 = false; + const page = _c2; + accumulator = pageReducer(accumulator, page, index2); + if (shouldStop(page)) { + return accumulator; + } + index2 += 1; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d2 && !_a2 && (_b = pageIterator_1.return)) yield _b.call(pageIterator_1); + } finally { + if (e_1) throw e_1.error; + } + } + return accumulator; + }))(); } - markAsError() { - return this.hasError = true, this; + /** + * This wrapper method provides an easy way to upload files using the following endpoints: + * + * **#1**: For each file submitted with this method, submit filenames + * and file metadata to {@link https://api.slack.com/methods/files.getUploadURLExternal files.getUploadURLExternal} to request a URL to + * which to send the file data to and an id for the file + * + * **#2**: for each returned file `upload_url`, upload corresponding file to + * URLs returned from step 1 (e.g. https://files.slack.com/upload/v1/...\") + * + * **#3**: Complete uploads {@link https://api.slack.com/methods/files.completeUploadExternal files.completeUploadExternal} + * @param options + */ + filesUploadV2(options) { + return __awaiter(this, void 0, void 0, function* () { + this.logger.debug("files.uploadV2() start"); + const fileUploads = yield this.getAllFileUploads(options); + const fileUploadsURLRes = yield this.fetchAllUploadURLExternal(fileUploads); + fileUploadsURLRes.forEach((res, idx) => { + fileUploads[idx].upload_url = res.upload_url; + fileUploads[idx].file_id = res.file_id; + }); + yield this.postFileUploadsToExternalURL(fileUploads, options); + const completion = yield this.completeFileUploads(fileUploads); + return { ok: true, files: completion }; + }); } - }; - var St = class extends Ye { - constructor() { - super(...arguments); - this.items = []; + /** + * For each file submitted with this method, submits filenames + * and file metadata to files.getUploadURLExternal to request a URL to + * which to send the file data to and an id for the file + * @param fileUploads + */ + fetchAllUploadURLExternal(fileUploads) { + return __awaiter(this, void 0, void 0, function* () { + return Promise.all(fileUploads.map((upload) => { + const options = { + filename: upload.filename, + length: upload.length, + alt_text: upload.alt_text, + snippet_type: upload.snippet_type + }; + if ("token" in upload) { + options.token = upload.token; + } + return this.files.getUploadURLExternal(options); + })); + }); } - addItem(r) { - return this.items.push(new dn(r)), this; + /** + * Complete uploads. + * @param fileUploads + * @returns + */ + completeFileUploads(fileUploads) { + return __awaiter(this, void 0, void 0, function* () { + const toComplete = Object.values((0, file_upload_1.getAllFileUploadsToComplete)(fileUploads)); + return Promise.all(toComplete.map((job) => this.files.completeUploadExternal(job))); + }); } - getField(r) { - return this.items[r]; + /** + * for each returned file upload URL, upload corresponding file + * @param fileUploads + * @returns + */ + postFileUploadsToExternalURL(fileUploads, options) { + return __awaiter(this, void 0, void 0, function* () { + return Promise.all(fileUploads.map((upload) => __awaiter(this, void 0, void 0, function* () { + const { upload_url, file_id, filename, data } = upload; + const body = data; + if (upload_url) { + const headers = {}; + if (options.token) + headers.Authorization = `Bearer ${options.token}`; + const uploadRes = yield this.makeRequest(upload_url, { + body + }, headers); + if (uploadRes.status !== 200) { + return Promise.reject(Error(`Failed to upload file (id:${file_id}, filename: ${filename})`)); + } + const returnData = { ok: true, body: uploadRes.data }; + return Promise.resolve(returnData); + } + return Promise.reject(Error(`No upload url found for file (id: ${file_id}, filename: ${filename}`)); + }))); + }); } - getPrintWidth() { - return this.items.length === 0 ? 2 : Math.max(...this.items.map((n) => n.value.getPrintWidth())) + 2; + /** + * @param options All file uploads arguments + * @returns An array of file upload entries + */ + getAllFileUploads(options) { + return __awaiter(this, void 0, void 0, function* () { + let fileUploads = []; + if ("file" in options || "content" in options) { + fileUploads.push(yield (0, file_upload_1.getFileUploadJob)(options, this.logger)); + } + if ("file_uploads" in options) { + fileUploads = fileUploads.concat(yield (0, file_upload_1.getMultipleFileUploadJobs)(options, this.logger)); + } + return fileUploads; + }); } - write(r) { - if (this.items.length === 0) { - this.writeEmpty(r); - return; + /** + * Low-level function to make a single API request. handles queuing, retries, and http-level errors + */ + makeRequest(url_1, body_1) { + return __awaiter(this, arguments, void 0, function* (url2, body, headers = {}) { + const task = () => this.requestQueue.add(() => __awaiter(this, void 0, void 0, function* () { + try { + const config3 = Object.assign({ headers }, this.tlsConfig); + if (url2.endsWith("admin.analytics.getFile")) { + config3.responseType = "arraybuffer"; + } + if (url2.endsWith("apps.event.authorizations.list")) { + body.token = void 0; + } + this.logger.debug(`http request url: ${url2}`); + this.logger.debug(`http request body: ${JSON.stringify(redact(body))}`); + let allHeaders = Object.keys(this.axios.defaults.headers).reduce((acc, cur) => { + if (!axiosHeaderPropsToIgnore.includes(cur)) { + acc[cur] = this.axios.defaults.headers[cur]; + } + return acc; + }, {}); + allHeaders = Object.assign(Object.assign(Object.assign({}, this.axios.defaults.headers.common), allHeaders), headers); + this.logger.debug(`http request headers: ${JSON.stringify(redact(allHeaders))}`); + const response = yield this.axios.post(url2, body, config3); + this.logger.debug("http response received"); + if (response.status === 429) { + const retrySec = parseRetryHeaders(response); + if (retrySec !== void 0) { + this.emit(WebClientEvent.RATE_LIMITED, retrySec, { url: url2, body }); + if (this.rejectRateLimitedCalls) { + throw new p_retry_1.AbortError((0, errors_1.rateLimitedErrorWithDelay)(retrySec)); + } + this.logger.info(`API Call failed due to rate limiting. Will retry in ${retrySec} seconds.`); + this.requestQueue.pause(); + yield (0, helpers_1.default)(retrySec * 1e3); + this.requestQueue.start(); + throw new Error(`A rate limit was exceeded (url: ${url2}, retry-after: ${retrySec})`); + } + throw new p_retry_1.AbortError(new Error(`Retry header did not contain a valid timeout (url: ${url2}, retry-after header: ${response.headers["retry-after"]})`)); + } + if (response.status !== 200) { + throw (0, errors_1.httpErrorFromResponse)(response); + } + return response; + } catch (error) { + const e = error; + this.logger.warn("http request failed", e.message); + if (e.request) { + throw (0, errors_1.requestErrorWithOriginal)(e, this.attachOriginalToWebAPIRequestError); + } + throw error; + } + })); + return (0, p_retry_1.default)(task, this.retryConfig); + }); + } + /** + * Get the complete request URL for the provided URL. + * @param url - The resource to POST to. Either a Slack API method or absolute URL. + */ + deriveRequestUrl(url2) { + const isAbsoluteURL2 = url2.startsWith("https://") || url2.startsWith("http://"); + if (isAbsoluteURL2 && this.allowAbsoluteUrls) { + return url2; } - this.writeWithItems(r); + return `${this.axios.getUri() + url2}`; } - writeEmpty(r) { - let n = new Pe("[]"); - this.hasError && n.setColor(r.context.colors.red).underline(), r.write(n); + /** + * Transforms options (a simple key-value object) into an acceptable value for a body. This can be either + * a string, used when posting with a content-type of url-encoded. Or, it can be a readable stream, used + * when the options contain a binary (a stream or a buffer) and the upload should be done with content-type + * multipart/form-data. + * @param config - The Axios request configuration object + */ + serializeApiCallData(config3) { + const { data, headers } = config3; + let containsBinaryData = false; + const flattened = Object.entries(data).map(([key, value]) => { + if (value === void 0 || value === null) { + return []; + } + let serializedValue = value; + if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { + containsBinaryData = true; + } else if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") { + serializedValue = JSON.stringify(value); + } + return [key, serializedValue]; + }); + if (containsBinaryData) { + this.logger.debug("Request arguments contain binary data"); + const form = flattened.reduce((frm, [key, value]) => { + if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { + const opts = {}; + opts.filename = (() => { + const streamOrBuffer = value; + if (typeof streamOrBuffer.name === "string") { + return (0, node_path_1.basename)(streamOrBuffer.name); + } + if (typeof streamOrBuffer.path === "string") { + return (0, node_path_1.basename)(streamOrBuffer.path); + } + return defaultFilename; + })(); + frm.append(key, value, opts); + } else if (key !== void 0 && value !== void 0) { + frm.append(key, value); + } + return frm; + }, new form_data_1.default()); + if (headers) { + for (const [header, value] of Object.entries(form.getHeaders())) { + headers[header] = value; + } + } + config3.data = form; + config3.headers = headers; + return config3; + } + if (headers) + headers["Content-Type"] = "application/x-www-form-urlencoded"; + const initialValue = {}; + config3.data = (0, node_querystring_1.stringify)(flattened.reduce((accumulator, [key, value]) => { + if (key !== void 0 && value !== void 0) { + accumulator[key] = value; + } + return accumulator; + }, initialValue)); + config3.headers = headers; + return config3; } - writeWithItems(r) { - let { colors: n } = r.context; - r.writeLine("[").withIndent(() => r.writeJoined(Ct, this.items).newLine()).write("]"), this.hasError && r.afterNextNewline(() => { - r.writeLine(n.red("~".repeat(this.getPrintWidth()))); + /** + * Processes an HTTP response into a WebAPICallResult by performing JSON parsing on the body and merging relevant + * HTTP headers into the object. + * @param response - an http response + */ + buildResult(response) { + return __awaiter(this, void 0, void 0, function* () { + let { data } = response; + const isGzipResponse = response.headers["content-type"] === "application/gzip"; + if (isGzipResponse) { + try { + const unzippedData = yield new Promise((resolve, reject) => { + node_zlib_1.default.unzip(data, (err, buf) => { + if (err) { + return reject(err); + } + return resolve(buf.toString().split("\n")); + }); + }).then((res) => res).catch((err) => { + throw err; + }); + const fileData = []; + if (Array.isArray(unzippedData)) { + for (const dataset of unzippedData) { + if (dataset && dataset.length > 0) { + fileData.push(JSON.parse(dataset)); + } + } + } + data = { file_data: fileData }; + } catch (err) { + data = { ok: false, error: err }; + } + } else if (!isGzipResponse && response.request.path === "/api/admin.analytics.getFile") { + data = JSON.parse(new node_util_1.TextDecoder().decode(data)); + } + if (typeof data === "string") { + try { + data = JSON.parse(data); + } catch (_) { + data = { ok: false, error: data }; + } + } + if (data.response_metadata === void 0) { + data.response_metadata = {}; + } + if (response.headers["x-oauth-scopes"] !== void 0) { + data.response_metadata.scopes = response.headers["x-oauth-scopes"].trim().split(/\s*,\s*/); + } + if (response.headers["x-accepted-oauth-scopes"] !== void 0) { + data.response_metadata.acceptedScopes = response.headers["x-accepted-oauth-scopes"].trim().split(/\s*,\s*/); + } + const retrySec = parseRetryHeaders(response); + if (retrySec !== void 0) { + data.response_metadata.retryAfter = retrySec; + } + return data; }); } - asObject() { - } }; - var At = class e extends Ye { - constructor() { - super(...arguments); - this.fields = {}; - this.suggestions = []; - } - addField(r) { - this.fields[r.name] = r; - } - addSuggestion(r) { - this.suggestions.push(r); - } - getField(r) { - return this.fields[r]; + exports2.WebClient = WebClient2; + WebClient2.loggerName = "WebClient"; + exports2.default = WebClient2; + function paginationOptionsForNextPage(previousResult, pageSize) { + if (previousResult !== void 0 && previousResult.response_metadata !== void 0 && previousResult.response_metadata.next_cursor !== void 0 && previousResult.response_metadata.next_cursor !== "") { + return { + limit: pageSize, + cursor: previousResult.response_metadata.next_cursor + }; } - getDeepField(r) { - let [n, ...i] = r, o = this.getField(n); - if (!o) return; - let s = o; - for (let a of i) { - let l; - if (s.value instanceof e ? l = s.value.getField(a) : s.value instanceof St && (l = s.value.getField(Number(a))), !l) return; - s = l; + return void 0; + } + function parseRetryHeaders(response) { + if (response.headers["retry-after"] !== void 0) { + const retryAfter = Number.parseInt(response.headers["retry-after"], 10); + if (!Number.isNaN(retryAfter)) { + return retryAfter; } - return s; - } - getDeepFieldValue(r) { - return r.length === 0 ? this : this.getDeepField(r)?.value; - } - hasField(r) { - return !!this.getField(r); - } - removeAllFields() { - this.fields = {}; } - removeField(r) { - delete this.fields[r]; - } - getFields() { - return this.fields; + return void 0; + } + function warnDeprecations(method, logger) { + const deprecatedMethods = ["workflows."]; + const isDeprecated = deprecatedMethods.some((depMethod) => { + const re2 = new RegExp(`^${depMethod}`); + return re2.test(method); + }); + if (isDeprecated) { + logger.warn(`${method} is deprecated. Please check on https://api.slack.com/methods for an alternative.`); } - isEmpty() { - return Object.keys(this.fields).length === 0; + } + function warnIfFallbackIsMissing(method, logger, options) { + const targetMethods = ["chat.postEphemeral", "chat.postMessage", "chat.scheduleMessage"]; + const isTargetMethod = targetMethods.includes(method); + const hasAttachments = (args) => Array.isArray(args.attachments) && args.attachments.length; + const missingAttachmentFallbackDetected = (args) => Array.isArray(args.attachments) && args.attachments.some((attachment) => !attachment.fallback || attachment.fallback.trim() === ""); + const isEmptyText = (args) => args.text === void 0 || args.text === null || args.text === ""; + const buildMissingTextWarning = () => `The top-level \`text\` argument is missing in the request payload for a ${method} call - It's a best practice to always provide a \`text\` argument when posting a message. The \`text\` is used in places where the content cannot be rendered such as: system push notifications, assistive technology such as screen readers, etc.`; + const buildMissingFallbackWarning = () => `Additionally, the attachment-level \`fallback\` argument is missing in the request payload for a ${method} call - To avoid this warning, it is recommended to always provide a top-level \`text\` argument when posting a message. Alternatively, you can provide an attachment-level \`fallback\` argument, though this is now considered a legacy field (see https://api.slack.com/reference/messaging/attachments#legacy_fields for more details).`; + if (isTargetMethod && typeof options === "object") { + if (hasAttachments(options)) { + if (missingAttachmentFallbackDetected(options) && isEmptyText(options)) { + logger.warn(buildMissingTextWarning()); + logger.warn(buildMissingFallbackWarning()); + } + } else if (isEmptyText(options)) { + logger.warn(buildMissingTextWarning()); + } } - getFieldValue(r) { - return this.getField(r)?.value; + } + function warnIfThreadTsIsNotString(method, logger, options) { + const targetMethods = ["chat.postEphemeral", "chat.postMessage", "chat.scheduleMessage", "files.upload"]; + const isTargetMethod = targetMethods.includes(method); + if (isTargetMethod && (options === null || options === void 0 ? void 0 : options.thread_ts) !== void 0 && typeof (options === null || options === void 0 ? void 0 : options.thread_ts) !== "string") { + logger.warn(buildThreadTsWarningMessage(method)); } - getDeepSubSelectionValue(r) { - let n = this; - for (let i of r) { - if (!(n instanceof e)) return; - let o = n.getSubSelectionValue(i); - if (!o) return; - n = o; + } + function buildThreadTsWarningMessage(method) { + return `The given thread_ts value in the request payload for a ${method} call is a float value. We highly recommend using a string value instead.`; + } + function redact(body) { + const flattened = Object.entries(body).map(([key, value]) => { + if (value === void 0 || value === null) { + return []; } - return n; - } - getDeepSelectionParent(r) { - let n = this.getSelectionParent(); - if (!n) return; - let i = n; - for (let o of r) { - let s = i.value.getFieldValue(o); - if (!s || !(s instanceof e)) return; - let a = s.getSelectionParent(); - if (!a) return; - i = a; + let serializedValue = value; + if (key.match(/.*token.*/) !== null || key.match(/[Aa]uthorization/)) { + serializedValue = "[[REDACTED]]"; } - return i; - } - getSelectionParent() { - let r = this.getField("select")?.value.asObject(); - if (r) return { kind: "select", value: r }; - let n = this.getField("include")?.value.asObject(); - if (n) return { kind: "include", value: n }; - } - getSubSelectionValue(r) { - return this.getSelectionParent()?.value.fields[r].value; - } - getPrintWidth() { - let r = Object.values(this.fields); - return r.length == 0 ? 2 : Math.max(...r.map((i) => i.getPrintWidth())) + 2; - } - write(r) { - let n = Object.values(this.fields); - if (n.length === 0 && this.suggestions.length === 0) { - this.writeEmpty(r); - return; + if (Buffer.isBuffer(value) || (0, is_stream_1.default)(value)) { + serializedValue = "[[BINARY VALUE OMITTED]]"; + } else if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") { + serializedValue = JSON.stringify(value); } - this.writeWithContents(r, n); - } - asObject() { - return this; - } - writeEmpty(r) { - let n = new Pe("{}"); - this.hasError && n.setColor(r.context.colors.red).underline(), r.write(n); - } - writeWithContents(r, n) { - r.writeLine("{").withIndent(() => { - r.writeJoined(Ct, [...n, ...this.suggestions]).newLine(); - }), r.write("}"), this.hasError && r.afterNextNewline(() => { - r.writeLine(r.context.colors.red("~".repeat(this.getPrintWidth()))); - }); + return [key, serializedValue]; + }); + const initialValue = {}; + return flattened.reduce((accumulator, [key, value]) => { + if (key !== void 0 && value !== void 0) { + accumulator[key] = value; + } + return accumulator; + }, initialValue); + } + } +}); + +// node_modules/@slack/web-api/dist/types/request/index.js +var require_request = __commonJS({ + "node_modules/@slack/web-api/dist/types/request/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/web-api/dist/types/response/index.js +var require_response = __commonJS({ + "node_modules/@slack/web-api/dist/types/response/index.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + } +}); + +// node_modules/@slack/web-api/dist/index.js +var require_dist4 = __commonJS({ + "node_modules/@slack/web-api/dist/index.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; } + Object.defineProperty(o, k22, desc); + } : function(o, m2, k2, k22) { + if (k22 === void 0) k22 = k2; + o[k22] = m2[k2]; + }); + var __exportStar = exports2 && exports2.__exportStar || function(m2, exports3) { + for (var p in m2) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m2, p); }; - var W = class extends Ye { - constructor(r) { - super(); - this.text = r; - } - getPrintWidth() { - return this.text.length; - } - write(r) { - let n = new Pe(this.text); - this.hasError && n.underline().setColor(r.context.colors.red), r.write(n); - } - asObject() { - } + var __importDefault = exports2 && exports2.__importDefault || function(mod2) { + return mod2 && mod2.__esModule ? mod2 : { "default": mod2 }; }; - var nr = class { - constructor() { - this.fields = []; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.addAppMetadata = exports2.retryPolicies = exports2.ErrorCode = exports2.LogLevel = exports2.WebClientEvent = exports2.WebClient = void 0; + var WebClient_1 = require_WebClient(); + Object.defineProperty(exports2, "WebClient", { enumerable: true, get: function() { + return WebClient_1.WebClient; + } }); + Object.defineProperty(exports2, "WebClientEvent", { enumerable: true, get: function() { + return WebClient_1.WebClientEvent; + } }); + var logger_1 = require_logger2(); + Object.defineProperty(exports2, "LogLevel", { enumerable: true, get: function() { + return logger_1.LogLevel; + } }); + var errors_1 = require_errors3(); + Object.defineProperty(exports2, "ErrorCode", { enumerable: true, get: function() { + return errors_1.ErrorCode; + } }); + var retry_policies_1 = require_retry_policies(); + Object.defineProperty(exports2, "retryPolicies", { enumerable: true, get: function() { + return __importDefault(retry_policies_1).default; + } }); + var instrument_1 = require_instrument(); + Object.defineProperty(exports2, "addAppMetadata", { enumerable: true, get: function() { + return instrument_1.addAppMetadata; + } }); + __exportStar(require_methods(), exports2); + __exportStar(require_request(), exports2); + __exportStar(require_response(), exports2); + } +}); + +// node_modules/@prisma/client/runtime/library.js +var require_library = __commonJS({ + "node_modules/@prisma/client/runtime/library.js"(exports, module) { + "use strict"; + var eu = Object.create; + var Nr = Object.defineProperty; + var tu = Object.getOwnPropertyDescriptor; + var ru = Object.getOwnPropertyNames; + var nu = Object.getPrototypeOf; + var iu = Object.prototype.hasOwnProperty; + var Z = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports); + var Ut = (e, t) => { + for (var r in t) Nr(e, r, { get: t[r], enumerable: true }); + }; + var ho = (e, t, r, n) => { + if (t && typeof t == "object" || typeof t == "function") for (let i of ru(t)) !iu.call(e, i) && i !== r && Nr(e, i, { get: () => t[i], enumerable: !(n = tu(t, i)) || n.enumerable }); + return e; + }; + var k = (e, t, r) => (r = e != null ? eu(nu(e)) : {}, ho(t || !e || !e.__esModule ? Nr(r, "default", { value: e, enumerable: true }) : r, e)); + var ou = (e) => ho(Nr({}, "__esModule", { value: true }), e); + var jo = Z((pf, Zn) => { + "use strict"; + var v = Zn.exports; + Zn.exports.default = v; + var D = "\x1B[", Ht = "\x1B]", ft = "\x07", Jr = ";", qo = process.env.TERM_PROGRAM === "Apple_Terminal"; + v.cursorTo = (e, t) => { + if (typeof e != "number") throw new TypeError("The `x` argument is required"); + return typeof t != "number" ? D + (e + 1) + "G" : D + (t + 1) + ";" + (e + 1) + "H"; + }; + v.cursorMove = (e, t) => { + if (typeof e != "number") throw new TypeError("The `x` argument is required"); + let r = ""; + return e < 0 ? r += D + -e + "D" : e > 0 && (r += D + e + "C"), t < 0 ? r += D + -t + "A" : t > 0 && (r += D + t + "B"), r; + }; + v.cursorUp = (e = 1) => D + e + "A"; + v.cursorDown = (e = 1) => D + e + "B"; + v.cursorForward = (e = 1) => D + e + "C"; + v.cursorBackward = (e = 1) => D + e + "D"; + v.cursorLeft = D + "G"; + v.cursorSavePosition = qo ? "\x1B7" : D + "s"; + v.cursorRestorePosition = qo ? "\x1B8" : D + "u"; + v.cursorGetPosition = D + "6n"; + v.cursorNextLine = D + "E"; + v.cursorPrevLine = D + "F"; + v.cursorHide = D + "?25l"; + v.cursorShow = D + "?25h"; + v.eraseLines = (e) => { + let t = ""; + for (let r = 0; r < e; r++) t += v.eraseLine + (r < e - 1 ? v.cursorUp() : ""); + return e && (t += v.cursorLeft), t; + }; + v.eraseEndLine = D + "K"; + v.eraseStartLine = D + "1K"; + v.eraseLine = D + "2K"; + v.eraseDown = D + "J"; + v.eraseUp = D + "1J"; + v.eraseScreen = D + "2J"; + v.scrollUp = D + "S"; + v.scrollDown = D + "T"; + v.clearScreen = "\x1Bc"; + v.clearTerminal = process.platform === "win32" ? `${v.eraseScreen}${D}0f` : `${v.eraseScreen}${D}3J${D}H`; + v.beep = ft; + v.link = (e, t) => [Ht, "8", Jr, Jr, t, ft, e, Ht, "8", Jr, Jr, ft].join(""); + v.image = (e, t = {}) => { + let r = `${Ht}1337;File=inline=1`; + return t.width && (r += `;width=${t.width}`), t.height && (r += `;height=${t.height}`), t.preserveAspectRatio === false && (r += ";preserveAspectRatio=0"), r + ":" + e.toString("base64") + ft; + }; + v.iTerm = { setCwd: (e = process.cwd()) => `${Ht}50;CurrentDir=${e}${ft}`, annotation: (e, t = {}) => { + let r = `${Ht}1337;`, n = typeof t.x < "u", i = typeof t.y < "u"; + if ((n || i) && !(n && i && typeof t.length < "u")) throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined"); + return e = e.replace(/\|/g, ""), r += t.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=", t.length > 0 ? r += (n ? [e, t.length, t.x, t.y] : [t.length, e]).join("|") : r += e, r + ft; + } }; + }); + var Xn = Z((df, Vo) => { + "use strict"; + Vo.exports = (e, t = process.argv) => { + let r = e.startsWith("-") ? "" : e.length === 1 ? "-" : "--", n = t.indexOf(r + e), i = t.indexOf("--"); + return n !== -1 && (i === -1 || n < i); + }; + }); + var Go = Z((mf, Uo) => { + "use strict"; + var Gu = __require("os"), Bo = __require("tty"), de = Xn(), { env: Q } = process, Qe; + de("no-color") || de("no-colors") || de("color=false") || de("color=never") ? Qe = 0 : (de("color") || de("colors") || de("color=true") || de("color=always")) && (Qe = 1); + "FORCE_COLOR" in Q && (Q.FORCE_COLOR === "true" ? Qe = 1 : Q.FORCE_COLOR === "false" ? Qe = 0 : Qe = Q.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(Q.FORCE_COLOR, 10), 3)); + function ei(e) { + return e === 0 ? false : { level: e, hasBasic: true, has256: e >= 2, has16m: e >= 3 }; } - addField(t, r) { - return this.fields.push({ write(n) { - let { green: i, dim: o } = n.context.colors; - n.write(i(o(`${t}: ${r}`))).addMarginSymbol(i(o("+"))); - } }), this; + function ti(e, t) { + if (Qe === 0) return 0; + if (de("color=16m") || de("color=full") || de("color=truecolor")) return 3; + if (de("color=256")) return 2; + if (e && !t && Qe === void 0) return 0; + let r = Qe || 0; + if (Q.TERM === "dumb") return r; + if (process.platform === "win32") { + let n = Gu.release().split("."); + return Number(n[0]) >= 10 && Number(n[2]) >= 10586 ? Number(n[2]) >= 14931 ? 3 : 2 : 1; + } + if ("CI" in Q) return ["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((n) => n in Q) || Q.CI_NAME === "codeship" ? 1 : r; + if ("TEAMCITY_VERSION" in Q) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Q.TEAMCITY_VERSION) ? 1 : 0; + if (Q.COLORTERM === "truecolor") return 3; + if ("TERM_PROGRAM" in Q) { + let n = parseInt((Q.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (Q.TERM_PROGRAM) { + case "iTerm.app": + return n >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; + } + } + return /-256(color)?$/i.test(Q.TERM) ? 2 : /^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Q.TERM) || "COLORTERM" in Q ? 1 : r; } - write(t) { - let { colors: { green: r } } = t.context; - t.writeLine(r("{")).withIndent(() => { - t.writeJoined(Ct, this.fields).newLine(); - }).write(r("}")).addMarginSymbol(r("+")); + function Qu(e) { + let t = ti(e, e && e.isTTY); + return ei(t); } - }; - function pn(e, t, r) { - switch (e.kind) { - case "MutuallyExclusiveFields": - Ip(e, t); - break; - case "IncludeOnScalar": - Op(e, t); - break; - case "EmptySelection": - kp(e, t, r); - break; - case "UnknownSelectionField": - Lp(e, t); - break; - case "InvalidSelectionValue": - Np(e, t); - break; - case "UnknownArgument": - Mp(e, t); - break; - case "UnknownInputField": - $p(e, t); - break; - case "RequiredArgumentMissing": - qp(e, t); - break; - case "InvalidArgumentType": - jp(e, t); - break; - case "InvalidArgumentValue": - Vp(e, t); - break; - case "ValueTooLarge": - Bp(e, t); - break; - case "SomeFieldsMissing": - Up(e, t); - break; - case "TooManyFieldsGiven": - Gp(e, t); - break; - case "Union": - Vs(e, t, r); - break; - default: - throw new Error("not implemented: " + e.kind); + Uo.exports = { supportsColor: Qu, stdout: ei(ti(true, Bo.isatty(1))), stderr: ei(ti(true, Bo.isatty(2))) }; + }); + var Wo = Z((ff, Jo) => { + "use strict"; + var Ju = Go(), gt = Xn(); + function Qo(e) { + if (/^\d{3,4}$/.test(e)) { + let r = /(\d{1,2})(\d{2})/.exec(e); + return { major: 0, minor: parseInt(r[1], 10), patch: parseInt(r[2], 10) }; + } + let t = (e || "").split(".").map((r) => parseInt(r, 10)); + return { major: t[0], minor: t[1], patch: t[2] }; } - } - function Ip(e, t) { - let r = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); - r && (r.getField(e.firstField)?.markAsError(), r.getField(e.secondField)?.markAsError()), t.addErrorMessage((n) => `Please ${n.bold("either")} use ${n.green(`\`${e.firstField}\``)} or ${n.green(`\`${e.secondField}\``)}, but ${n.red("not both")} at the same time.`); - } - function Op(e, t) { - let [r, n] = ir(e.selectionPath), i = e.outputType, o = t.arguments.getDeepSelectionParent(r)?.value; - if (o && (o.getField(n)?.markAsError(), i)) for (let s of i.fields) s.isRelation && o.addSuggestion(new ue(s.name, "true")); - t.addErrorMessage((s) => { - let a = `Invalid scalar field ${s.red(`\`${n}\``)} for ${s.bold("include")} statement`; - return i ? a += ` on model ${s.bold(i.name)}. ${or(s)}` : a += ".", a += ` -Note that ${s.bold("include")} statements only accept relation fields.`, a; - }); - } - function kp(e, t, r) { - let n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); - if (n) { - let i = n.getField("omit")?.value.asObject(); - if (i) { - Dp(e, t, i); - return; + function ri(e) { + let { env: t } = process; + if ("FORCE_HYPERLINK" in t) return !(t.FORCE_HYPERLINK.length > 0 && parseInt(t.FORCE_HYPERLINK, 10) === 0); + if (gt("no-hyperlink") || gt("no-hyperlinks") || gt("hyperlink=false") || gt("hyperlink=never")) return false; + if (gt("hyperlink=true") || gt("hyperlink=always") || "NETLIFY" in t) return true; + if (!Ju.supportsColor(e) || e && !e.isTTY || process.platform === "win32" || "CI" in t || "TEAMCITY_VERSION" in t) return false; + if ("TERM_PROGRAM" in t) { + let r = Qo(t.TERM_PROGRAM_VERSION); + switch (t.TERM_PROGRAM) { + case "iTerm.app": + return r.major === 3 ? r.minor >= 1 : r.major > 3; + case "WezTerm": + return r.major >= 20200620; + case "vscode": + return r.major > 1 || r.major === 1 && r.minor >= 72; + } } - if (n.hasField("select")) { - _p(e, t); - return; + if ("VTE_VERSION" in t) { + if (t.VTE_VERSION === "0.50.0") return false; + let r = Qo(t.VTE_VERSION); + return r.major > 0 || r.minor >= 50; + } + return false; + } + Jo.exports = { supportsHyperlink: ri, stdout: ri(process.stdout), stderr: ri(process.stderr) }; + }); + var Ko = Z((gf, Kt) => { + "use strict"; + var Wu = jo(), ni = Wo(), Ho = (e, t, { target: r = "stdout", ...n } = {}) => ni[r] ? Wu.link(e, t) : n.fallback === false ? e : typeof n.fallback == "function" ? n.fallback(e, t) : `${e} (\u200B${t}\u200B)`; + Kt.exports = (e, t, r = {}) => Ho(e, t, r); + Kt.exports.stderr = (e, t, r = {}) => Ho(e, t, { target: "stderr", ...r }); + Kt.exports.isSupported = ni.stdout; + Kt.exports.stderr.isSupported = ni.stderr; + }); + var oi = Z((Rf, Hu) => { + Hu.exports = { name: "@prisma/engines-version", version: "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2", main: "index.js", types: "index.d.ts", license: "Apache-2.0", author: "Tim Suchanek ", prisma: { enginesVersion: "605197351a3c8bdd595af2d2a9bc3025bca48ea2" }, repository: { type: "git", url: "https://github.com/prisma/engines-wrapper.git", directory: "packages/engines-version" }, devDependencies: { "@types/node": "18.19.34", typescript: "4.9.5" }, files: ["index.js", "index.d.ts"], scripts: { build: "tsc -d" } }; + }); + var si = Z((Wr) => { + "use strict"; + Object.defineProperty(Wr, "__esModule", { value: true }); + Wr.enginesVersion = void 0; + Wr.enginesVersion = oi().prisma.enginesVersion; + }); + var Xo = Z((Gf, Yu) => { + Yu.exports = { name: "dotenv", version: "16.0.3", description: "Loads environment variables from .env file", main: "lib/main.js", types: "lib/main.d.ts", exports: { ".": { require: "./lib/main.js", types: "./lib/main.d.ts", default: "./lib/main.js" }, "./config": "./config.js", "./config.js": "./config.js", "./lib/env-options": "./lib/env-options.js", "./lib/env-options.js": "./lib/env-options.js", "./lib/cli-options": "./lib/cli-options.js", "./lib/cli-options.js": "./lib/cli-options.js", "./package.json": "./package.json" }, scripts: { "dts-check": "tsc --project tests/types/tsconfig.json", lint: "standard", "lint-readme": "standard-markdown", pretest: "npm run lint && npm run dts-check", test: "tap tests/*.js --100 -Rspec", prerelease: "npm test", release: "standard-version" }, repository: { type: "git", url: "git://github.com/motdotla/dotenv.git" }, keywords: ["dotenv", "env", ".env", "environment", "variables", "config", "settings"], readmeFilename: "README.md", license: "BSD-2-Clause", devDependencies: { "@types/node": "^17.0.9", decache: "^4.6.1", dtslint: "^3.7.0", sinon: "^12.0.1", standard: "^16.0.4", "standard-markdown": "^7.1.0", "standard-version": "^9.3.2", tap: "^15.1.6", tar: "^6.1.11", typescript: "^4.5.4" }, engines: { node: ">=12" } }; + }); + var ts = Z((Qf, Kr) => { + "use strict"; + var Zu = __require("fs"), es = __require("path"), Xu = __require("os"), ec = Xo(), tc = ec.version, rc = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; + function nc2(e) { + let t = {}, r = e.toString(); + r = r.replace(/\r\n?/mg, ` +`); + let n; + for (; (n = rc.exec(r)) != null; ) { + let i = n[1], o = n[2] || ""; + o = o.trim(); + let s = o[0]; + o = o.replace(/^(['"`])([\s\S]*)\1$/mg, "$2"), s === '"' && (o = o.replace(/\\n/g, ` +`), o = o.replace(/\\r/g, "\r")), t[i] = o; } + return t; } - if (r?.[xt(e.outputType.name)]) { - Fp(e, t); - return; + function ci(e) { + console.log(`[dotenv@${tc}][DEBUG] ${e}`); } - t.addErrorMessage(() => `Unknown field at "${e.selectionPath.join(".")} selection"`); - } - function Dp(e, t, r) { - r.removeAllFields(); - for (let n of e.outputType.fields) r.addSuggestion(new ue(n.name, "false")); - t.addErrorMessage((n) => `The ${n.red("omit")} statement includes every field of the model ${n.bold(e.outputType.name)}. At least one field must be included in the result`); - } - function _p(e, t) { - let r = e.outputType, n = t.arguments.getDeepSelectionParent(e.selectionPath)?.value, i = n?.isEmpty() ?? false; - n && (n.removeAllFields(), Ws(n, r)), t.addErrorMessage((o) => i ? `The ${o.red("`select`")} statement for type ${o.bold(r.name)} must not be empty. ${or(o)}` : `The ${o.red("`select`")} statement for type ${o.bold(r.name)} needs ${o.bold("at least one truthy value")}.`); - } - function Fp(e, t) { - let r = new nr(); - for (let i of e.outputType.fields) i.isRelation || r.addField(i.name, "false"); - let n = new ue("omit", r).makeRequired(); - if (e.selectionPath.length === 0) t.arguments.addSuggestion(n); - else { - let [i, o] = ir(e.selectionPath), a = t.arguments.getDeepSelectionParent(i)?.value.asObject()?.getField(o); - if (a) { - let l = a?.value.asObject() ?? new At(); - l.addSuggestion(n), a.value = l; - } + function ic(e) { + return e[0] === "~" ? es.join(Xu.homedir(), e.slice(1)) : e; } - t.addErrorMessage((i) => `The global ${i.red("omit")} configuration excludes every field of the model ${i.bold(e.outputType.name)}. At least one field must be included in the result`); - } - function Lp(e, t) { - let r = Hs(e.selectionPath, t); - if (r.parentKind !== "unknown") { - r.field.markAsError(); - let n = r.parent; - switch (r.parentKind) { - case "select": - Ws(n, e.outputType); - break; - case "include": - Qp(n, e.outputType); - break; - case "omit": - Jp(n, e.outputType); - break; + function oc(e) { + let t = es.resolve(process.cwd(), ".env"), r = "utf8", n = !!(e && e.debug), i = !!(e && e.override); + e && (e.path != null && (t = ic(e.path)), e.encoding != null && (r = e.encoding)); + try { + let o = Hr.parse(Zu.readFileSync(t, { encoding: r })); + return Object.keys(o).forEach(function(s) { + Object.prototype.hasOwnProperty.call(process.env, s) ? (i === true && (process.env[s] = o[s]), n && ci(i === true ? `"${s}" is already defined in \`process.env\` and WAS overwritten` : `"${s}" is already defined in \`process.env\` and was NOT overwritten`)) : process.env[s] = o[s]; + }), { parsed: o }; + } catch (o) { + return n && ci(`Failed to load ${t} ${o.message}`), { error: o }; } } - t.addErrorMessage((n) => { - let i = [`Unknown field ${n.red(`\`${r.fieldName}\``)}`]; - return r.parentKind !== "unknown" && i.push(`for ${n.bold(r.parentKind)} statement`), i.push(`on model ${n.bold(`\`${e.outputType.name}\``)}.`), i.push(or(n)), i.join(" "); - }); + var Hr = { config: oc, parse: nc2 }; + Kr.exports.config = Hr.config; + Kr.exports.parse = Hr.parse; + Kr.exports = Hr; + }); + var as = Z((Zf, ss) => { + "use strict"; + ss.exports = (e) => { + let t = e.match(/^[ \t]*(?=\S)/gm); + return t ? t.reduce((r, n) => Math.min(r, n.length), 1 / 0) : 0; + }; + }); + var us = Z((Xf, ls) => { + "use strict"; + var uc = as(); + ls.exports = (e) => { + let t = uc(e); + if (t === 0) return e; + let r = new RegExp(`^[ \\t]{${t}}`, "gm"); + return e.replace(r, ""); + }; + }); + var fi = Z((og, cs) => { + "use strict"; + cs.exports = (e, t = 1, r) => { + if (r = { indent: " ", includeEmptyLines: false, ...r }, typeof e != "string") throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof e}\``); + if (typeof t != "number") throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof t}\``); + if (typeof r.indent != "string") throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof r.indent}\``); + if (t === 0) return e; + let n = r.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; + return e.replace(n, r.indent.repeat(t)); + }; + }); + var fs = Z((lg, ms) => { + "use strict"; + ms.exports = ({ onlyFirst: e = false } = {}) => { + let t = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"); + return new RegExp(t, e ? void 0 : "g"); + }; + }); + var bi = Z((ug, gs) => { + "use strict"; + var yc = fs(); + gs.exports = (e) => typeof e == "string" ? e.replace(yc(), "") : e; + }); + var hs = Z((dg, Zr) => { + "use strict"; + Zr.exports = (e = {}) => { + let t; + if (e.repoUrl) t = e.repoUrl; + else if (e.user && e.repo) t = `https://github.com/${e.user}/${e.repo}`; + else throw new Error("You need to specify either the `repoUrl` option or both the `user` and `repo` options"); + let r = new URL(`${t}/issues/new`), n = ["body", "title", "labels", "template", "milestone", "assignee", "projects"]; + for (let i of n) { + let o = e[i]; + if (o !== void 0) { + if (i === "labels" || i === "projects") { + if (!Array.isArray(o)) throw new TypeError(`The \`${i}\` option should be an array`); + o = o.join(","); + } + r.searchParams.set(i, o); + } + } + return r.toString(); + }; + Zr.exports.default = Zr.exports; + }); + var Ai = Z((Th, $s) => { + "use strict"; + $s.exports = /* @__PURE__ */ function() { + function e(t, r, n, i, o) { + return t < r || n < r ? t > n ? n + 1 : t + 1 : i === o ? r : r + 1; + } + return function(t, r) { + if (t === r) return 0; + if (t.length > r.length) { + var n = t; + t = r, r = n; + } + for (var i = t.length, o = r.length; i > 0 && t.charCodeAt(i - 1) === r.charCodeAt(o - 1); ) i--, o--; + for (var s = 0; s < i && t.charCodeAt(s) === r.charCodeAt(s); ) s++; + if (i -= s, o -= s, i === 0 || o < 3) return o; + var a = 0, l, u, c, p, d, f, g, h, O, T, S, C, E = []; + for (l = 0; l < i; l++) E.push(l + 1), E.push(t.charCodeAt(s + l)); + for (var me = E.length - 1; a < o - 3; ) for (O = r.charCodeAt(s + (u = a)), T = r.charCodeAt(s + (c = a + 1)), S = r.charCodeAt(s + (p = a + 2)), C = r.charCodeAt(s + (d = a + 3)), f = a += 4, l = 0; l < me; l += 2) g = E[l], h = E[l + 1], u = e(g, u, c, O, h), c = e(u, c, p, T, h), p = e(c, p, d, S, h), f = e(p, d, f, C, h), E[l] = f, d = p, p = c, c = u, u = g; + for (; a < o; ) for (O = r.charCodeAt(s + (u = a)), f = ++a, l = 0; l < me; l += 2) g = E[l], E[l] = f = e(g, u, f, O, E[l + 1]), u = g; + return f; + }; + }(); + }); + var Nm = {}; + Ut(Nm, { Debug: () => Gn, Decimal: () => xe, Extensions: () => jn, MetricsClient: () => Dt, NotFoundError: () => Le, PrismaClientInitializationError: () => R, PrismaClientKnownRequestError: () => V, PrismaClientRustPanicError: () => le, PrismaClientUnknownRequestError: () => B, PrismaClientValidationError: () => J, Public: () => Vn, Sql: () => oe, defineDmmfProperty: () => ua, deserializeJsonResponse: () => wt, dmmfToRuntimeDataModel: () => la, empty: () => ma, getPrismaClient: () => Yl, getRuntime: () => In, join: () => da, makeStrictEnum: () => Zl, makeTypedQueryFactory: () => ca, objectEnumValues: () => yn, raw: () => ji, serializeJsonQuery: () => vn, skip: () => Pn, sqltag: () => Vi, warnEnvConflicts: () => Xl, warnOnce: () => tr }); + module.exports = ou(Nm); + var jn = {}; + Ut(jn, { defineExtension: () => yo, getExtensionContext: () => bo }); + function yo(e) { + return typeof e == "function" ? e : (t) => t.$extends(e); } - function Np(e, t) { - let r = Hs(e.selectionPath, t); - r.parentKind !== "unknown" && r.field.value.markAsError(), t.addErrorMessage((n) => `Invalid value for selection field \`${n.red(r.fieldName)}\`: ${e.underlyingError}`); + function bo(e) { + return e; } - function Mp(e, t) { - let r = e.argumentPath[0], n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); - n && (n.getField(r)?.markAsError(), Wp(n, e.arguments)), t.addErrorMessage((i) => Qs(i, r, e.arguments.map((o) => o.name))); + var Vn = {}; + Ut(Vn, { validator: () => Eo }); + function Eo(...e) { + return (t) => t; } - function $p(e, t) { - let [r, n] = ir(e.argumentPath), i = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); - if (i) { - i.getDeepField(e.argumentPath)?.markAsError(); - let o = i.getDeepFieldValue(r)?.asObject(); - o && Ks(o, e.inputType); - } - t.addErrorMessage((o) => Qs(o, n, e.inputType.fields.map((s) => s.name))); + var Mr = {}; + Ut(Mr, { $: () => To, bgBlack: () => gu, bgBlue: () => Eu, bgCyan: () => xu, bgGreen: () => yu, bgMagenta: () => wu, bgRed: () => hu, bgWhite: () => Pu, bgYellow: () => bu, black: () => pu, blue: () => rt, bold: () => H, cyan: () => De, dim: () => Oe, gray: () => Gt, green: () => qe, grey: () => fu, hidden: () => uu, inverse: () => lu, italic: () => au, magenta: () => du, red: () => ce, reset: () => su, strikethrough: () => cu, underline: () => X, white: () => mu, yellow: () => ke }); + var Bn; + var wo; + var xo; + var Po; + var vo = true; + typeof process < "u" && ({ FORCE_COLOR: Bn, NODE_DISABLE_COLORS: wo, NO_COLOR: xo, TERM: Po } = process.env || {}, vo = process.stdout && process.stdout.isTTY); + var To = { enabled: !wo && xo == null && Po !== "dumb" && (Bn != null && Bn !== "0" || vo) }; + function M(e, t) { + let r = new RegExp(`\\x1b\\[${t}m`, "g"), n = `\x1B[${e}m`, i = `\x1B[${t}m`; + return function(o) { + return !To.enabled || o == null ? o : n + (~("" + o).indexOf(i) ? o.replace(r, i + n) : o) + i; + }; } - function Qs(e, t, r) { - let n = [`Unknown argument \`${e.red(t)}\`.`], i = Kp(t, r); - return i && n.push(`Did you mean \`${e.green(i)}\`?`), r.length > 0 && n.push(or(e)), n.join(" "); + var su = M(0, 0); + var H = M(1, 22); + var Oe = M(2, 22); + var au = M(3, 23); + var X = M(4, 24); + var lu = M(7, 27); + var uu = M(8, 28); + var cu = M(9, 29); + var pu = M(30, 39); + var ce = M(31, 39); + var qe = M(32, 39); + var ke = M(33, 39); + var rt = M(34, 39); + var du = M(35, 39); + var De = M(36, 39); + var mu = M(37, 39); + var Gt = M(90, 39); + var fu = M(90, 39); + var gu = M(40, 49); + var hu = M(41, 49); + var yu = M(42, 49); + var bu = M(43, 49); + var Eu = M(44, 49); + var wu = M(45, 49); + var xu = M(46, 49); + var Pu = M(47, 49); + var vu = 100; + var Ro = ["green", "yellow", "blue", "magenta", "cyan", "red"]; + var Qt = []; + var Co = Date.now(); + var Tu = 0; + var Un = typeof process < "u" ? process.env : {}; + globalThis.DEBUG ??= Un.DEBUG ?? ""; + globalThis.DEBUG_COLORS ??= Un.DEBUG_COLORS ? Un.DEBUG_COLORS === "true" : true; + var Jt = { enable(e) { + typeof e == "string" && (globalThis.DEBUG = e); + }, disable() { + let e = globalThis.DEBUG; + return globalThis.DEBUG = "", e; + }, enabled(e) { + let t = globalThis.DEBUG.split(",").map((i) => i.replace(/[.+?^${}()|[\]\\]/g, "\\$&")), r = t.some((i) => i === "" || i[0] === "-" ? false : e.match(RegExp(i.split("*").join(".*") + "$"))), n = t.some((i) => i === "" || i[0] !== "-" ? false : e.match(RegExp(i.slice(1).split("*").join(".*") + "$"))); + return r && !n; + }, log: (...e) => { + let [t, r, ...n] = e; + (console.warn ?? console.log)(`${t} ${r}`, ...n); + }, formatters: {} }; + function Ru(e) { + let t = { color: Ro[Tu++ % Ro.length], enabled: Jt.enabled(e), namespace: e, log: Jt.log, extend: () => { + } }, r = (...n) => { + let { enabled: i, namespace: o, color: s, log: a } = t; + if (n.length !== 0 && Qt.push([o, ...n]), Qt.length > vu && Qt.shift(), Jt.enabled(o) || i) { + let l = n.map((c) => typeof c == "string" ? c : Cu(c)), u = `+${Date.now() - Co}ms`; + Co = Date.now(), globalThis.DEBUG_COLORS ? a(Mr[s](H(o)), ...l, Mr[s](u)) : a(o, ...l, u); + } + }; + return new Proxy(r, { get: (n, i) => t[i], set: (n, i, o) => t[i] = o }); } - function qp(e, t) { - let r; - t.addErrorMessage((l) => r?.value instanceof W && r.value.text === "null" ? `Argument \`${l.green(o)}\` must not be ${l.red("null")}.` : `Argument \`${l.green(o)}\` is missing.`); - let n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); - if (!n) return; - let [i, o] = ir(e.argumentPath), s = new nr(), a = n.getDeepFieldValue(i)?.asObject(); - if (a) if (r = a.getField(o), r && a.removeField(o), e.inputTypes.length === 1 && e.inputTypes[0].kind === "object") { - for (let l of e.inputTypes[0].fields) s.addField(l.name, l.typeNames.join(" | ")); - a.addSuggestion(new ue(o, s).makeRequired()); - } else { - let l = e.inputTypes.map(Js).join(" | "); - a.addSuggestion(new ue(o, l).makeRequired()); - } + var Gn = new Proxy(Ru, { get: (e, t) => Jt[t], set: (e, t, r) => Jt[t] = r }); + function Cu(e, t = 2) { + let r = /* @__PURE__ */ new Set(); + return JSON.stringify(e, (n, i) => { + if (typeof i == "object" && i !== null) { + if (r.has(i)) return "[Circular *]"; + r.add(i); + } else if (typeof i == "bigint") return i.toString(); + return i; + }, t); } - function Js(e) { - return e.kind === "list" ? `${Js(e.elementType)}[]` : e.name; + function So(e = 7500) { + let t = Qt.map(([r, ...n]) => `${r} ${n.map((i) => typeof i == "string" ? i : JSON.stringify(i)).join(" ")}`).join(` +`); + return t.length < e ? t : t.slice(-e); } - function jp(e, t) { - let r = e.argument.name, n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); - n && n.getDeepFieldValue(e.argumentPath)?.markAsError(), t.addErrorMessage((i) => { - let o = gn("or", e.argument.typeNames.map((s) => i.green(s))); - return `Argument \`${i.bold(r)}\`: Invalid value provided. Expected ${o}, provided ${i.red(e.inferredType)}.`; - }); + function Ao() { + Qt.length = 0; } - function Vp(e, t) { - let r = e.argument.name, n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); - n && n.getDeepFieldValue(e.argumentPath)?.markAsError(), t.addErrorMessage((i) => { - let o = [`Invalid value for argument \`${i.bold(r)}\``]; - if (e.underlyingError && o.push(`: ${e.underlyingError}`), o.push("."), e.argument.typeNames.length > 0) { - let s = gn("or", e.argument.typeNames.map((a) => i.green(a))); - o.push(` Expected ${s}.`); - } - return o.join(""); - }); + var L = Gn; + var Io = k(__require("fs")); + function Qn() { + let e = process.env.PRISMA_QUERY_ENGINE_LIBRARY; + if (!(e && Io.default.existsSync(e)) && process.arch === "ia32") throw new Error('The default query engine type (Node-API, "library") is currently not supported for 32bit Node. Please set `engineType = "binary"` in the "generator" block of your "schema.prisma" file (or use the environment variables "PRISMA_CLIENT_ENGINE_TYPE=binary" and/or "PRISMA_CLI_QUERY_ENGINE_TYPE=binary".)'); } - function Bp(e, t) { - let r = e.argument.name, n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(), i; - if (n) { - let s = n.getDeepField(e.argumentPath)?.value; - s?.markAsError(), s instanceof W && (i = s.text); - } - t.addErrorMessage((o) => { - let s = ["Unable to fit value"]; - return i && s.push(o.red(i)), s.push(`into a 64-bit signed integer for field \`${o.bold(r)}\``), s.join(" "); - }); + var Jn = ["darwin", "darwin-arm64", "debian-openssl-1.0.x", "debian-openssl-1.1.x", "debian-openssl-3.0.x", "rhel-openssl-1.0.x", "rhel-openssl-1.1.x", "rhel-openssl-3.0.x", "linux-arm64-openssl-1.1.x", "linux-arm64-openssl-1.0.x", "linux-arm64-openssl-3.0.x", "linux-arm-openssl-1.1.x", "linux-arm-openssl-1.0.x", "linux-arm-openssl-3.0.x", "linux-musl", "linux-musl-openssl-3.0.x", "linux-musl-arm64-openssl-1.1.x", "linux-musl-arm64-openssl-3.0.x", "linux-nixos", "linux-static-x64", "linux-static-arm64", "windows", "freebsd11", "freebsd12", "freebsd13", "freebsd14", "freebsd15", "openbsd", "netbsd", "arm"]; + var $r = "libquery_engine"; + function qr(e, t) { + let r = t === "url"; + return e.includes("windows") ? r ? "query_engine.dll.node" : `query_engine-${e}.dll.node` : e.includes("darwin") ? r ? `${$r}.dylib.node` : `${$r}-${e}.dylib.node` : r ? `${$r}.so.node` : `${$r}-${e}.so.node`; } - function Up(e, t) { - let r = e.argumentPath[e.argumentPath.length - 1], n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); - if (n) { - let i = n.getDeepFieldValue(e.argumentPath)?.asObject(); - i && Ks(i, e.inputType); + var _o = k(__require("child_process")); + var zn = k(__require("fs/promises")); + var Gr = k(__require("os")); + var _e = Symbol.for("@ts-pattern/matcher"); + var Su = Symbol.for("@ts-pattern/isVariadic"); + var Vr = "@ts-pattern/anonymous-select-key"; + var Wn = (e) => !!(e && typeof e == "object"); + var jr = (e) => e && !!e[_e]; + var Ee = (e, t, r) => { + if (jr(e)) { + let n = e[_e](), { matched: i, selections: o } = n.match(t); + return i && o && Object.keys(o).forEach((s) => r(s, o[s])), i; } - t.addErrorMessage((i) => { - let o = [`Argument \`${i.bold(r)}\` of type ${i.bold(e.inputType.name)} needs`]; - return e.constraints.minFieldCount === 1 ? e.constraints.requiredFields ? o.push(`${i.green("at least one of")} ${gn("or", e.constraints.requiredFields.map((s) => `\`${i.bold(s)}\``))} arguments.`) : o.push(`${i.green("at least one")} argument.`) : o.push(`${i.green(`at least ${e.constraints.minFieldCount}`)} arguments.`), o.push(or(i)), o.join(" "); - }); - } - function Gp(e, t) { - let r = e.argumentPath[e.argumentPath.length - 1], n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(), i = []; - if (n) { - let o = n.getDeepFieldValue(e.argumentPath)?.asObject(); - o && (o.markAsError(), i = Object.keys(o.getFields())); + if (Wn(e)) { + if (!Wn(t)) return false; + if (Array.isArray(e)) { + if (!Array.isArray(t)) return false; + let n = [], i = [], o = []; + for (let s of e.keys()) { + let a = e[s]; + jr(a) && a[Su] ? o.push(a) : o.length ? i.push(a) : n.push(a); + } + if (o.length) { + if (o.length > 1) throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed."); + if (t.length < n.length + i.length) return false; + let s = t.slice(0, n.length), a = i.length === 0 ? [] : t.slice(-i.length), l = t.slice(n.length, i.length === 0 ? 1 / 0 : -i.length); + return n.every((u, c) => Ee(u, s[c], r)) && i.every((u, c) => Ee(u, a[c], r)) && (o.length === 0 || Ee(o[0], l, r)); + } + return e.length === t.length && e.every((s, a) => Ee(s, t[a], r)); + } + return Object.keys(e).every((n) => { + let i = e[n]; + return (n in t || jr(o = i) && o[_e]().matcherType === "optional") && Ee(i, t[n], r); + var o; + }); } - t.addErrorMessage((o) => { - let s = [`Argument \`${o.bold(r)}\` of type ${o.bold(e.inputType.name)} needs`]; - return e.constraints.minFieldCount === 1 && e.constraints.maxFieldCount == 1 ? s.push(`${o.green("exactly one")} argument,`) : e.constraints.maxFieldCount == 1 ? s.push(`${o.green("at most one")} argument,`) : s.push(`${o.green(`at most ${e.constraints.maxFieldCount}`)} arguments,`), s.push(`but you provided ${gn("and", i.map((a) => o.red(a)))}. Please choose`), e.constraints.maxFieldCount === 1 ? s.push("one.") : s.push(`${e.constraints.maxFieldCount}.`), s.join(" "); - }); + return Object.is(t, e); + }; + var Ge = (e) => { + var t, r, n; + return Wn(e) ? jr(e) ? (t = (r = (n = e[_e]()).getSelectionKeys) == null ? void 0 : r.call(n)) != null ? t : [] : Array.isArray(e) ? Wt(e, Ge) : Wt(Object.values(e), Ge) : []; + }; + var Wt = (e, t) => e.reduce((r, n) => r.concat(t(n)), []); + function pe(e) { + return Object.assign(e, { optional: () => Au(e), and: (t) => j(e, t), or: (t) => Iu(e, t), select: (t) => t === void 0 ? Oo(e) : Oo(t, e) }); } - function Ws(e, t) { - for (let r of t.fields) e.hasField(r.name) || e.addSuggestion(new ue(r.name, "true")); + function Au(e) { + return pe({ [_e]: () => ({ match: (t) => { + let r = {}, n = (i, o) => { + r[i] = o; + }; + return t === void 0 ? (Ge(e).forEach((i) => n(i, void 0)), { matched: true, selections: r }) : { matched: Ee(e, t, n), selections: r }; + }, getSelectionKeys: () => Ge(e), matcherType: "optional" }) }); } - function Qp(e, t) { - for (let r of t.fields) r.isRelation && !e.hasField(r.name) && e.addSuggestion(new ue(r.name, "true")); + function j(...e) { + return pe({ [_e]: () => ({ match: (t) => { + let r = {}, n = (i, o) => { + r[i] = o; + }; + return { matched: e.every((i) => Ee(i, t, n)), selections: r }; + }, getSelectionKeys: () => Wt(e, Ge), matcherType: "and" }) }); } - function Jp(e, t) { - for (let r of t.fields) !e.hasField(r.name) && !r.isRelation && e.addSuggestion(new ue(r.name, "true")); + function Iu(...e) { + return pe({ [_e]: () => ({ match: (t) => { + let r = {}, n = (i, o) => { + r[i] = o; + }; + return Wt(e, Ge).forEach((i) => n(i, void 0)), { matched: e.some((i) => Ee(i, t, n)), selections: r }; + }, getSelectionKeys: () => Wt(e, Ge), matcherType: "or" }) }); } - function Wp(e, t) { - for (let r of t) e.hasField(r.name) || e.addSuggestion(new ue(r.name, r.typeNames.join(" | "))); + function I(e) { + return { [_e]: () => ({ match: (t) => ({ matched: !!e(t) }) }) }; } - function Hs(e, t) { - let [r, n] = ir(e), i = t.arguments.getDeepSubSelectionValue(r)?.asObject(); - if (!i) return { parentKind: "unknown", fieldName: n }; - let o = i.getFieldValue("select")?.asObject(), s = i.getFieldValue("include")?.asObject(), a = i.getFieldValue("omit")?.asObject(), l = o?.getField(n); - return o && l ? { parentKind: "select", parent: o, field: l, fieldName: n } : (l = s?.getField(n), s && l ? { parentKind: "include", field: l, parent: s, fieldName: n } : (l = a?.getField(n), a && l ? { parentKind: "omit", field: l, parent: a, fieldName: n } : { parentKind: "unknown", fieldName: n })); + function Oo(...e) { + let t = typeof e[0] == "string" ? e[0] : void 0, r = e.length === 2 ? e[1] : typeof e[0] == "string" ? void 0 : e[0]; + return pe({ [_e]: () => ({ match: (n) => { + let i = { [t ?? Vr]: n }; + return { matched: r === void 0 || Ee(r, n, (o, s) => { + i[o] = s; + }), selections: i }; + }, getSelectionKeys: () => [t ?? Vr].concat(r === void 0 ? [] : Ge(r)) }) }); } - function Ks(e, t) { - if (t.kind === "object") for (let r of t.fields) e.hasField(r.name) || e.addSuggestion(new ue(r.name, r.typeNames.join(" | "))); + function ye(e) { + return typeof e == "number"; } - function ir(e) { - let t = [...e], r = t.pop(); - if (!r) throw new Error("unexpected empty path"); - return [t, r]; + function je(e) { + return typeof e == "string"; } - function or({ green: e, enabled: t }) { - return "Available options are " + (t ? `listed in ${e("green")}` : "marked with ?") + "."; + function Ve(e) { + return typeof e == "bigint"; } - function gn(e, t) { - if (t.length === 1) return t[0]; - let r = [...t], n = r.pop(); - return `${r.join(", ")} ${e} ${n}`; + var Km = pe(I(function(e) { + return true; + })); + var Be = (e) => Object.assign(pe(e), { startsWith: (t) => { + return Be(j(e, (r = t, I((n) => je(n) && n.startsWith(r))))); + var r; + }, endsWith: (t) => { + return Be(j(e, (r = t, I((n) => je(n) && n.endsWith(r))))); + var r; + }, minLength: (t) => Be(j(e, ((r) => I((n) => je(n) && n.length >= r))(t))), length: (t) => Be(j(e, ((r) => I((n) => je(n) && n.length === r))(t))), maxLength: (t) => Be(j(e, ((r) => I((n) => je(n) && n.length <= r))(t))), includes: (t) => { + return Be(j(e, (r = t, I((n) => je(n) && n.includes(r))))); + var r; + }, regex: (t) => { + return Be(j(e, (r = t, I((n) => je(n) && !!n.match(r))))); + var r; + } }); + var zm = Be(I(je)); + var be = (e) => Object.assign(pe(e), { between: (t, r) => be(j(e, ((n, i) => I((o) => ye(o) && n <= o && i >= o))(t, r))), lt: (t) => be(j(e, ((r) => I((n) => ye(n) && n < r))(t))), gt: (t) => be(j(e, ((r) => I((n) => ye(n) && n > r))(t))), lte: (t) => be(j(e, ((r) => I((n) => ye(n) && n <= r))(t))), gte: (t) => be(j(e, ((r) => I((n) => ye(n) && n >= r))(t))), int: () => be(j(e, I((t) => ye(t) && Number.isInteger(t)))), finite: () => be(j(e, I((t) => ye(t) && Number.isFinite(t)))), positive: () => be(j(e, I((t) => ye(t) && t > 0))), negative: () => be(j(e, I((t) => ye(t) && t < 0))) }); + var Ym = be(I(ye)); + var Ue = (e) => Object.assign(pe(e), { between: (t, r) => Ue(j(e, ((n, i) => I((o) => Ve(o) && n <= o && i >= o))(t, r))), lt: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n < r))(t))), gt: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n > r))(t))), lte: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n <= r))(t))), gte: (t) => Ue(j(e, ((r) => I((n) => Ve(n) && n >= r))(t))), positive: () => Ue(j(e, I((t) => Ve(t) && t > 0))), negative: () => Ue(j(e, I((t) => Ve(t) && t < 0))) }); + var Zm = Ue(I(Ve)); + var Xm = pe(I(function(e) { + return typeof e == "boolean"; + })); + var ef = pe(I(function(e) { + return typeof e == "symbol"; + })); + var tf = pe(I(function(e) { + return e == null; + })); + var rf = pe(I(function(e) { + return e != null; + })); + var Hn = { matched: false, value: void 0 }; + function mt(e) { + return new Kn(e, Hn); } - var Hp = 3; - function Kp(e, t) { - let r = 1 / 0, n; - for (let i of t) { - let o = (0, Gs.default)(e, i); - o > Hp || o < r && (r = o, n = i); + var Kn = class e { + constructor(t, r) { + this.input = void 0, this.state = void 0, this.input = t, this.state = r; } - return n; - } - function zs(e) { - return e.substring(0, 1).toLowerCase() + e.substring(1); - } - var sr = class { - constructor(t, r, n, i, o) { - this.modelName = t, this.name = r, this.typeName = n, this.isList = i, this.isEnum = o; + with(...t) { + if (this.state.matched) return this; + let r = t[t.length - 1], n = [t[0]], i; + t.length === 3 && typeof t[1] == "function" ? i = t[1] : t.length > 2 && n.push(...t.slice(1, t.length - 1)); + let o = false, s = {}, a = (u, c) => { + o = true, s[u] = c; + }, l = !n.some((u) => Ee(u, this.input, a)) || i && !i(this.input) ? Hn : { matched: true, value: r(o ? Vr in s ? s[Vr] : s : this.input, this.input) }; + return new e(this.input, l); } - _toGraphQLInputType() { - let t = this.isList ? "List" : "", r = this.isEnum ? "Enum" : ""; - return `${t}${r}${this.typeName}FieldRefInput<${this.modelName}>`; + when(t, r) { + if (this.state.matched) return this; + let n = !!t(this.input); + return new e(this.input, n ? { matched: true, value: r(this.input, this.input) } : Hn); } - }; - function It(e) { - return e instanceof sr; - } - var hn = Symbol(); - var Ii = /* @__PURE__ */ new WeakMap(); - var Me = class { - constructor(t) { - t === hn ? Ii.set(this, `Prisma.${this._getName()}`) : Ii.set(this, `new Prisma.${this._getNamespace()}.${this._getName()}()`); + otherwise(t) { + return this.state.matched ? this.state.value : t(this.input); } - _getName() { - return this.constructor.name; + exhaustive() { + if (this.state.matched) return this.state.value; + let t; + try { + t = JSON.stringify(this.input); + } catch { + t = this.input; + } + throw new Error(`Pattern matching error: no pattern matches value ${t}`); } - toString() { - return Ii.get(this); + run() { + return this.exhaustive(); } - }; - var ar = class extends Me { - _getNamespace() { - return "NullTypes"; + returnType() { + return this; } }; - var lr = class extends ar { - }; - Oi(lr, "DbNull"); - var ur = class extends ar { - }; - Oi(ur, "JsonNull"); - var cr = class extends ar { - }; - Oi(cr, "AnyNull"); - var yn = { classes: { DbNull: lr, JsonNull: ur, AnyNull: cr }, instances: { DbNull: new lr(hn), JsonNull: new ur(hn), AnyNull: new cr(hn) } }; - function Oi(e, t) { - Object.defineProperty(e, "name", { value: t, configurable: true }); + var Fo = __require("util"); + var Ou = { warn: ke("prisma:warn") }; + var ku = { warn: () => !process.env.PRISMA_DISABLE_WARNINGS }; + function Br(e, ...t) { + ku.warn() && console.warn(`${Ou.warn} ${e}`, ...t); } - var Ys = ": "; - var bn = class { - constructor(t, r) { - this.name = t; - this.value = r; - this.hasError = false; - } - markAsError() { - this.hasError = true; + var Du = (0, Fo.promisify)(_o.default.exec); + var te = L("prisma:get-platform"); + var _u = ["1.0.x", "1.1.x", "3.0.x"]; + async function Lo() { + let e = Gr.default.platform(), t = process.arch; + if (e === "freebsd") { + let s = await Qr("freebsd-version"); + if (s && s.trim().length > 0) { + let l = /^(\d+)\.?/.exec(s); + if (l) return { platform: "freebsd", targetDistro: `freebsd${l[1]}`, arch: t }; + } } - getPrintWidth() { - return this.name.length + this.value.getPrintWidth() + Ys.length; + if (e !== "linux") return { platform: e, arch: t }; + let r = await Lu(), n = await Uu(), i = Mu({ arch: t, archFromUname: n, familyDistro: r.familyDistro }), { libssl: o } = await $u(i); + return { platform: "linux", libssl: o, arch: t, archFromUname: n, ...r }; + } + function Fu(e) { + let t = /^ID="?([^"\n]*)"?$/im, r = /^ID_LIKE="?([^"\n]*)"?$/im, n = t.exec(e), i = n && n[1] && n[1].toLowerCase() || "", o = r.exec(e), s = o && o[1] && o[1].toLowerCase() || "", a = mt({ id: i, idLike: s }).with({ id: "alpine" }, ({ id: l }) => ({ targetDistro: "musl", familyDistro: l, originalDistro: l })).with({ id: "raspbian" }, ({ id: l }) => ({ targetDistro: "arm", familyDistro: "debian", originalDistro: l })).with({ id: "nixos" }, ({ id: l }) => ({ targetDistro: "nixos", originalDistro: l, familyDistro: "nixos" })).with({ id: "debian" }, { id: "ubuntu" }, ({ id: l }) => ({ targetDistro: "debian", familyDistro: "debian", originalDistro: l })).with({ id: "rhel" }, { id: "centos" }, { id: "fedora" }, ({ id: l }) => ({ targetDistro: "rhel", familyDistro: "rhel", originalDistro: l })).when(({ idLike: l }) => l.includes("debian") || l.includes("ubuntu"), ({ id: l }) => ({ targetDistro: "debian", familyDistro: "debian", originalDistro: l })).when(({ idLike: l }) => i === "arch" || l.includes("arch"), ({ id: l }) => ({ targetDistro: "debian", familyDistro: "arch", originalDistro: l })).when(({ idLike: l }) => l.includes("centos") || l.includes("fedora") || l.includes("rhel") || l.includes("suse"), ({ id: l }) => ({ targetDistro: "rhel", familyDistro: "rhel", originalDistro: l })).otherwise(({ id: l }) => ({ targetDistro: void 0, familyDistro: void 0, originalDistro: l })); + return te(`Found distro info: +${JSON.stringify(a, null, 2)}`), a; + } + async function Lu() { + let e = "/etc/os-release"; + try { + let t = await zn.default.readFile(e, { encoding: "utf-8" }); + return Fu(t); + } catch { + return { targetDistro: void 0, familyDistro: void 0, originalDistro: void 0 }; } - write(t) { - let r = new Pe(this.name); - this.hasError && r.underline().setColor(t.context.colors.red), t.write(r).write(Ys).write(this.value); + } + function Nu(e) { + let t = /^OpenSSL\s(\d+\.\d+)\.\d+/.exec(e); + if (t) { + let r = `${t[1]}.x`; + return No(r); } - }; - var ki = class { - constructor(t) { - this.errorMessages = []; - this.arguments = t; + } + function ko(e) { + let t = /libssl\.so\.(\d)(\.\d)?/.exec(e); + if (t) { + let r = `${t[1]}${t[2] ?? ".0"}.x`; + return No(r); } - write(t) { - t.write(this.arguments); + } + function No(e) { + let t = (() => { + if ($o(e)) return e; + let r = e.split("."); + return r[1] = "0", r.join("."); + })(); + if (_u.includes(t)) return t; + } + function Mu(e) { + return mt(e).with({ familyDistro: "musl" }, () => (te('Trying platform-specific paths for "alpine"'), ["/lib"])).with({ familyDistro: "debian" }, ({ archFromUname: t }) => (te('Trying platform-specific paths for "debian" (and "ubuntu")'), [`/usr/lib/${t}-linux-gnu`, `/lib/${t}-linux-gnu`])).with({ familyDistro: "rhel" }, () => (te('Trying platform-specific paths for "rhel"'), ["/lib64", "/usr/lib64"])).otherwise(({ familyDistro: t, arch: r, archFromUname: n }) => (te(`Don't know any platform-specific paths for "${t}" on ${r} (${n})`), [])); + } + async function $u(e) { + let t = 'grep -v "libssl.so.0"', r = await Do(e); + if (r) { + te(`Found libssl.so file using platform-specific paths: ${r}`); + let o = ko(r); + if (te(`The parsed libssl version is: ${o}`), o) return { libssl: o, strategy: "libssl-specific-path" }; } - addErrorMessage(t) { - this.errorMessages.push(t); + te('Falling back to "ldconfig" and other generic paths'); + let n = await Qr(`ldconfig -p | sed "s/.*=>s*//" | sed "s|.*/||" | grep libssl | sort | ${t}`); + if (n || (n = await Do(["/lib64", "/usr/lib64", "/lib"])), n) { + te(`Found libssl.so file using "ldconfig" or other generic paths: ${n}`); + let o = ko(n); + if (te(`The parsed libssl version is: ${o}`), o) return { libssl: o, strategy: "ldconfig" }; } - renderAllMessages(t) { - return this.errorMessages.map((r) => r(t)).join(` -`); + let i = await Qr("openssl version -v"); + if (i) { + te(`Found openssl binary with version: ${i}`); + let o = Nu(i); + if (te(`The parsed openssl version is: ${o}`), o) return { libssl: o, strategy: "openssl-binary" }; } - }; - function Ot(e) { - return new ki(Zs(e)); + return te("Couldn't find any version of libssl or OpenSSL in the system"), {}; } - function Zs(e) { - let t = new At(); - for (let [r, n] of Object.entries(e)) { - let i = new bn(r, Xs(n)); - t.addField(i); + async function Do(e) { + for (let t of e) { + let r = await qu(t); + if (r) return r; } - return t; } - function Xs(e) { - if (typeof e == "string") return new W(JSON.stringify(e)); - if (typeof e == "number" || typeof e == "boolean") return new W(String(e)); - if (typeof e == "bigint") return new W(`${e}n`); - if (e === null) return new W("null"); - if (e === void 0) return new W("undefined"); - if (vt(e)) return new W(`new Prisma.Decimal("${e.toFixed()}")`); - if (e instanceof Uint8Array) return Buffer.isBuffer(e) ? new W(`Buffer.alloc(${e.byteLength})`) : new W(`new Uint8Array(${e.byteLength})`); - if (e instanceof Date) { - let t = ln(e) ? e.toISOString() : "Invalid Date"; - return new W(`new Date("${t}")`); + async function qu(e) { + try { + return (await zn.default.readdir(e)).find((r) => r.startsWith("libssl.so.") && !r.startsWith("libssl.so.0")); + } catch (t) { + if (t.code === "ENOENT") return; + throw t; } - return e instanceof Me ? new W(`Prisma.${e._getName()}`) : It(e) ? new W(`prisma.${zs(e.modelName)}.$fields.${e.name}`) : Array.isArray(e) ? zp(e) : typeof e == "object" ? Zs(e) : new W(Object.prototype.toString.call(e)); } - function zp(e) { - let t = new St(); - for (let r of e) t.addItem(Xs(r)); - return t; + async function nt() { + let { binaryTarget: e } = await Mo(); + return e; } - function En(e, t) { - let r = t === "pretty" ? Us : fn, n = e.renderAllMessages(r), i = new Rt(0, { colors: r }).write(e).toString(); - return { message: n, args: i }; + function ju(e) { + return e.binaryTarget !== void 0; } - function wn({ args: e, errors: t, errorFormat: r, callsite: n, originalMethod: i, clientVersion: o, globalOmit: s }) { - let a = Ot(e); - for (let p of t) pn(p, a, s); - let { message: l, args: u } = En(a, r), c = Tt({ message: l, callsite: n, originalMethod: i, showColors: r === "pretty", callArguments: u }); - throw new J(c, { clientVersion: o }); + async function Yn() { + let { memoized: e, ...t } = await Mo(); + return t; } - var ve = class { - constructor() { - this._map = /* @__PURE__ */ new Map(); - } - get(t) { - return this._map.get(t)?.value; + var Ur = {}; + async function Mo() { + if (ju(Ur)) return Promise.resolve({ ...Ur, memoized: true }); + let e = await Lo(), t = Vu(e); + return Ur = { ...e, binaryTarget: t }, { ...Ur, memoized: false }; + } + function Vu(e) { + let { platform: t, arch: r, archFromUname: n, libssl: i, targetDistro: o, familyDistro: s, originalDistro: a } = e; + t === "linux" && !["x64", "arm64"].includes(r) && Br(`Prisma only officially supports Linux on amd64 (x86_64) and arm64 (aarch64) system architectures (detected "${r}" instead). If you are using your own custom Prisma engines, you can ignore this warning, as long as you've compiled the engines for your system architecture "${n}".`); + let l = "1.1.x"; + if (t === "linux" && i === void 0) { + let c = mt({ familyDistro: s }).with({ familyDistro: "debian" }, () => "Please manually install OpenSSL via `apt-get update -y && apt-get install -y openssl` and try installing Prisma again. If you're running Prisma on Docker, add this command to your Dockerfile, or switch to an image that already has OpenSSL installed.").otherwise(() => "Please manually install OpenSSL and try installing Prisma again."); + Br(`Prisma failed to detect the libssl/openssl version to use, and may not work as expected. Defaulting to "openssl-${l}". +${c}`); } - set(t, r) { - this._map.set(t, { value: r }); + let u = "debian"; + if (t === "linux" && o === void 0 && te(`Distro is "${a}". Falling back to Prisma engines built for "${u}".`), t === "darwin" && r === "arm64") return "darwin-arm64"; + if (t === "darwin") return "darwin"; + if (t === "win32") return "windows"; + if (t === "freebsd") return o; + if (t === "openbsd") return "openbsd"; + if (t === "netbsd") return "netbsd"; + if (t === "linux" && o === "nixos") return "linux-nixos"; + if (t === "linux" && r === "arm64") return `${o === "musl" ? "linux-musl-arm64" : "linux-arm64"}-openssl-${i || l}`; + if (t === "linux" && r === "arm") return `linux-arm-openssl-${i || l}`; + if (t === "linux" && o === "musl") { + let c = "linux-musl"; + return !i || $o(i) ? c : `${c}-openssl-${i}`; } - getOrCreate(t, r) { - let n = this._map.get(t); - if (n) return n.value; - let i = r(); - return this.set(t, i), i; + return t === "linux" && o && i ? `${o}-openssl-${i}` : (t !== "linux" && Br(`Prisma detected unknown OS "${t}" and may not work as expected. Defaulting to "linux".`), i ? `${u}-openssl-${i}` : o ? `${o}-openssl-${l}` : `${u}-openssl-${l}`); + } + async function Bu(e) { + try { + return await e(); + } catch { + return; } - }; - function pr(e) { - let t; - return { get() { - return t || (t = { value: e() }), t.value; - } }; } - function Te(e) { - return e.replace(/^./, (t) => t.toLowerCase()); + function Qr(e) { + return Bu(async () => { + let t = await Du(e); + return te(`Command "${e}" successfully returned "${t.stdout}"`), t.stdout; + }); } - function ta(e, t, r) { - let n = Te(r); - return !t.result || !(t.result.$allModels || t.result[n]) ? e : Yp({ ...e, ...ea(t.name, e, t.result.$allModels), ...ea(t.name, e, t.result[n]) }); + async function Uu() { + return typeof Gr.default.machine == "function" ? Gr.default.machine() : (await Qr("uname -m"))?.trim(); } - function Yp(e) { - let t = new ve(), r = (n, i) => t.getOrCreate(n, () => i.has(n) ? [n] : (i.add(n), e[n] ? e[n].needs.flatMap((o) => r(o, i)) : [n])); - return yt(e, (n) => ({ ...n, needs: r(n.name, /* @__PURE__ */ new Set()) })); + function $o(e) { + return e.startsWith("1."); } - function ea(e, t, r) { - return r ? yt(r, ({ needs: n, compute: i }, o) => ({ name: o, needs: n ? Object.keys(n).filter((s) => n[s]) : [], compute: Zp(t, o, i) })) : {}; + var zo = k(Ko()); + function ii(e) { + return (0, zo.default)(e, e, { fallback: X }); } - function Zp(e, t, r) { - let n = e?.[t]?.compute; - return n ? (i) => r({ ...i, [t]: n(i) }) : r; + var Ku = k(si()); + var $ = k(__require("path")); + var zu = k(si()); + var Lf = L("prisma:engines"); + function Yo() { + return $.default.join(__dirname, "../"); } - function ra(e, t) { - if (!t) return e; - let r = { ...e }; - for (let n of Object.values(t)) if (e[n.name]) for (let i of n.needs) r[i] = true; - return r; + var Nf = "libquery-engine"; + $.default.join(__dirname, "../query-engine-darwin"); + $.default.join(__dirname, "../query-engine-darwin-arm64"); + $.default.join(__dirname, "../query-engine-debian-openssl-1.0.x"); + $.default.join(__dirname, "../query-engine-debian-openssl-1.1.x"); + $.default.join(__dirname, "../query-engine-debian-openssl-3.0.x"); + $.default.join(__dirname, "../query-engine-linux-static-x64"); + $.default.join(__dirname, "../query-engine-linux-static-arm64"); + $.default.join(__dirname, "../query-engine-rhel-openssl-1.0.x"); + $.default.join(__dirname, "../query-engine-rhel-openssl-1.1.x"); + $.default.join(__dirname, "../query-engine-rhel-openssl-3.0.x"); + $.default.join(__dirname, "../libquery_engine-darwin.dylib.node"); + $.default.join(__dirname, "../libquery_engine-darwin-arm64.dylib.node"); + $.default.join(__dirname, "../libquery_engine-debian-openssl-1.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-debian-openssl-1.1.x.so.node"); + $.default.join(__dirname, "../libquery_engine-debian-openssl-3.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-linux-arm64-openssl-1.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-linux-arm64-openssl-1.1.x.so.node"); + $.default.join(__dirname, "../libquery_engine-linux-arm64-openssl-3.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-linux-musl.so.node"); + $.default.join(__dirname, "../libquery_engine-linux-musl-openssl-3.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-rhel-openssl-1.0.x.so.node"); + $.default.join(__dirname, "../libquery_engine-rhel-openssl-1.1.x.so.node"); + $.default.join(__dirname, "../libquery_engine-rhel-openssl-3.0.x.so.node"); + $.default.join(__dirname, "../query_engine-windows.dll.node"); + var ai = k(__require("fs")); + var Zo = L("chmodPlusX"); + function li(e) { + if (process.platform === "win32") return; + let t = ai.default.statSync(e), r = t.mode | 64 | 8 | 1; + if (t.mode === r) { + Zo(`Execution permissions of ${e} are fine`); + return; + } + let n = r.toString(8).slice(-3); + Zo(`Have to call chmodPlusX on ${e}`), ai.default.chmodSync(e, n); } - function na(e, t) { - if (!t) return e; - let r = { ...e }; - for (let n of Object.values(t)) if (!e[n.name]) for (let i of n.needs) delete r[i]; - return r; + function ui(e) { + let t = e.e, r = (a) => `Prisma cannot find the required \`${a}\` system library in your system`, n = t.message.includes("cannot open shared object file"), i = `Please refer to the documentation about Prisma's system requirements: ${ii("https://pris.ly/d/system-requirements")}`, o = `Unable to require(\`${Oe(e.id)}\`).`, s = mt({ message: t.message, code: t.code }).with({ code: "ENOENT" }, () => "File does not exist.").when(({ message: a }) => n && a.includes("libz"), () => `${r("libz")}. Please install it and try again.`).when(({ message: a }) => n && a.includes("libgcc_s"), () => `${r("libgcc_s")}. Please install it and try again.`).when(({ message: a }) => n && a.includes("libssl"), () => { + let a = e.platformInfo.libssl ? `openssl-${e.platformInfo.libssl}` : "openssl"; + return `${r("libssl")}. Please install ${a} and try again.`; + }).when(({ message: a }) => a.includes("GLIBC"), () => `Prisma has detected an incompatible version of the \`glibc\` C standard library installed in your system. This probably means your system may be too old to run Prisma. ${i}`).when(({ message: a }) => e.platformInfo.platform === "linux" && a.includes("symbol not found"), () => `The Prisma engines are not compatible with your system ${e.platformInfo.originalDistro} on (${e.platformInfo.archFromUname}) which uses the \`${e.platformInfo.binaryTarget}\` binaryTarget by default. ${i}`).otherwise(() => `The Prisma engines do not seem to be compatible with your system. ${i}`); + return `${o} +${s} + +Details: ${t.message}`; } - var xn = class { - constructor(t, r) { - this.extension = t; - this.previous = r; - this.computedFieldsCache = new ve(); - this.modelExtensionsCache = new ve(); - this.queryCallbacksCache = new ve(); - this.clientExtensions = pr(() => this.extension.client ? { ...this.previous?.getAllClientExtensions(), ...this.extension.client } : this.previous?.getAllClientExtensions()); - this.batchCallbacks = pr(() => { - let t2 = this.previous?.getAllBatchQueryCallbacks() ?? [], r2 = this.extension.query?.$__internalBatch; - return r2 ? t2.concat(r2) : t2; - }); - } - getAllComputedFields(t) { - return this.computedFieldsCache.getOrCreate(t, () => ta(this.previous?.getAllComputedFields(t), this.extension, t)); - } - getAllClientExtensions() { - return this.clientExtensions.get(); - } - getAllModelExtensions(t) { - return this.modelExtensionsCache.getOrCreate(t, () => { - let r = Te(t); - return !this.extension.model || !(this.extension.model[r] || this.extension.model.$allModels) ? this.previous?.getAllModelExtensions(t) : { ...this.previous?.getAllModelExtensions(t), ...this.extension.model.$allModels, ...this.extension.model[r] }; - }); - } - getAllQueryCallbacks(t, r) { - return this.queryCallbacksCache.getOrCreate(`${t}:${r}`, () => { - let n = this.previous?.getAllQueryCallbacks(t, r) ?? [], i = [], o = this.extension.query; - return !o || !(o[t] || o.$allModels || o[r] || o.$allOperations) ? n : (o[t] !== void 0 && (o[t][r] !== void 0 && i.push(o[t][r]), o[t].$allOperations !== void 0 && i.push(o[t].$allOperations)), t !== "$none" && o.$allModels !== void 0 && (o.$allModels[r] !== void 0 && i.push(o.$allModels[r]), o.$allModels.$allOperations !== void 0 && i.push(o.$allModels.$allOperations)), o[r] !== void 0 && i.push(o[r]), o.$allOperations !== void 0 && i.push(o.$allOperations), n.concat(i)); - }); - } - getAllBatchQueryCallbacks() { - return this.batchCallbacks.get(); - } - }; - var kt = class e { - constructor(t) { - this.head = t; - } - static empty() { - return new e(); - } - static single(t) { - return new e(new xn(t)); - } - isEmpty() { - return this.head === void 0; - } - append(t) { - return new e(new xn(t, this.head)); - } - getAllComputedFields(t) { - return this.head?.getAllComputedFields(t); - } - getAllClientExtensions() { - return this.head?.getAllClientExtensions(); - } - getAllModelExtensions(t) { - return this.head?.getAllModelExtensions(t); - } - getAllQueryCallbacks(t, r) { - return this.head?.getAllQueryCallbacks(t, r) ?? []; + var di = k(ts()); + var zr = k(__require("fs")); + var ht = k(__require("path")); + function rs(e) { + let t = e.ignoreProcessEnv ? {} : process.env, r = (n) => n.match(/(.?\${(?:[a-zA-Z0-9_]+)?})/g)?.reduce(function(o, s) { + let a = /(.?)\${([a-zA-Z0-9_]+)?}/g.exec(s); + if (!a) return o; + let l = a[1], u, c; + if (l === "\\") c = a[0], u = c.replace("\\$", "$"); + else { + let p = a[2]; + c = a[0].substring(l.length), u = Object.hasOwnProperty.call(t, p) ? t[p] : e.parsed[p] || "", u = r(u); + } + return o.replace(c, u); + }, n) ?? n; + for (let n in e.parsed) { + let i = Object.hasOwnProperty.call(t, n) ? t[n] : e.parsed[n]; + e.parsed[n] = r(i); } - getAllBatchQueryCallbacks() { - return this.head?.getAllBatchQueryCallbacks() ?? []; + for (let n in e.parsed) t[n] = e.parsed[n]; + return e; + } + var pi = L("prisma:tryLoadEnv"); + function zt({ rootEnvPath: e, schemaEnvPath: t }, r = { conflictCheck: "none" }) { + let n = ns(e); + r.conflictCheck !== "none" && sc(n, t, r.conflictCheck); + let i = null; + return is(n?.path, t) || (i = ns(t)), !n && !i && pi("No Environment variables loaded"), i?.dotenvResult.error ? console.error(ce(H("Schema Env Error: ")) + i.dotenvResult.error) : { message: [n?.message, i?.message].filter(Boolean).join(` +`), parsed: { ...n?.dotenvResult?.parsed, ...i?.dotenvResult?.parsed } }; + } + function sc(e, t, r) { + let n = e?.dotenvResult.parsed, i = !is(e?.path, t); + if (n && t && i && zr.default.existsSync(t)) { + let o = di.default.parse(zr.default.readFileSync(t)), s = []; + for (let a in o) n[a] === o[a] && s.push(a); + if (s.length > 0) { + let a = ht.default.relative(process.cwd(), e.path), l = ht.default.relative(process.cwd(), t); + if (r === "error") { + let u = `There is a conflict between env var${s.length > 1 ? "s" : ""} in ${X(a)} and ${X(l)} +Conflicting env vars: +${s.map((c) => ` ${H(c)}`).join(` +`)} + +We suggest to move the contents of ${X(l)} to ${X(a)} to consolidate your env vars. +`; + throw new Error(u); + } else if (r === "warn") { + let u = `Conflict for env var${s.length > 1 ? "s" : ""} ${s.map((c) => H(c)).join(", ")} in ${X(a)} and ${X(l)} +Env vars from ${X(l)} overwrite the ones from ${X(a)} + `; + console.warn(`${ke("warn(prisma)")} ${u}`); + } + } } - }; - var ia = Symbol(); - var dr = class { + } + function ns(e) { + if (ac(e)) { + pi(`Environment variables loaded from ${e}`); + let t = di.default.config({ path: e, debug: process.env.DOTENV_CONFIG_DEBUG ? true : void 0 }); + return { dotenvResult: rs(t), message: Oe(`Environment variables loaded from ${ht.default.relative(process.cwd(), e)}`), path: e }; + } else pi(`Environment variables not found at ${e}`); + return null; + } + function is(e, t) { + return e && t && ht.default.resolve(e) === ht.default.resolve(t); + } + function ac(e) { + return !!(e && zr.default.existsSync(e)); + } + var os = "library"; + function Yt(e) { + let t = lc(); + return t || (e?.config.engineType === "library" ? "library" : e?.config.engineType === "binary" ? "binary" : os); + } + function lc() { + let e = process.env.PRISMA_CLIENT_ENGINE_TYPE; + return e === "library" ? "library" : e === "binary" ? "binary" : void 0; + } + var Je; + ((t) => { + let e; + ((E) => (E.findUnique = "findUnique", E.findUniqueOrThrow = "findUniqueOrThrow", E.findFirst = "findFirst", E.findFirstOrThrow = "findFirstOrThrow", E.findMany = "findMany", E.create = "create", E.createMany = "createMany", E.createManyAndReturn = "createManyAndReturn", E.update = "update", E.updateMany = "updateMany", E.upsert = "upsert", E.delete = "delete", E.deleteMany = "deleteMany", E.groupBy = "groupBy", E.count = "count", E.aggregate = "aggregate", E.findRaw = "findRaw", E.aggregateRaw = "aggregateRaw"))(e = t.ModelAction ||= {}); + })(Je ||= {}); + var Zt = k(__require("path")); + function mi(e) { + return Zt.default.sep === Zt.default.posix.sep ? e : e.split(Zt.default.sep).join(Zt.default.posix.sep); + } + var ps = k(fi()); + function hi(e) { + return String(new gi(e)); + } + var gi = class { constructor(t) { - if (t !== ia) throw new Error("Skip instance can not be constructed directly"); + this.config = t; } - ifUndefined(t) { - return t === void 0 ? Pn : t; + toString() { + let { config: t } = this, r = t.provider.fromEnvVar ? `env("${t.provider.fromEnvVar}")` : t.provider.value, n = JSON.parse(JSON.stringify({ provider: r, binaryTargets: cc(t.binaryTargets) })); + return `generator ${t.name} { +${(0, ps.default)(pc(n), 2)} +}`; } }; - var Pn = new dr(ia); - function Re(e) { - return e instanceof dr; + function cc(e) { + let t; + if (e.length > 0) { + let r = e.find((n) => n.fromEnvVar !== null); + r ? t = `env("${r.fromEnvVar}")` : t = e.map((n) => n.native ? "native" : n.value); + } else t = void 0; + return t; } - var Xp = { findUnique: "findUnique", findUniqueOrThrow: "findUniqueOrThrow", findFirst: "findFirst", findFirstOrThrow: "findFirstOrThrow", findMany: "findMany", count: "aggregate", create: "createOne", createMany: "createMany", createManyAndReturn: "createManyAndReturn", update: "updateOne", updateMany: "updateMany", upsert: "upsertOne", delete: "deleteOne", deleteMany: "deleteMany", executeRaw: "executeRaw", queryRaw: "queryRaw", aggregate: "aggregate", groupBy: "groupBy", runCommandRaw: "runCommandRaw", findRaw: "findRaw", aggregateRaw: "aggregateRaw" }; - var oa = "explicitly `undefined` values are not allowed"; - function vn({ modelName: e, action: t, args: r, runtimeDataModel: n, extensions: i = kt.empty(), callsite: o, clientMethod: s, errorFormat: a, clientVersion: l, previewFeatures: u, globalOmit: c }) { - let p = new Di({ runtimeDataModel: n, modelName: e, action: t, rootArgs: r, callsite: o, extensions: i, selectionPath: [], argumentPath: [], originalMethod: s, errorFormat: a, clientVersion: l, previewFeatures: u, globalOmit: c }); - return { modelName: e, action: Xp[t], query: mr(r, p) }; + function pc(e) { + let t = Object.keys(e).reduce((r, n) => Math.max(r, n.length), 0); + return Object.entries(e).map(([r, n]) => `${r.padEnd(t)} = ${dc(n)}`).join(` +`); } - function mr({ select: e, include: t, ...r } = {}, n) { - let i; - return n.isPreviewFeatureOn("omitApi") && (i = r.omit, delete r.omit), { arguments: aa(r, n), selection: ed(e, t, i, n) }; + function dc(e) { + return JSON.parse(JSON.stringify(e, (t, r) => Array.isArray(r) ? `[${r.map((n) => JSON.stringify(n)).join(", ")}]` : JSON.stringify(r))); } - function ed(e, t, r, n) { - return e ? (t ? n.throwValidationError({ kind: "MutuallyExclusiveFields", firstField: "include", secondField: "select", selectionPath: n.getSelectionPath() }) : r && n.isPreviewFeatureOn("omitApi") && n.throwValidationError({ kind: "MutuallyExclusiveFields", firstField: "omit", secondField: "select", selectionPath: n.getSelectionPath() }), id(e, n)) : td(n, t, r); + var er = {}; + Ut(er, { error: () => gc, info: () => fc, log: () => mc, query: () => hc, should: () => ds, tags: () => Xt, warn: () => yi }); + var Xt = { error: ce("prisma:error"), warn: ke("prisma:warn"), info: De("prisma:info"), query: rt("prisma:query") }; + var ds = { warn: () => !process.env.PRISMA_DISABLE_WARNINGS }; + function mc(...e) { + console.log(...e); } - function td(e, t, r) { - let n = {}; - return e.modelOrType && !e.isRawAction() && (n.$composites = true, n.$scalars = true), t && rd(n, t, e), e.isPreviewFeatureOn("omitApi") && nd(n, r, e), n; + function yi(e, ...t) { + ds.warn() && console.warn(`${Xt.warn} ${e}`, ...t); } - function rd(e, t, r) { - for (let [n, i] of Object.entries(t)) { - if (Re(i)) continue; - let o = r.nestSelection(n); - if (_i(i, o), i === false || i === void 0) { - e[n] = false; - continue; - } - let s = r.findField(n); - if (s && s.kind !== "object" && r.throwValidationError({ kind: "IncludeOnScalar", selectionPath: r.getSelectionPath().concat(n), outputType: r.getOutputTypeDescription() }), s) { - e[n] = mr(i === true ? {} : i, o); - continue; - } - if (i === true) { - e[n] = true; - continue; - } - e[n] = mr(i, o); - } + function fc(e, ...t) { + console.info(`${Xt.info} ${e}`, ...t); } - function nd(e, t, r) { - let n = r.getComputedFields(), i = { ...r.getGlobalOmit(), ...t }, o = na(i, n); - for (let [s, a] of Object.entries(o)) { - if (Re(a)) continue; - _i(a, r.nestSelection(s)); - let l = r.findField(s); - n?.[s] && !l || (e[s] = !a); - } + function gc(e, ...t) { + console.error(`${Xt.error} ${e}`, ...t); } - function id(e, t) { - let r = {}, n = t.getComputedFields(), i = ra(e, n); - for (let [o, s] of Object.entries(i)) { - if (Re(s)) continue; - let a = t.nestSelection(o); - _i(s, a); - let l = t.findField(o); - if (!(n?.[o] && !l)) { - if (s === false || s === void 0 || Re(s)) { - r[o] = false; - continue; - } - if (s === true) { - l?.kind === "object" ? r[o] = mr({}, a) : r[o] = true; - continue; - } - r[o] = mr(s, a); - } - } - return r; + function hc(e, ...t) { + console.log(`${Xt.query} ${e}`, ...t); } - function sa(e, t) { - if (e === null) return null; - if (typeof e == "string" || typeof e == "number" || typeof e == "boolean") return e; - if (typeof e == "bigint") return { $type: "BigInt", value: String(e) }; - if (Pt(e)) { - if (ln(e)) return { $type: "DateTime", value: e.toISOString() }; - t.throwValidationError({ kind: "InvalidArgumentValue", selectionPath: t.getSelectionPath(), argumentPath: t.getArgumentPath(), argument: { name: t.getArgumentName(), typeNames: ["Date"] }, underlyingError: "Provided Date object is invalid" }); - } - if (It(e)) return { $type: "FieldRef", value: { _ref: e.name, _container: e.modelName } }; - if (Array.isArray(e)) return od(e, t); - if (ArrayBuffer.isView(e)) return { $type: "Bytes", value: Buffer.from(e).toString("base64") }; - if (sd(e)) return e.values; - if (vt(e)) return { $type: "Decimal", value: e.toFixed() }; - if (e instanceof Me) { - if (e !== yn.instances[e._getName()]) throw new Error("Invalid ObjectEnumValue"); - return { $type: "Enum", value: e._getName() }; - } - if (ad(e)) return e.toJSON(); - if (typeof e == "object") return aa(e, t); - t.throwValidationError({ kind: "InvalidArgumentValue", selectionPath: t.getSelectionPath(), argumentPath: t.getArgumentPath(), argument: { name: t.getArgumentName(), typeNames: [] }, underlyingError: `We could not serialize ${Object.prototype.toString.call(e)} value. Serialize the object to JSON or implement a ".toJSON()" method on it` }); + function Yr(e, t) { + if (!e) throw new Error(`${t}. This should never happen. If you see this error, please, open an issue at https://pris.ly/prisma-prisma-bug-report`); } - function aa(e, t) { - if (e.$type) return { $type: "Raw", value: e }; + function Fe(e, t) { + throw new Error(t); + } + function Ei(e, t) { + return Object.prototype.hasOwnProperty.call(e, t); + } + var wi = (e, t) => e.reduce((r, n) => (r[t(n)] = n, r), {}); + function yt(e, t) { let r = {}; - for (let n in e) { - let i = e[n], o = t.nestArgument(n); - Re(i) || (i !== void 0 ? r[n] = sa(i, o) : t.isPreviewFeatureOn("strictUndefinedChecks") && t.throwValidationError({ kind: "InvalidArgumentValue", argumentPath: o.getArgumentPath(), selectionPath: t.getSelectionPath(), argument: { name: t.getArgumentName(), typeNames: [] }, underlyingError: oa })); - } + for (let n of Object.keys(e)) r[n] = t(e[n], n); return r; } - function od(e, t) { - let r = []; - for (let n = 0; n < e.length; n++) { - let i = t.nestArgument(String(n)), o = e[n]; - if (o === void 0 || Re(o)) { - let s = o === void 0 ? "undefined" : "Prisma.skip"; - t.throwValidationError({ kind: "InvalidArgumentValue", selectionPath: i.getSelectionPath(), argumentPath: i.getArgumentPath(), argument: { name: `${t.getArgumentName()}[${n}]`, typeNames: [] }, underlyingError: `Can not use \`${s}\` value within array. Use \`null\` or filter out \`${s}\` values` }); - } - r.push(sa(o, i)); - } + function xi(e, t) { + if (e.length === 0) return; + let r = e[0]; + for (let n = 1; n < e.length; n++) t(r, e[n]) < 0 && (r = e[n]); return r; } - function sd(e) { - return typeof e == "object" && e !== null && e.__prismaRawParameters__ === true; - } - function ad(e) { - return typeof e == "object" && e !== null && typeof e.toJSON == "function"; - } - function _i(e, t) { - e === void 0 && t.isPreviewFeatureOn("strictUndefinedChecks") && t.throwValidationError({ kind: "InvalidSelectionValue", selectionPath: t.getSelectionPath(), underlyingError: oa }); + function w(e, t) { + Object.defineProperty(e, "name", { value: t, configurable: true }); } - var Di = class e { - constructor(t) { - this.params = t; - this.params.modelName && (this.modelOrType = this.params.runtimeDataModel.models[this.params.modelName] ?? this.params.runtimeDataModel.types[this.params.modelName]); - } - throwValidationError(t) { - wn({ errors: [t], originalMethod: this.params.originalMethod, args: this.params.rootArgs ?? {}, callsite: this.params.callsite, errorFormat: this.params.errorFormat, clientVersion: this.params.clientVersion, globalOmit: this.params.globalOmit }); + var ys = /* @__PURE__ */ new Set(); + var tr = (e, t, ...r) => { + ys.has(e) || (ys.add(e), yi(t, ...r)); + }; + var V = class extends Error { + constructor(t, { code: r, clientVersion: n, meta: i, batchRequestIdx: o }) { + super(t), this.name = "PrismaClientKnownRequestError", this.code = r, this.clientVersion = n, this.meta = i, Object.defineProperty(this, "batchRequestIdx", { value: o, enumerable: false, writable: true }); } - getSelectionPath() { - return this.params.selectionPath; + get [Symbol.toStringTag]() { + return "PrismaClientKnownRequestError"; } - getArgumentPath() { - return this.params.argumentPath; + }; + w(V, "PrismaClientKnownRequestError"); + var Le = class extends V { + constructor(t, r) { + super(t, { code: "P2025", clientVersion: r }), this.name = "NotFoundError"; } - getArgumentName() { - return this.params.argumentPath[this.params.argumentPath.length - 1]; + }; + w(Le, "NotFoundError"); + var R = class e extends Error { + constructor(t, r, n) { + super(t), this.name = "PrismaClientInitializationError", this.clientVersion = r, this.errorCode = n, Error.captureStackTrace(e); } - getOutputTypeDescription() { - if (!(!this.params.modelName || !this.modelOrType)) return { name: this.params.modelName, fields: this.modelOrType.fields.map((t) => ({ name: t.name, typeName: "boolean", isRelation: t.kind === "object" })) }; + get [Symbol.toStringTag]() { + return "PrismaClientInitializationError"; } - isRawAction() { - return ["executeRaw", "queryRaw", "runCommandRaw", "findRaw", "aggregateRaw"].includes(this.params.action); + }; + w(R, "PrismaClientInitializationError"); + var le = class extends Error { + constructor(t, r) { + super(t), this.name = "PrismaClientRustPanicError", this.clientVersion = r; } - isPreviewFeatureOn(t) { - return this.params.previewFeatures.includes(t); + get [Symbol.toStringTag]() { + return "PrismaClientRustPanicError"; } - getComputedFields() { - if (this.params.modelName) return this.params.extensions.getAllComputedFields(this.params.modelName); + }; + w(le, "PrismaClientRustPanicError"); + var B = class extends Error { + constructor(t, { clientVersion: r, batchRequestIdx: n }) { + super(t), this.name = "PrismaClientUnknownRequestError", this.clientVersion = r, Object.defineProperty(this, "batchRequestIdx", { value: n, writable: true, enumerable: false }); } - findField(t) { - return this.modelOrType?.fields.find((r) => r.name === t); + get [Symbol.toStringTag]() { + return "PrismaClientUnknownRequestError"; } - nestSelection(t) { - let r = this.findField(t), n = r?.kind === "object" ? r.type : void 0; - return new e({ ...this.params, modelName: n, selectionPath: this.params.selectionPath.concat(t) }); + }; + w(B, "PrismaClientUnknownRequestError"); + var J = class extends Error { + constructor(r, { clientVersion: n }) { + super(r); + this.name = "PrismaClientValidationError"; + this.clientVersion = n; } - getGlobalOmit() { - return this.params.modelName && this.shouldApplyGlobalOmit() ? this.params.globalOmit?.[xt(this.params.modelName)] ?? {} : {}; + get [Symbol.toStringTag]() { + return "PrismaClientValidationError"; } - shouldApplyGlobalOmit() { - switch (this.params.action) { - case "findFirst": - case "findFirstOrThrow": - case "findUniqueOrThrow": - case "findMany": - case "upsert": - case "findUnique": - case "createManyAndReturn": - case "create": - case "update": - case "delete": - return true; - case "executeRaw": - case "aggregateRaw": - case "runCommandRaw": - case "findRaw": - case "createMany": - case "deleteMany": - case "groupBy": - case "updateMany": - case "count": - case "aggregate": - case "queryRaw": - return false; - default: - Fe(this.params.action, "Unknown action"); + }; + w(J, "PrismaClientValidationError"); + var bt = 9e15; + var ze = 1e9; + var Pi = "0123456789abcdef"; + var tn = "2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058"; + var rn = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789"; + var vi = { precision: 20, rounding: 4, modulo: 1, toExpNeg: -7, toExpPos: 21, minE: -bt, maxE: bt, crypto: false }; + var xs; + var Ne; + var x = true; + var on = "[DecimalError] "; + var Ke = on + "Invalid argument: "; + var Ps = on + "Precision limit exceeded"; + var vs = on + "crypto unavailable"; + var Ts = "[object Decimal]"; + var ee = Math.floor; + var G = Math.pow; + var bc = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i; + var Ec = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i; + var wc = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i; + var Rs = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i; + var ge = 1e7; + var b = 7; + var xc = 9007199254740991; + var Pc = tn.length - 1; + var Ti = rn.length - 1; + var m = { toStringTag: Ts }; + m.absoluteValue = m.abs = function() { + var e = new this.constructor(this); + return e.s < 0 && (e.s = 1), y(e); + }; + m.ceil = function() { + return y(new this.constructor(this), this.e + 1, 2); + }; + m.clampedTo = m.clamp = function(e, t) { + var r, n = this, i = n.constructor; + if (e = new i(e), t = new i(t), !e.s || !t.s) return new i(NaN); + if (e.gt(t)) throw Error(Ke + t); + return r = n.cmp(e), r < 0 ? e : n.cmp(t) > 0 ? t : new i(n); + }; + m.comparedTo = m.cmp = function(e) { + var t, r, n, i, o = this, s = o.d, a = (e = new o.constructor(e)).d, l = o.s, u = e.s; + if (!s || !a) return !l || !u ? NaN : l !== u ? l : s === a ? 0 : !s ^ l < 0 ? 1 : -1; + if (!s[0] || !a[0]) return s[0] ? l : a[0] ? -u : 0; + if (l !== u) return l; + if (o.e !== e.e) return o.e > e.e ^ l < 0 ? 1 : -1; + for (n = s.length, i = a.length, t = 0, r = n < i ? n : i; t < r; ++t) if (s[t] !== a[t]) return s[t] > a[t] ^ l < 0 ? 1 : -1; + return n === i ? 0 : n > i ^ l < 0 ? 1 : -1; + }; + m.cosine = m.cos = function() { + var e, t, r = this, n = r.constructor; + return r.d ? r.d[0] ? (e = n.precision, t = n.rounding, n.precision = e + Math.max(r.e, r.sd()) + b, n.rounding = 1, r = vc(n, Os(n, r)), n.precision = e, n.rounding = t, y(Ne == 2 || Ne == 3 ? r.neg() : r, e, t, true)) : new n(1) : new n(NaN); + }; + m.cubeRoot = m.cbrt = function() { + var e, t, r, n, i, o, s, a, l, u, c = this, p = c.constructor; + if (!c.isFinite() || c.isZero()) return new p(c); + for (x = false, o = c.s * G(c.s * c, 1 / 3), !o || Math.abs(o) == 1 / 0 ? (r = K(c.d), e = c.e, (o = (e - r.length + 1) % 3) && (r += o == 1 || o == -2 ? "0" : "00"), o = G(r, 1 / 3), e = ee((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)), o == 1 / 0 ? r = "5e" + e : (r = o.toExponential(), r = r.slice(0, r.indexOf("e") + 1) + e), n = new p(r), n.s = c.s) : n = new p(o.toString()), s = (e = p.precision) + 3; ; ) if (a = n, l = a.times(a).times(a), u = l.plus(c), n = N(u.plus(c).times(a), u.plus(l), s + 2, 1), K(a.d).slice(0, s) === (r = K(n.d)).slice(0, s)) if (r = r.slice(s - 3, s + 1), r == "9999" || !i && r == "4999") { + if (!i && (y(a, e + 1, 0), a.times(a).times(a).eq(c))) { + n = a; + break; } + s += 4, i = 1; + } else { + (!+r || !+r.slice(1) && r.charAt(0) == "5") && (y(n, e + 1, 1), t = !n.times(n).times(n).eq(c)); + break; } - nestArgument(t) { - return new e({ ...this.params, argumentPath: this.params.argumentPath.concat(t) }); + return x = true, y(n, e, p.rounding, t); + }; + m.decimalPlaces = m.dp = function() { + var e, t = this.d, r = NaN; + if (t) { + if (e = t.length - 1, r = (e - ee(this.e / b)) * b, e = t[e], e) for (; e % 10 == 0; e /= 10) r--; + r < 0 && (r = 0); } + return r; }; - var Dt = class { - constructor(t) { - this._engine = t; + m.dividedBy = m.div = function(e) { + return N(this, new this.constructor(e)); + }; + m.dividedToIntegerBy = m.divToInt = function(e) { + var t = this, r = t.constructor; + return y(N(t, new r(e), 0, 1, 1), r.precision, r.rounding); + }; + m.equals = m.eq = function(e) { + return this.cmp(e) === 0; + }; + m.floor = function() { + return y(new this.constructor(this), this.e + 1, 3); + }; + m.greaterThan = m.gt = function(e) { + return this.cmp(e) > 0; + }; + m.greaterThanOrEqualTo = m.gte = function(e) { + var t = this.cmp(e); + return t == 1 || t === 0; + }; + m.hyperbolicCosine = m.cosh = function() { + var e, t, r, n, i, o = this, s = o.constructor, a = new s(1); + if (!o.isFinite()) return new s(o.s ? 1 / 0 : NaN); + if (o.isZero()) return a; + r = s.precision, n = s.rounding, s.precision = r + Math.max(o.e, o.sd()) + 4, s.rounding = 1, i = o.d.length, i < 32 ? (e = Math.ceil(i / 3), t = (1 / an(4, e)).toString()) : (e = 16, t = "2.3283064365386962890625e-10"), o = Et(s, 1, o.times(t), new s(1), true); + for (var l, u = e, c = new s(8); u--; ) l = o.times(o), o = a.minus(l.times(c.minus(l.times(c)))); + return y(o, s.precision = r, s.rounding = n, true); + }; + m.hyperbolicSine = m.sinh = function() { + var e, t, r, n, i = this, o = i.constructor; + if (!i.isFinite() || i.isZero()) return new o(i); + if (t = o.precision, r = o.rounding, o.precision = t + Math.max(i.e, i.sd()) + 4, o.rounding = 1, n = i.d.length, n < 3) i = Et(o, 2, i, i, true); + else { + e = 1.4 * Math.sqrt(n), e = e > 16 ? 16 : e | 0, i = i.times(1 / an(5, e)), i = Et(o, 2, i, i, true); + for (var s, a = new o(5), l = new o(16), u = new o(20); e--; ) s = i.times(i), i = i.times(a.plus(s.times(l.times(s).plus(u)))); } - prometheus(t) { - return this._engine.metrics({ format: "prometheus", ...t }); + return o.precision = t, o.rounding = r, y(i, t, r, true); + }; + m.hyperbolicTangent = m.tanh = function() { + var e, t, r = this, n = r.constructor; + return r.isFinite() ? r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + 7, n.rounding = 1, N(r.sinh(), r.cosh(), n.precision = e, n.rounding = t)) : new n(r.s); + }; + m.inverseCosine = m.acos = function() { + var e, t = this, r = t.constructor, n = t.abs().cmp(1), i = r.precision, o = r.rounding; + return n !== -1 ? n === 0 ? t.isNeg() ? fe(r, i, o) : new r(0) : new r(NaN) : t.isZero() ? fe(r, i + 4, o).times(0.5) : (r.precision = i + 6, r.rounding = 1, t = t.asin(), e = fe(r, i + 4, o).times(0.5), r.precision = i, r.rounding = o, e.minus(t)); + }; + m.inverseHyperbolicCosine = m.acosh = function() { + var e, t, r = this, n = r.constructor; + return r.lte(1) ? new n(r.eq(1) ? 0 : NaN) : r.isFinite() ? (e = n.precision, t = n.rounding, n.precision = e + Math.max(Math.abs(r.e), r.sd()) + 4, n.rounding = 1, x = false, r = r.times(r).minus(1).sqrt().plus(r), x = true, n.precision = e, n.rounding = t, r.ln()) : new n(r); + }; + m.inverseHyperbolicSine = m.asinh = function() { + var e, t, r = this, n = r.constructor; + return !r.isFinite() || r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + 2 * Math.max(Math.abs(r.e), r.sd()) + 6, n.rounding = 1, x = false, r = r.times(r).plus(1).sqrt().plus(r), x = true, n.precision = e, n.rounding = t, r.ln()); + }; + m.inverseHyperbolicTangent = m.atanh = function() { + var e, t, r, n, i = this, o = i.constructor; + return i.isFinite() ? i.e >= 0 ? new o(i.abs().eq(1) ? i.s / 0 : i.isZero() ? i : NaN) : (e = o.precision, t = o.rounding, n = i.sd(), Math.max(n, e) < 2 * -i.e - 1 ? y(new o(i), e, t, true) : (o.precision = r = n - i.e, i = N(i.plus(1), new o(1).minus(i), r + e, 1), o.precision = e + 4, o.rounding = 1, i = i.ln(), o.precision = e, o.rounding = t, i.times(0.5))) : new o(NaN); + }; + m.inverseSine = m.asin = function() { + var e, t, r, n, i = this, o = i.constructor; + return i.isZero() ? new o(i) : (t = i.abs().cmp(1), r = o.precision, n = o.rounding, t !== -1 ? t === 0 ? (e = fe(o, r + 4, n).times(0.5), e.s = i.s, e) : new o(NaN) : (o.precision = r + 6, o.rounding = 1, i = i.div(new o(1).minus(i.times(i)).sqrt().plus(1)).atan(), o.precision = r, o.rounding = n, i.times(2))); + }; + m.inverseTangent = m.atan = function() { + var e, t, r, n, i, o, s, a, l, u = this, c = u.constructor, p = c.precision, d = c.rounding; + if (u.isFinite()) { + if (u.isZero()) return new c(u); + if (u.abs().eq(1) && p + 4 <= Ti) return s = fe(c, p + 4, d).times(0.25), s.s = u.s, s; + } else { + if (!u.s) return new c(NaN); + if (p + 4 <= Ti) return s = fe(c, p + 4, d).times(0.5), s.s = u.s, s; } - json(t) { - return this._engine.metrics({ format: "json", ...t }); + for (c.precision = a = p + 10, c.rounding = 1, r = Math.min(28, a / b + 2 | 0), e = r; e; --e) u = u.div(u.times(u).plus(1).sqrt().plus(1)); + for (x = false, t = Math.ceil(a / b), n = 1, l = u.times(u), s = new c(u), i = u; e !== -1; ) if (i = i.times(l), o = s.minus(i.div(n += 2)), i = i.times(l), s = o.plus(i.div(n += 2)), s.d[t] !== void 0) for (e = t; s.d[e] === o.d[e] && e--; ) ; + return r && (s = s.times(2 << r - 1)), x = true, y(s, c.precision = p, c.rounding = d, true); + }; + m.isFinite = function() { + return !!this.d; + }; + m.isInteger = m.isInt = function() { + return !!this.d && ee(this.e / b) > this.d.length - 2; + }; + m.isNaN = function() { + return !this.s; + }; + m.isNegative = m.isNeg = function() { + return this.s < 0; + }; + m.isPositive = m.isPos = function() { + return this.s > 0; + }; + m.isZero = function() { + return !!this.d && this.d[0] === 0; + }; + m.lessThan = m.lt = function(e) { + return this.cmp(e) < 0; + }; + m.lessThanOrEqualTo = m.lte = function(e) { + return this.cmp(e) < 1; + }; + m.logarithm = m.log = function(e) { + var t, r, n, i, o, s, a, l, u = this, c = u.constructor, p = c.precision, d = c.rounding, f = 5; + if (e == null) e = new c(10), t = true; + else { + if (e = new c(e), r = e.d, e.s < 0 || !r || !r[0] || e.eq(1)) return new c(NaN); + t = e.eq(10); } + if (r = u.d, u.s < 0 || !r || !r[0] || u.eq(1)) return new c(r && !r[0] ? -1 / 0 : u.s != 1 ? NaN : r ? 0 : 1 / 0); + if (t) if (r.length > 1) o = true; + else { + for (i = r[0]; i % 10 === 0; ) i /= 10; + o = i !== 1; + } + if (x = false, a = p + f, s = He(u, a), n = t ? nn(c, a + 10) : He(e, a), l = N(s, n, a, 1), rr(l.d, i = p, d)) do + if (a += 10, s = He(u, a), n = t ? nn(c, a + 10) : He(e, a), l = N(s, n, a, 1), !o) { + +K(l.d).slice(i + 1, i + 15) + 1 == 1e14 && (l = y(l, p + 1, 0)); + break; + } + while (rr(l.d, i += 10, d)); + return x = true, y(l, p, d); }; - function la(e) { - return { models: Fi(e.models), enums: Fi(e.enums), types: Fi(e.types) }; - } - function Fi(e) { - let t = {}; - for (let { name: r, ...n } of e) t[r] = n; - return t; - } - function ua(e, t) { - let r = pr(() => ld(t)); - Object.defineProperty(e, "dmmf", { get: () => r.get() }); - } - function ld(e) { - return { datamodel: { models: Li(e.models), enums: Li(e.enums), types: Li(e.types) } }; - } - function Li(e) { - return Object.entries(e).map(([t, r]) => ({ name: t, ...r })); - } - var Ni = /* @__PURE__ */ new WeakMap(); - var Tn = "$$PrismaTypedSql"; - var Mi = class { - constructor(t, r) { - Ni.set(this, { sql: t, values: r }), Object.defineProperty(this, Tn, { value: Tn }); + m.minus = m.sub = function(e) { + var t, r, n, i, o, s, a, l, u, c, p, d, f = this, g = f.constructor; + if (e = new g(e), !f.d || !e.d) return !f.s || !e.s ? e = new g(NaN) : f.d ? e.s = -e.s : e = new g(e.d || f.s !== e.s ? f : NaN), e; + if (f.s != e.s) return e.s = -e.s, f.plus(e); + if (u = f.d, d = e.d, a = g.precision, l = g.rounding, !u[0] || !d[0]) { + if (d[0]) e.s = -e.s; + else if (u[0]) e = new g(f); + else return new g(l === 3 ? -0 : 0); + return x ? y(e, a, l) : e; } - get sql() { - return Ni.get(this).sql; + if (r = ee(e.e / b), c = ee(f.e / b), u = u.slice(), o = c - r, o) { + for (p = o < 0, p ? (t = u, o = -o, s = d.length) : (t = d, r = c, s = u.length), n = Math.max(Math.ceil(a / b), s) + 2, o > n && (o = n, t.length = 1), t.reverse(), n = o; n--; ) t.push(0); + t.reverse(); + } else { + for (n = u.length, s = d.length, p = n < s, p && (s = n), n = 0; n < s; n++) if (u[n] != d[n]) { + p = u[n] < d[n]; + break; + } + o = 0; } - get values() { - return Ni.get(this).values; + for (p && (t = u, u = d, d = t, e.s = -e.s), s = u.length, n = d.length - s; n > 0; --n) u[s++] = 0; + for (n = d.length; n > o; ) { + if (u[--n] < d[n]) { + for (i = n; i && u[--i] === 0; ) u[i] = ge - 1; + --u[i], u[n] += ge; + } + u[n] -= d[n]; } + for (; u[--s] === 0; ) u.pop(); + for (; u[0] === 0; u.shift()) --r; + return u[0] ? (e.d = u, e.e = sn(u, r), x ? y(e, a, l) : e) : new g(l === 3 ? -0 : 0); }; - function ca(e) { - return (...t) => new Mi(e, t); - } - function pa(e) { - return e != null && e[Tn] === Tn; - } - function fr(e) { - return { ok: false, error: e, map() { - return fr(e); - }, flatMap() { - return fr(e); - } }; - } - var $i = class { - constructor() { - this.registeredErrors = []; - } - consumeError(t) { - return this.registeredErrors[t]; - } - registerNewError(t) { - let r = 0; - for (; this.registeredErrors[r] !== void 0; ) r++; - return this.registeredErrors[r] = { error: t }, r; + m.modulo = m.mod = function(e) { + var t, r = this, n = r.constructor; + return e = new n(e), !r.d || !e.s || e.d && !e.d[0] ? new n(NaN) : !e.d || r.d && !r.d[0] ? y(new n(r), n.precision, n.rounding) : (x = false, n.modulo == 9 ? (t = N(r, e.abs(), 0, 3, 1), t.s *= e.s) : t = N(r, e, 0, n.modulo, 1), t = t.times(e), x = true, r.minus(t)); + }; + m.naturalExponential = m.exp = function() { + return Ri(this); + }; + m.naturalLogarithm = m.ln = function() { + return He(this); + }; + m.negated = m.neg = function() { + var e = new this.constructor(this); + return e.s = -e.s, y(e); + }; + m.plus = m.add = function(e) { + var t, r, n, i, o, s, a, l, u, c, p = this, d = p.constructor; + if (e = new d(e), !p.d || !e.d) return !p.s || !e.s ? e = new d(NaN) : p.d || (e = new d(e.d || p.s === e.s ? p : NaN)), e; + if (p.s != e.s) return e.s = -e.s, p.minus(e); + if (u = p.d, c = e.d, a = d.precision, l = d.rounding, !u[0] || !c[0]) return c[0] || (e = new d(p)), x ? y(e, a, l) : e; + if (o = ee(p.e / b), n = ee(e.e / b), u = u.slice(), i = o - n, i) { + for (i < 0 ? (r = u, i = -i, s = c.length) : (r = c, n = o, s = u.length), o = Math.ceil(a / b), s = o > s ? o + 1 : s + 1, i > s && (i = s, r.length = 1), r.reverse(); i--; ) r.push(0); + r.reverse(); } + for (s = u.length, i = c.length, s - i < 0 && (i = s, r = c, c = u, u = r), t = 0; i; ) t = (u[--i] = u[i] + c[i] + t) / ge | 0, u[i] %= ge; + for (t && (u.unshift(t), ++n), s = u.length; u[--s] == 0; ) u.pop(); + return e.d = u, e.e = sn(u, n), x ? y(e, a, l) : e; }; - var qi = (e) => { - let t = new $i(), r = Ce(t, e.transactionContext.bind(e)), n = { adapterName: e.adapterName, errorRegistry: t, queryRaw: Ce(t, e.queryRaw.bind(e)), executeRaw: Ce(t, e.executeRaw.bind(e)), provider: e.provider, transactionContext: async (...i) => (await r(...i)).map((s) => ud(t, s)) }; - return e.getConnectionInfo && (n.getConnectionInfo = pd(t, e.getConnectionInfo.bind(e))), n; + m.precision = m.sd = function(e) { + var t, r = this; + if (e !== void 0 && e !== !!e && e !== 1 && e !== 0) throw Error(Ke + e); + return r.d ? (t = Cs(r.d), e && r.e + 1 > t && (t = r.e + 1)) : t = NaN, t; }; - var ud = (e, t) => { - let r = Ce(e, t.startTransaction.bind(t)); - return { adapterName: t.adapterName, provider: t.provider, queryRaw: Ce(e, t.queryRaw.bind(t)), executeRaw: Ce(e, t.executeRaw.bind(t)), startTransaction: async (...n) => (await r(...n)).map((o) => cd(e, o)) }; + m.round = function() { + var e = this, t = e.constructor; + return y(new t(e), e.e + 1, t.rounding); }; - var cd = (e, t) => ({ adapterName: t.adapterName, provider: t.provider, options: t.options, queryRaw: Ce(e, t.queryRaw.bind(t)), executeRaw: Ce(e, t.executeRaw.bind(t)), commit: Ce(e, t.commit.bind(t)), rollback: Ce(e, t.rollback.bind(t)) }); - function Ce(e, t) { - return async (...r) => { - try { - return await t(...r); - } catch (n) { - let i = e.registerNewError(n); - return fr({ kind: "GenericJs", id: i }); - } - }; - } - function pd(e, t) { - return (...r) => { - try { - return t(...r); - } catch (n) { - let i = e.registerNewError(n); - return fr({ kind: "GenericJs", id: i }); - } - }; - } - var Wl = k(oi()); - var Hl = __require("async_hooks"); - var Kl = __require("events"); - var zl = k(__require("fs")); - var Fr = k(__require("path")); - var oe = class e { - constructor(t, r) { - if (t.length - 1 !== r.length) throw t.length === 0 ? new TypeError("Expected at least 1 string") : new TypeError(`Expected ${t.length} strings to have ${t.length - 1} values`); - let n = r.reduce((s, a) => s + (a instanceof e ? a.values.length : 1), 0); - this.values = new Array(n), this.strings = new Array(n + 1), this.strings[0] = t[0]; - let i = 0, o = 0; - for (; i < r.length; ) { - let s = r[i++], a = t[i]; - if (s instanceof e) { - this.strings[o] += s.strings[0]; - let l = 0; - for (; l < s.values.length; ) this.values[o++] = s.values[l++], this.strings[o] = s.strings[l]; - this.strings[o] += a; - } else this.values[o++] = s, this.strings[o] = a; + m.sine = m.sin = function() { + var e, t, r = this, n = r.constructor; + return r.isFinite() ? r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + Math.max(r.e, r.sd()) + b, n.rounding = 1, r = Rc(n, Os(n, r)), n.precision = e, n.rounding = t, y(Ne > 2 ? r.neg() : r, e, t, true)) : new n(NaN); + }; + m.squareRoot = m.sqrt = function() { + var e, t, r, n, i, o, s = this, a = s.d, l = s.e, u = s.s, c = s.constructor; + if (u !== 1 || !a || !a[0]) return new c(!u || u < 0 && (!a || a[0]) ? NaN : a ? s : 1 / 0); + for (x = false, u = Math.sqrt(+s), u == 0 || u == 1 / 0 ? (t = K(a), (t.length + l) % 2 == 0 && (t += "0"), u = Math.sqrt(t), l = ee((l + 1) / 2) - (l < 0 || l % 2), u == 1 / 0 ? t = "5e" + l : (t = u.toExponential(), t = t.slice(0, t.indexOf("e") + 1) + l), n = new c(t)) : n = new c(u.toString()), r = (l = c.precision) + 3; ; ) if (o = n, n = o.plus(N(s, o, r + 2, 1)).times(0.5), K(o.d).slice(0, r) === (t = K(n.d)).slice(0, r)) if (t = t.slice(r - 3, r + 1), t == "9999" || !i && t == "4999") { + if (!i && (y(o, l + 1, 0), o.times(o).eq(s))) { + n = o; + break; } + r += 4, i = 1; + } else { + (!+t || !+t.slice(1) && t.charAt(0) == "5") && (y(n, l + 1, 1), e = !n.times(n).eq(s)); + break; } - get sql() { - let t = this.strings.length, r = 1, n = this.strings[0]; - for (; r < t; ) n += `?${this.strings[r++]}`; - return n; + return x = true, y(n, l, c.rounding, e); + }; + m.tangent = m.tan = function() { + var e, t, r = this, n = r.constructor; + return r.isFinite() ? r.isZero() ? new n(r) : (e = n.precision, t = n.rounding, n.precision = e + 10, n.rounding = 1, r = r.sin(), r.s = 1, r = N(r, new n(1).minus(r.times(r)).sqrt(), e + 10, 0), n.precision = e, n.rounding = t, y(Ne == 2 || Ne == 4 ? r.neg() : r, e, t, true)) : new n(NaN); + }; + m.times = m.mul = function(e) { + var t, r, n, i, o, s, a, l, u, c = this, p = c.constructor, d = c.d, f = (e = new p(e)).d; + if (e.s *= c.s, !d || !d[0] || !f || !f[0]) return new p(!e.s || d && !d[0] && !f || f && !f[0] && !d ? NaN : !d || !f ? e.s / 0 : e.s * 0); + for (r = ee(c.e / b) + ee(e.e / b), l = d.length, u = f.length, l < u && (o = d, d = f, f = o, s = l, l = u, u = s), o = [], s = l + u, n = s; n--; ) o.push(0); + for (n = u; --n >= 0; ) { + for (t = 0, i = l + n; i > n; ) a = o[i] + f[n] * d[i - n - 1] + t, o[i--] = a % ge | 0, t = a / ge | 0; + o[i] = (o[i] + t) % ge | 0; } - get statement() { - let t = this.strings.length, r = 1, n = this.strings[0]; - for (; r < t; ) n += `:${r}${this.strings[r++]}`; - return n; + for (; !o[--s]; ) o.pop(); + return t ? ++r : o.shift(), e.d = o, e.e = sn(o, r), x ? y(e, p.precision, p.rounding) : e; + }; + m.toBinary = function(e, t) { + return Si(this, 2, e, t); + }; + m.toDecimalPlaces = m.toDP = function(e, t) { + var r = this, n = r.constructor; + return r = new n(r), e === void 0 ? r : (ie(e, 0, ze), t === void 0 ? t = n.rounding : ie(t, 0, 8), y(r, e + r.e + 1, t)); + }; + m.toExponential = function(e, t) { + var r, n = this, i = n.constructor; + return e === void 0 ? r = we(n, true) : (ie(e, 0, ze), t === void 0 ? t = i.rounding : ie(t, 0, 8), n = y(new i(n), e + 1, t), r = we(n, true, e + 1)), n.isNeg() && !n.isZero() ? "-" + r : r; + }; + m.toFixed = function(e, t) { + var r, n, i = this, o = i.constructor; + return e === void 0 ? r = we(i) : (ie(e, 0, ze), t === void 0 ? t = o.rounding : ie(t, 0, 8), n = y(new o(i), e + i.e + 1, t), r = we(n, false, e + n.e + 1)), i.isNeg() && !i.isZero() ? "-" + r : r; + }; + m.toFraction = function(e) { + var t, r, n, i, o, s, a, l, u, c, p, d, f = this, g = f.d, h = f.constructor; + if (!g) return new h(f); + if (u = r = new h(1), n = l = new h(0), t = new h(n), o = t.e = Cs(g) - f.e - 1, s = o % b, t.d[0] = G(10, s < 0 ? b + s : s), e == null) e = o > 0 ? t : u; + else { + if (a = new h(e), !a.isInt() || a.lt(u)) throw Error(Ke + a); + e = a.gt(t) ? o > 0 ? t : u : a; } - get text() { - let t = this.strings.length, r = 1, n = this.strings[0]; - for (; r < t; ) n += `$${r}${this.strings[r++]}`; - return n; + for (x = false, a = new h(K(g)), c = h.precision, h.precision = o = g.length * b * 2; p = N(a, t, 0, 1, 1), i = r.plus(p.times(n)), i.cmp(e) != 1; ) r = n, n = i, i = u, u = l.plus(p.times(i)), l = i, i = t, t = a.minus(p.times(i)), a = i; + return i = N(e.minus(r), n, 0, 1, 1), l = l.plus(i.times(u)), r = r.plus(i.times(n)), l.s = u.s = f.s, d = N(u, n, o, 1).minus(f).abs().cmp(N(l, r, o, 1).minus(f).abs()) < 1 ? [u, n] : [l, r], h.precision = c, x = true, d; + }; + m.toHexadecimal = m.toHex = function(e, t) { + return Si(this, 16, e, t); + }; + m.toNearest = function(e, t) { + var r = this, n = r.constructor; + if (r = new n(r), e == null) { + if (!r.d) return r; + e = new n(1), t = n.rounding; + } else { + if (e = new n(e), t === void 0 ? t = n.rounding : ie(t, 0, 8), !r.d) return e.s ? r : e; + if (!e.d) return e.s && (e.s = r.s), e; } - inspect() { - return { sql: this.sql, statement: this.statement, text: this.text, values: this.values }; + return e.d[0] ? (x = false, r = N(r, e, 0, t, 1).times(e), x = true, y(r)) : (e.s = r.s, r = e), r; + }; + m.toNumber = function() { + return +this; + }; + m.toOctal = function(e, t) { + return Si(this, 8, e, t); + }; + m.toPower = m.pow = function(e) { + var t, r, n, i, o, s, a = this, l = a.constructor, u = +(e = new l(e)); + if (!a.d || !e.d || !a.d[0] || !e.d[0]) return new l(G(+a, u)); + if (a = new l(a), a.eq(1)) return a; + if (n = l.precision, o = l.rounding, e.eq(1)) return y(a, n, o); + if (t = ee(e.e / b), t >= e.d.length - 1 && (r = u < 0 ? -u : u) <= xc) return i = Ss(l, a, r, n), e.s < 0 ? new l(1).div(i) : y(i, n, o); + if (s = a.s, s < 0) { + if (t < e.d.length - 1) return new l(NaN); + if (e.d[t] & 1 || (s = 1), a.e == 0 && a.d[0] == 1 && a.d.length == 1) return a.s = s, a; } + return r = G(+a, u), t = r == 0 || !isFinite(r) ? ee(u * (Math.log("0." + K(a.d)) / Math.LN10 + a.e + 1)) : new l(r + "").e, t > l.maxE + 1 || t < l.minE - 1 ? new l(t > 0 ? s / 0 : 0) : (x = false, l.rounding = a.s = 1, r = Math.min(12, (t + "").length), i = Ri(e.times(He(a, n + r)), n), i.d && (i = y(i, n + 5, 1), rr(i.d, n, o) && (t = n + 10, i = y(Ri(e.times(He(a, t + r)), t), t + 5, 1), +K(i.d).slice(n + 1, n + 15) + 1 == 1e14 && (i = y(i, n + 1, 0)))), i.s = s, x = true, l.rounding = o, y(i, n, o)); }; - function da(e, t = ",", r = "", n = "") { - if (e.length === 0) throw new TypeError("Expected `join([])` to be called with an array of multiple elements, but got an empty array"); - return new oe([r, ...Array(e.length - 1).fill(t), n], e); - } - function ji(e) { - return new oe([e], []); - } - var ma = ji(""); - function Vi(e, ...t) { - return new oe(e, t); - } - function gr(e) { - return { getKeys() { - return Object.keys(e); - }, getPropertyValue(t) { - return e[t]; - } }; - } - function re(e, t) { - return { getKeys() { - return [e]; - }, getPropertyValue() { - return t(); - } }; - } - function ot(e) { - let t = new ve(); - return { getKeys() { - return e.getKeys(); - }, getPropertyValue(r) { - return t.getOrCreate(r, () => e.getPropertyValue(r)); - }, getPropertyDescriptor(r) { - return e.getPropertyDescriptor?.(r); - } }; + m.toPrecision = function(e, t) { + var r, n = this, i = n.constructor; + return e === void 0 ? r = we(n, n.e <= i.toExpNeg || n.e >= i.toExpPos) : (ie(e, 1, ze), t === void 0 ? t = i.rounding : ie(t, 0, 8), n = y(new i(n), e, t), r = we(n, e <= n.e || n.e <= i.toExpNeg, e)), n.isNeg() && !n.isZero() ? "-" + r : r; + }; + m.toSignificantDigits = m.toSD = function(e, t) { + var r = this, n = r.constructor; + return e === void 0 ? (e = n.precision, t = n.rounding) : (ie(e, 1, ze), t === void 0 ? t = n.rounding : ie(t, 0, 8)), y(new n(r), e, t); + }; + m.toString = function() { + var e = this, t = e.constructor, r = we(e, e.e <= t.toExpNeg || e.e >= t.toExpPos); + return e.isNeg() && !e.isZero() ? "-" + r : r; + }; + m.truncated = m.trunc = function() { + return y(new this.constructor(this), this.e + 1, 1); + }; + m.valueOf = m.toJSON = function() { + var e = this, t = e.constructor, r = we(e, e.e <= t.toExpNeg || e.e >= t.toExpPos); + return e.isNeg() ? "-" + r : r; + }; + function K(e) { + var t, r, n, i = e.length - 1, o = "", s = e[0]; + if (i > 0) { + for (o += s, t = 1; t < i; t++) n = e[t] + "", r = b - n.length, r && (o += We(r)), o += n; + s = e[t], n = s + "", r = b - n.length, r && (o += We(r)); + } else if (s === 0) return "0"; + for (; s % 10 === 0; ) s /= 10; + return o + s; } - var Rn = { enumerable: true, configurable: true, writable: true }; - function Cn(e) { - let t = new Set(e); - return { getOwnPropertyDescriptor: () => Rn, has: (r, n) => t.has(n), set: (r, n, i) => t.add(n) && Reflect.set(r, n, i), ownKeys: () => [...t] }; + function ie(e, t, r) { + if (e !== ~~e || e < t || e > r) throw Error(Ke + e); } - var fa = Symbol.for("nodejs.util.inspect.custom"); - function Se(e, t) { - let r = dd(t), n = /* @__PURE__ */ new Set(), i = new Proxy(e, { get(o, s) { - if (n.has(s)) return o[s]; - let a = r.get(s); - return a ? a.getPropertyValue(s) : o[s]; - }, has(o, s) { - if (n.has(s)) return true; - let a = r.get(s); - return a ? a.has?.(s) ?? true : Reflect.has(o, s); - }, ownKeys(o) { - let s = ga(Reflect.ownKeys(o), r), a = ga(Array.from(r.keys()), r); - return [.../* @__PURE__ */ new Set([...s, ...a, ...n])]; - }, set(o, s, a) { - return r.get(s)?.getPropertyDescriptor?.(s)?.writable === false ? false : (n.add(s), Reflect.set(o, s, a)); - }, getOwnPropertyDescriptor(o, s) { - let a = Reflect.getOwnPropertyDescriptor(o, s); - if (a && !a.configurable) return a; - let l = r.get(s); - return l ? l.getPropertyDescriptor ? { ...Rn, ...l?.getPropertyDescriptor(s) } : Rn : a; - }, defineProperty(o, s, a) { - return n.add(s), Reflect.defineProperty(o, s, a); - } }); - return i[fa] = function() { - let o = { ...this }; - return delete o[fa], o; - }, i; + function rr(e, t, r, n) { + var i, o, s, a; + for (o = e[0]; o >= 10; o /= 10) --t; + return --t < 0 ? (t += b, i = 0) : (i = Math.ceil((t + 1) / b), t %= b), o = G(10, b - t), a = e[i] % o | 0, n == null ? t < 3 ? (t == 0 ? a = a / 100 | 0 : t == 1 && (a = a / 10 | 0), s = r < 4 && a == 99999 || r > 3 && a == 49999 || a == 5e4 || a == 0) : s = (r < 4 && a + 1 == o || r > 3 && a + 1 == o / 2) && (e[i + 1] / o / 100 | 0) == G(10, t - 2) - 1 || (a == o / 2 || a == 0) && (e[i + 1] / o / 100 | 0) == 0 : t < 4 ? (t == 0 ? a = a / 1e3 | 0 : t == 1 ? a = a / 100 | 0 : t == 2 && (a = a / 10 | 0), s = (n || r < 4) && a == 9999 || !n && r > 3 && a == 4999) : s = ((n || r < 4) && a + 1 == o || !n && r > 3 && a + 1 == o / 2) && (e[i + 1] / o / 1e3 | 0) == G(10, t - 3) - 1, s; } - function dd(e) { - let t = /* @__PURE__ */ new Map(); - for (let r of e) { - let n = r.getKeys(); - for (let i of n) t.set(i, r); + function en(e, t, r) { + for (var n, i = [0], o, s = 0, a = e.length; s < a; ) { + for (o = i.length; o--; ) i[o] *= t; + for (i[0] += Pi.indexOf(e.charAt(s++)), n = 0; n < i.length; n++) i[n] > r - 1 && (i[n + 1] === void 0 && (i[n + 1] = 0), i[n + 1] += i[n] / r | 0, i[n] %= r); } - return t; - } - function ga(e, t) { - return e.filter((r) => t.get(r)?.has?.(r) ?? true); - } - function _t(e) { - return { getKeys() { - return e; - }, has() { - return false; - }, getPropertyValue() { - } }; - } - function Ft(e, t) { - return { batch: e, transaction: t?.kind === "batch" ? { isolationLevel: t.options.isolationLevel } : void 0 }; - } - function ha(e) { - if (e === void 0) return ""; - let t = Ot(e); - return new Rt(0, { colors: fn }).write(t).toString(); - } - var md = "P2037"; - function st({ error: e, user_facing_error: t }, r, n) { - return t.error_code ? new V(fd(t, n), { code: t.error_code, clientVersion: r, meta: t.meta, batchRequestIdx: t.batch_request_idx }) : new B(e, { clientVersion: r, batchRequestIdx: t.batch_request_idx }); - } - function fd(e, t) { - let r = e.message; - return (t === "postgresql" || t === "postgres" || t === "mysql") && e.error_code === md && (r += ` -Prisma Accelerate has built-in connection pooling to prevent such errors: https://pris.ly/client/error-accelerate`), r; - } - var hr = ""; - function ya(e) { - var t = e.split(` -`); - return t.reduce(function(r, n) { - var i = yd(n) || Ed(n) || Pd(n) || Cd(n) || Td(n); - return i && r.push(i), r; - }, []); - } - var gd = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack||\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; - var hd = /\((\S*)(?::(\d+))(?::(\d+))\)/; - function yd(e) { - var t = gd.exec(e); - if (!t) return null; - var r = t[2] && t[2].indexOf("native") === 0, n = t[2] && t[2].indexOf("eval") === 0, i = hd.exec(t[2]); - return n && i != null && (t[2] = i[1], t[3] = i[2], t[4] = i[3]), { file: r ? null : t[2], methodName: t[1] || hr, arguments: r ? [t[2]] : [], lineNumber: t[3] ? +t[3] : null, column: t[4] ? +t[4] : null }; - } - var bd = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i; - function Ed(e) { - var t = bd.exec(e); - return t ? { file: t[2], methodName: t[1] || hr, arguments: [], lineNumber: +t[3], column: t[4] ? +t[4] : null } : null; - } - var wd = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i; - var xd = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; - function Pd(e) { - var t = wd.exec(e); - if (!t) return null; - var r = t[3] && t[3].indexOf(" > eval") > -1, n = xd.exec(t[3]); - return r && n != null && (t[3] = n[1], t[4] = n[2], t[5] = null), { file: t[3], methodName: t[1] || hr, arguments: t[2] ? t[2].split(",") : [], lineNumber: t[4] ? +t[4] : null, column: t[5] ? +t[5] : null }; - } - var vd = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i; - function Td(e) { - var t = vd.exec(e); - return t ? { file: t[3], methodName: t[1] || hr, arguments: [], lineNumber: +t[4], column: t[5] ? +t[5] : null } : null; + return i.reverse(); } - var Rd = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i; - function Cd(e) { - var t = Rd.exec(e); - return t ? { file: t[2], methodName: t[1] || hr, arguments: [], lineNumber: +t[3], column: t[4] ? +t[4] : null } : null; + function vc(e, t) { + var r, n, i; + if (t.isZero()) return t; + n = t.d.length, n < 32 ? (r = Math.ceil(n / 3), i = (1 / an(4, r)).toString()) : (r = 16, i = "2.3283064365386962890625e-10"), e.precision += r, t = Et(e, 1, t.times(i), new e(1)); + for (var o = r; o--; ) { + var s = t.times(t); + t = s.times(s).minus(s).times(8).plus(1); + } + return e.precision -= r, t; } - var Bi = class { - getLocation() { - return null; + var N = /* @__PURE__ */ function() { + function e(n, i, o) { + var s, a = 0, l = n.length; + for (n = n.slice(); l--; ) s = n[l] * i + a, n[l] = s % o | 0, a = s / o | 0; + return a && n.unshift(a), n; } - }; - var Ui = class { - constructor() { - this._error = new Error(); + function t(n, i, o, s) { + var a, l; + if (o != s) l = o > s ? 1 : -1; + else for (a = l = 0; a < o; a++) if (n[a] != i[a]) { + l = n[a] > i[a] ? 1 : -1; + break; + } + return l; } - getLocation() { - let t = this._error.stack; - if (!t) return null; - let n = ya(t).find((i) => { - if (!i.file) return false; - let o = mi(i.file); - return o !== "" && !o.includes("@prisma") && !o.includes("/packages/client/src/runtime/") && !o.endsWith("/runtime/binary.js") && !o.endsWith("/runtime/library.js") && !o.endsWith("/runtime/edge.js") && !o.endsWith("/runtime/edge-esm.js") && !o.startsWith("internal/") && !i.methodName.includes("new ") && !i.methodName.includes("getCallSite") && !i.methodName.includes("Proxy.") && i.methodName.split(".").length < 4; - }); - return !n || !n.file ? null : { fileName: n.file, lineNumber: n.lineNumber, columnNumber: n.column }; + function r(n, i, o, s) { + for (var a = 0; o--; ) n[o] -= a, a = n[o] < i[o] ? 1 : 0, n[o] = a * s + n[o] - i[o]; + for (; !n[0] && n.length > 1; ) n.shift(); } - }; - function Ze(e) { - return e === "minimal" ? typeof $EnabledCallSite == "function" && e !== "minimal" ? new $EnabledCallSite() : new Bi() : new Ui(); - } - var ba = { _avg: true, _count: true, _sum: true, _min: true, _max: true }; - function Lt(e = {}) { - let t = Ad(e); - return Object.entries(t).reduce((n, [i, o]) => (ba[i] !== void 0 ? n.select[i] = { select: o } : n[i] = o, n), { select: {} }); - } - function Ad(e = {}) { - return typeof e._count == "boolean" ? { ...e, _count: { _all: e._count } } : e; + return function(n, i, o, s, a, l) { + var u, c, p, d, f, g, h, O, T, S, C, E, me, ae, Bt, U, ne, Ie, z, dt, Lr = n.constructor, qn = n.s == i.s ? 1 : -1, Y = n.d, _ = i.d; + if (!Y || !Y[0] || !_ || !_[0]) return new Lr(!n.s || !i.s || (Y ? _ && Y[0] == _[0] : !_) ? NaN : Y && Y[0] == 0 || !_ ? qn * 0 : qn / 0); + for (l ? (f = 1, c = n.e - i.e) : (l = ge, f = b, c = ee(n.e / f) - ee(i.e / f)), z = _.length, ne = Y.length, T = new Lr(qn), S = T.d = [], p = 0; _[p] == (Y[p] || 0); p++) ; + if (_[p] > (Y[p] || 0) && c--, o == null ? (ae = o = Lr.precision, s = Lr.rounding) : a ? ae = o + (n.e - i.e) + 1 : ae = o, ae < 0) S.push(1), g = true; + else { + if (ae = ae / f + 2 | 0, p = 0, z == 1) { + for (d = 0, _ = _[0], ae++; (p < ne || d) && ae--; p++) Bt = d * l + (Y[p] || 0), S[p] = Bt / _ | 0, d = Bt % _ | 0; + g = d || p < ne; + } else { + for (d = l / (_[0] + 1) | 0, d > 1 && (_ = e(_, d, l), Y = e(Y, d, l), z = _.length, ne = Y.length), U = z, C = Y.slice(0, z), E = C.length; E < z; ) C[E++] = 0; + dt = _.slice(), dt.unshift(0), Ie = _[0], _[1] >= l / 2 && ++Ie; + do + d = 0, u = t(_, C, z, E), u < 0 ? (me = C[0], z != E && (me = me * l + (C[1] || 0)), d = me / Ie | 0, d > 1 ? (d >= l && (d = l - 1), h = e(_, d, l), O = h.length, E = C.length, u = t(h, C, O, E), u == 1 && (d--, r(h, z < O ? dt : _, O, l))) : (d == 0 && (u = d = 1), h = _.slice()), O = h.length, O < E && h.unshift(0), r(C, h, E, l), u == -1 && (E = C.length, u = t(_, C, z, E), u < 1 && (d++, r(C, z < E ? dt : _, E, l))), E = C.length) : u === 0 && (d++, C = [0]), S[p++] = d, u && C[0] ? C[E++] = Y[U] || 0 : (C = [Y[U]], E = 1); + while ((U++ < ne || C[0] !== void 0) && ae--); + g = C[0] !== void 0; + } + S[0] || S.shift(); + } + if (f == 1) T.e = c, xs = g; + else { + for (p = 1, d = S[0]; d >= 10; d /= 10) p++; + T.e = p + c * f - 1, y(T, a ? o + T.e + 1 : o, s, g); + } + return T; + }; + }(); + function y(e, t, r, n) { + var i, o, s, a, l, u, c, p, d, f = e.constructor; + e: if (t != null) { + if (p = e.d, !p) return e; + for (i = 1, a = p[0]; a >= 10; a /= 10) i++; + if (o = t - i, o < 0) o += b, s = t, c = p[d = 0], l = c / G(10, i - s - 1) % 10 | 0; + else if (d = Math.ceil((o + 1) / b), a = p.length, d >= a) if (n) { + for (; a++ <= d; ) p.push(0); + c = l = 0, i = 1, o %= b, s = o - b + 1; + } else break e; + else { + for (c = a = p[d], i = 1; a >= 10; a /= 10) i++; + o %= b, s = o - b + i, l = s < 0 ? 0 : c / G(10, i - s - 1) % 10 | 0; + } + if (n = n || t < 0 || p[d + 1] !== void 0 || (s < 0 ? c : c % G(10, i - s - 1)), u = r < 4 ? (l || n) && (r == 0 || r == (e.s < 0 ? 3 : 2)) : l > 5 || l == 5 && (r == 4 || n || r == 6 && (o > 0 ? s > 0 ? c / G(10, i - s) : 0 : p[d - 1]) % 10 & 1 || r == (e.s < 0 ? 8 : 7)), t < 1 || !p[0]) return p.length = 0, u ? (t -= e.e + 1, p[0] = G(10, (b - t % b) % b), e.e = -t || 0) : p[0] = e.e = 0, e; + if (o == 0 ? (p.length = d, a = 1, d--) : (p.length = d + 1, a = G(10, b - o), p[d] = s > 0 ? (c / G(10, i - s) % G(10, s) | 0) * a : 0), u) for (; ; ) if (d == 0) { + for (o = 1, s = p[0]; s >= 10; s /= 10) o++; + for (s = p[0] += a, a = 1; s >= 10; s /= 10) a++; + o != a && (e.e++, p[0] == ge && (p[0] = 1)); + break; + } else { + if (p[d] += a, p[d] != ge) break; + p[d--] = 0, a = 1; + } + for (o = p.length; p[--o] === 0; ) p.pop(); + } + return x && (e.e > f.maxE ? (e.d = null, e.e = NaN) : e.e < f.minE && (e.e = 0, e.d = [0])), e; } - function Sn(e = {}) { - return (t) => (typeof e._count == "boolean" && (t._count = t._count._all), t); + function we(e, t, r) { + if (!e.isFinite()) return Is(e); + var n, i = e.e, o = K(e.d), s = o.length; + return t ? (r && (n = r - s) > 0 ? o = o.charAt(0) + "." + o.slice(1) + We(n) : s > 1 && (o = o.charAt(0) + "." + o.slice(1)), o = o + (e.e < 0 ? "e" : "e+") + e.e) : i < 0 ? (o = "0." + We(-i - 1) + o, r && (n = r - s) > 0 && (o += We(n))) : i >= s ? (o += We(i + 1 - s), r && (n = r - i - 1) > 0 && (o = o + "." + We(n))) : ((n = i + 1) < s && (o = o.slice(0, n) + "." + o.slice(n)), r && (n = r - s) > 0 && (i + 1 === s && (o += "."), o += We(n))), o; } - function Ea(e, t) { - let r = Sn(e); - return t({ action: "aggregate", unpacker: r, argsMapper: Lt })(e); + function sn(e, t) { + var r = e[0]; + for (t *= b; r >= 10; r /= 10) t++; + return t; } - function Id(e = {}) { - let { select: t, ...r } = e; - return typeof t == "object" ? Lt({ ...r, _count: t }) : Lt({ ...r, _count: { _all: true } }); + function nn(e, t, r) { + if (t > Pc) throw x = true, r && (e.precision = r), Error(Ps); + return y(new e(tn), t, 1, true); } - function Od(e = {}) { - return typeof e.select == "object" ? (t) => Sn(e)(t)._count : (t) => Sn(e)(t)._count._all; + function fe(e, t, r) { + if (t > Ti) throw Error(Ps); + return y(new e(rn), t, r, true); } - function wa(e, t) { - return t({ action: "count", unpacker: Od(e), argsMapper: Id })(e); + function Cs(e) { + var t = e.length - 1, r = t * b + 1; + if (t = e[t], t) { + for (; t % 10 == 0; t /= 10) r--; + for (t = e[0]; t >= 10; t /= 10) r++; + } + return r; } - function kd(e = {}) { - let t = Lt(e); - if (Array.isArray(t.by)) for (let r of t.by) typeof r == "string" && (t.select[r] = true); - else typeof t.by == "string" && (t.select[t.by] = true); + function We(e) { + for (var t = ""; e--; ) t += "0"; return t; } - function Dd(e = {}) { - return (t) => (typeof e?._count == "boolean" && t.forEach((r) => { - r._count = r._count._all; - }), t); + function Ss(e, t, r, n) { + var i, o = new e(1), s = Math.ceil(n / b + 4); + for (x = false; ; ) { + if (r % 2 && (o = o.times(t), Es(o.d, s) && (i = true)), r = ee(r / 2), r === 0) { + r = o.d.length - 1, i && o.d[r] === 0 && ++o.d[r]; + break; + } + t = t.times(t), Es(t.d, s); + } + return x = true, o; } - function xa(e, t) { - return t({ action: "groupBy", unpacker: Dd(e), argsMapper: kd })(e); + function bs(e) { + return e.d[e.d.length - 1] & 1; } - function Pa(e, t, r) { - if (t === "aggregate") return (n) => Ea(n, r); - if (t === "count") return (n) => wa(n, r); - if (t === "groupBy") return (n) => xa(n, r); + function As(e, t, r) { + for (var n, i = new e(t[0]), o = 0; ++o < t.length; ) if (n = new e(t[o]), n.s) i[r](n) && (i = n); + else { + i = n; + break; + } + return i; } - function va(e, t) { - let r = t.fields.filter((i) => !i.relationName), n = wi(r, (i) => i.name); - return new Proxy({}, { get(i, o) { - if (o in i || typeof o == "symbol") return i[o]; - let s = n[o]; - if (s) return new sr(e, o, s.type, s.isList, s.kind === "enum"); - }, ...Cn(Object.keys(n)) }); + function Ri(e, t) { + var r, n, i, o, s, a, l, u = 0, c = 0, p = 0, d = e.constructor, f = d.rounding, g = d.precision; + if (!e.d || !e.d[0] || e.e > 17) return new d(e.d ? e.d[0] ? e.s < 0 ? 0 : 1 / 0 : 1 : e.s ? e.s < 0 ? 0 : e : NaN); + for (t == null ? (x = false, l = g) : l = t, a = new d(0.03125); e.e > -2; ) e = e.times(a), p += 5; + for (n = Math.log(G(2, p)) / Math.LN10 * 2 + 5 | 0, l += n, r = o = s = new d(1), d.precision = l; ; ) { + if (o = y(o.times(e), l, 1), r = r.times(++c), a = s.plus(N(o, r, l, 1)), K(a.d).slice(0, l) === K(s.d).slice(0, l)) { + for (i = p; i--; ) s = y(s.times(s), l, 1); + if (t == null) if (u < 3 && rr(s.d, l - n, f, u)) d.precision = l += 10, r = o = a = new d(1), c = 0, u++; + else return y(s, d.precision = g, f, x = true); + else return d.precision = g, s; + } + s = a; + } } - var Ta = (e) => Array.isArray(e) ? e : e.split("."); - var Gi = (e, t) => Ta(t).reduce((r, n) => r && r[n], e); - var Ra = (e, t, r) => Ta(t).reduceRight((n, i, o, s) => Object.assign({}, Gi(e, s.slice(0, o)), { [i]: n }), r); - function _d(e, t) { - return e === void 0 || t === void 0 ? [] : [...t, "select", e]; + function He(e, t) { + var r, n, i, o, s, a, l, u, c, p, d, f = 1, g = 10, h = e, O = h.d, T = h.constructor, S = T.rounding, C = T.precision; + if (h.s < 0 || !O || !O[0] || !h.e && O[0] == 1 && O.length == 1) return new T(O && !O[0] ? -1 / 0 : h.s != 1 ? NaN : O ? 0 : h); + if (t == null ? (x = false, c = C) : c = t, T.precision = c += g, r = K(O), n = r.charAt(0), Math.abs(o = h.e) < 15e14) { + for (; n < 7 && n != 1 || n == 1 && r.charAt(1) > 3; ) h = h.times(e), r = K(h.d), n = r.charAt(0), f++; + o = h.e, n > 1 ? (h = new T("0." + r), o++) : h = new T(n + "." + r.slice(1)); + } else return u = nn(T, c + 2, C).times(o + ""), h = He(new T(n + "." + r.slice(1)), c - g).plus(u), T.precision = C, t == null ? y(h, C, S, x = true) : h; + for (p = h, l = s = h = N(h.minus(1), h.plus(1), c, 1), d = y(h.times(h), c, 1), i = 3; ; ) { + if (s = y(s.times(d), c, 1), u = l.plus(N(s, new T(i), c, 1)), K(u.d).slice(0, c) === K(l.d).slice(0, c)) if (l = l.times(2), o !== 0 && (l = l.plus(nn(T, c + 2, C).times(o + ""))), l = N(l, new T(f), c, 1), t == null) if (rr(l.d, c - g, S, a)) T.precision = c += g, u = s = h = N(p.minus(1), p.plus(1), c, 1), d = y(h.times(h), c, 1), i = a = 1; + else return y(l, T.precision = C, S, x = true); + else return T.precision = C, l; + l = u, i += 2; + } } - function Fd(e, t, r) { - return t === void 0 ? e ?? {} : Ra(t, r, e || true); + function Is(e) { + return String(e.s * e.s / 0); } - function Qi(e, t, r, n, i, o) { - let a = e._runtimeDataModel.models[t].fields.reduce((l, u) => ({ ...l, [u.name]: u }), {}); - return (l) => { - let u = Ze(e._errorFormat), c = _d(n, i), p = Fd(l, o, c), d = r({ dataPath: c, callsite: u })(p), f = Ld(e, t); - return new Proxy(d, { get(g, h) { - if (!f.includes(h)) return g[h]; - let T = [a[h].type, r, h], S = [c, p]; - return Qi(e, ...T, ...S); - }, ...Cn([...f, ...Object.getOwnPropertyNames(d)]) }); - }; + function Ci(e, t) { + var r, n, i; + for ((r = t.indexOf(".")) > -1 && (t = t.replace(".", "")), (n = t.search(/e/i)) > 0 ? (r < 0 && (r = n), r += +t.slice(n + 1), t = t.substring(0, n)) : r < 0 && (r = t.length), n = 0; t.charCodeAt(n) === 48; n++) ; + for (i = t.length; t.charCodeAt(i - 1) === 48; --i) ; + if (t = t.slice(n, i), t) { + if (i -= n, e.e = r = r - n - 1, e.d = [], n = (r + 1) % b, r < 0 && (n += b), n < i) { + for (n && e.d.push(+t.slice(0, n)), i -= b; n < i; ) e.d.push(+t.slice(n, n += b)); + t = t.slice(n), n = b - t.length; + } else n -= i; + for (; n--; ) t += "0"; + e.d.push(+t), x && (e.e > e.constructor.maxE ? (e.d = null, e.e = NaN) : e.e < e.constructor.minE && (e.e = 0, e.d = [0])); + } else e.e = 0, e.d = [0]; + return e; } - function Ld(e, t) { - return e._runtimeDataModel.models[t].fields.filter((r) => r.kind === "object").map((r) => r.name); + function Tc(e, t) { + var r, n, i, o, s, a, l, u, c; + if (t.indexOf("_") > -1) { + if (t = t.replace(/(\d)_(?=\d)/g, "$1"), Rs.test(t)) return Ci(e, t); + } else if (t === "Infinity" || t === "NaN") return +t || (e.s = NaN), e.e = NaN, e.d = null, e; + if (Ec.test(t)) r = 16, t = t.toLowerCase(); + else if (bc.test(t)) r = 2; + else if (wc.test(t)) r = 8; + else throw Error(Ke + t); + for (o = t.search(/p/i), o > 0 ? (l = +t.slice(o + 1), t = t.substring(2, o)) : t = t.slice(2), o = t.indexOf("."), s = o >= 0, n = e.constructor, s && (t = t.replace(".", ""), a = t.length, o = a - o, i = Ss(n, new n(r), o, o * 2)), u = en(t, r, ge), c = u.length - 1, o = c; u[o] === 0; --o) u.pop(); + return o < 0 ? new n(e.s * 0) : (e.e = sn(u, c), e.d = u, x = false, s && (e = N(e, i, a * 4)), l && (e = e.times(Math.abs(l) < 54 ? G(2, l) : it.pow(2, l))), x = true, e); } - function Ca(e, t, r, n) { - return e === Je.ModelAction.findFirstOrThrow || e === Je.ModelAction.findUniqueOrThrow ? Nd(t, r, n) : n; + function Rc(e, t) { + var r, n = t.d.length; + if (n < 3) return t.isZero() ? t : Et(e, 2, t, t); + r = 1.4 * Math.sqrt(n), r = r > 16 ? 16 : r | 0, t = t.times(1 / an(5, r)), t = Et(e, 2, t, t); + for (var i, o = new e(5), s = new e(16), a = new e(20); r--; ) i = t.times(t), t = t.times(o.plus(i.times(s.times(i).minus(a)))); + return t; } - function Nd(e, t, r) { - return async (n) => { - if ("rejectOnNotFound" in n.args) { - let o = Tt({ originalMethod: n.clientMethod, callsite: n.callsite, message: "'rejectOnNotFound' option is not supported" }); - throw new J(o, { clientVersion: t }); + function Et(e, t, r, n, i) { + var o, s, a, l, u = 1, c = e.precision, p = Math.ceil(c / b); + for (x = false, l = r.times(r), a = new e(n); ; ) { + if (s = N(a.times(l), new e(t++ * t++), c, 1), a = i ? n.plus(s) : n.minus(s), n = N(s.times(l), new e(t++ * t++), c, 1), s = a.plus(n), s.d[p] !== void 0) { + for (o = p; s.d[o] === a.d[o] && o--; ) ; + if (o == -1) break; } - return await r(n).catch((o) => { - throw o instanceof V && o.code === "P2025" ? new Le(`No ${e} found`, t) : o; - }); - }; + o = a, a = n, n = s, s = o, u++; + } + return x = true, s.d.length = p + 1, s; } - var Md = ["findUnique", "findUniqueOrThrow", "findFirst", "findFirstOrThrow", "create", "update", "upsert", "delete"]; - var $d = ["aggregate", "count", "groupBy"]; - function Ji(e, t) { - let r = e._extensions.getAllModelExtensions(t) ?? {}, n = [qd(e, t), Vd(e, t), gr(r), re("name", () => t), re("$name", () => t), re("$parent", () => e._appliedParent)]; - return Se({}, n); + function an(e, t) { + for (var r = e; --t; ) r *= e; + return r; } - function qd(e, t) { - let r = Te(t), n = Object.keys(Je.ModelAction).concat("count"); - return { getKeys() { - return n; - }, getPropertyValue(i) { - let o = i, s = (l) => e._request(l); - s = Ca(o, t, e._clientVersion, s); - let a = (l) => (u) => { - let c = Ze(e._errorFormat); - return e._createPrismaPromise((p) => { - let d = { args: u, dataPath: [], action: o, model: t, clientMethod: `${r}.${i}`, jsModelName: r, transaction: p, callsite: c }; - return s({ ...d, ...l }); - }); - }; - return Md.includes(o) ? Qi(e, t, a) : jd(i) ? Pa(e, i, a) : a({}); - } }; + function Os(e, t) { + var r, n = t.s < 0, i = fe(e, e.precision, 1), o = i.times(0.5); + if (t = t.abs(), t.lte(o)) return Ne = n ? 4 : 1, t; + if (r = t.divToInt(i), r.isZero()) Ne = n ? 3 : 2; + else { + if (t = t.minus(r.times(i)), t.lte(o)) return Ne = bs(r) ? n ? 2 : 3 : n ? 4 : 1, t; + Ne = bs(r) ? n ? 1 : 4 : n ? 3 : 2; + } + return t.minus(i).abs(); } - function jd(e) { - return $d.includes(e); + function Si(e, t, r, n) { + var i, o, s, a, l, u, c, p, d, f = e.constructor, g = r !== void 0; + if (g ? (ie(r, 1, ze), n === void 0 ? n = f.rounding : ie(n, 0, 8)) : (r = f.precision, n = f.rounding), !e.isFinite()) c = Is(e); + else { + for (c = we(e), s = c.indexOf("."), g ? (i = 2, t == 16 ? r = r * 4 - 3 : t == 8 && (r = r * 3 - 2)) : i = t, s >= 0 && (c = c.replace(".", ""), d = new f(1), d.e = c.length - s, d.d = en(we(d), 10, i), d.e = d.d.length), p = en(c, 10, i), o = l = p.length; p[--l] == 0; ) p.pop(); + if (!p[0]) c = g ? "0p+0" : "0"; + else { + if (s < 0 ? o-- : (e = new f(e), e.d = p, e.e = o, e = N(e, d, r, n, 0, i), p = e.d, o = e.e, u = xs), s = p[r], a = i / 2, u = u || p[r + 1] !== void 0, u = n < 4 ? (s !== void 0 || u) && (n === 0 || n === (e.s < 0 ? 3 : 2)) : s > a || s === a && (n === 4 || u || n === 6 && p[r - 1] & 1 || n === (e.s < 0 ? 8 : 7)), p.length = r, u) for (; ++p[--r] > i - 1; ) p[r] = 0, r || (++o, p.unshift(1)); + for (l = p.length; !p[l - 1]; --l) ; + for (s = 0, c = ""; s < l; s++) c += Pi.charAt(p[s]); + if (g) { + if (l > 1) if (t == 16 || t == 8) { + for (s = t == 16 ? 4 : 3, --l; l % s; l++) c += "0"; + for (p = en(c, i, t), l = p.length; !p[l - 1]; --l) ; + for (s = 1, c = "1."; s < l; s++) c += Pi.charAt(p[s]); + } else c = c.charAt(0) + "." + c.slice(1); + c = c + (o < 0 ? "p" : "p+") + o; + } else if (o < 0) { + for (; ++o; ) c = "0" + c; + c = "0." + c; + } else if (++o > l) for (o -= l; o--; ) c += "0"; + else o < l && (c = c.slice(0, o) + "." + c.slice(o)); + } + c = (t == 16 ? "0x" : t == 2 ? "0b" : t == 8 ? "0o" : "") + c; + } + return e.s < 0 ? "-" + c : c; } - function Vd(e, t) { - return ot(re("fields", () => { - let r = e._runtimeDataModel.models[t]; - return va(t, r); - })); + function Es(e, t) { + if (e.length > t) return e.length = t, true; } - function Sa(e) { - return e.replace(/^./, (t) => t.toUpperCase()); + function Cc(e) { + return new this(e).abs(); } - var Wi = Symbol(); - function yr(e) { - let t = [Bd(e), re(Wi, () => e), re("$parent", () => e._appliedParent)], r = e._extensions.getAllClientExtensions(); - return r && t.push(gr(r)), Se(e, t); + function Sc(e) { + return new this(e).acos(); } - function Bd(e) { - let t = Object.keys(e._runtimeDataModel.models), r = t.map(Te), n = [...new Set(t.concat(r))]; - return ot({ getKeys() { - return n; - }, getPropertyValue(i) { - let o = Sa(i); - if (e._runtimeDataModel.models[o] !== void 0) return Ji(e, o); - if (e._runtimeDataModel.models[i] !== void 0) return Ji(e, i); - }, getPropertyDescriptor(i) { - if (!r.includes(i)) return { enumerable: false }; - } }); + function Ac(e) { + return new this(e).acosh(); } - function Aa(e) { - return e[Wi] ? e[Wi] : e; + function Ic(e, t) { + return new this(e).plus(t); } - function Ia(e) { - if (typeof e == "function") return e(this); - if (e.client?.__AccelerateEngine) { - let r = e.client.__AccelerateEngine; - this._originalClient._engine = new r(this._originalClient._accelerateEngineConfig); - } - let t = Object.create(this._originalClient, { _extensions: { value: this._extensions.append(e) }, _appliedParent: { value: this, configurable: true }, $use: { value: void 0 }, $on: { value: void 0 } }); - return yr(t); + function Oc(e) { + return new this(e).asin(); } - function Oa({ result: e, modelName: t, select: r, omit: n, extensions: i }) { - let o = i.getAllComputedFields(t); - if (!o) return e; - let s = [], a = []; - for (let l of Object.values(o)) { - if (n) { - if (n[l.name]) continue; - let u = l.needs.filter((c) => n[c]); - u.length > 0 && a.push(_t(u)); - } else if (r) { - if (!r[l.name]) continue; - let u = l.needs.filter((c) => !r[c]); - u.length > 0 && a.push(_t(u)); - } - Ud(e, l.needs) && s.push(Gd(l, Se(e, s))); - } - return s.length > 0 || a.length > 0 ? Se(e, [...s, ...a]) : e; + function kc(e) { + return new this(e).asinh(); } - function Ud(e, t) { - return t.every((r) => Ei(e, r)); + function Dc(e) { + return new this(e).atan(); } - function Gd(e, t) { - return ot(re(e.name, () => e.compute(t))); + function _c(e) { + return new this(e).atanh(); } - function An({ visitor: e, result: t, args: r, runtimeDataModel: n, modelName: i }) { - if (Array.isArray(t)) { - for (let s = 0; s < t.length; s++) t[s] = An({ result: t[s], args: r, modelName: i, runtimeDataModel: n, visitor: e }); - return t; - } - let o = e(t, i, r) ?? t; - return r.include && ka({ includeOrSelect: r.include, result: o, parentModelName: i, runtimeDataModel: n, visitor: e }), r.select && ka({ includeOrSelect: r.select, result: o, parentModelName: i, runtimeDataModel: n, visitor: e }), o; + function Fc(e, t) { + e = new this(e), t = new this(t); + var r, n = this.precision, i = this.rounding, o = n + 4; + return !e.s || !t.s ? r = new this(NaN) : !e.d && !t.d ? (r = fe(this, o, 1).times(t.s > 0 ? 0.25 : 0.75), r.s = e.s) : !t.d || e.isZero() ? (r = t.s < 0 ? fe(this, n, i) : new this(0), r.s = e.s) : !e.d || t.isZero() ? (r = fe(this, o, 1).times(0.5), r.s = e.s) : t.s < 0 ? (this.precision = o, this.rounding = 1, r = this.atan(N(e, t, o, 1)), t = fe(this, o, 1), this.precision = n, this.rounding = i, r = e.s < 0 ? r.minus(t) : r.plus(t)) : r = this.atan(N(e, t, o, 1)), r; } - function ka({ includeOrSelect: e, result: t, parentModelName: r, runtimeDataModel: n, visitor: i }) { - for (let [o, s] of Object.entries(e)) { - if (!s || t[o] == null || Re(s)) continue; - let l = n.models[r].fields.find((c) => c.name === o); - if (!l || l.kind !== "object" || !l.relationName) continue; - let u = typeof s == "object" ? s : {}; - t[o] = An({ visitor: i, result: t[o], args: u, modelName: l.type, runtimeDataModel: n }); - } + function Lc(e) { + return new this(e).cbrt(); } - function Da({ result: e, modelName: t, args: r, extensions: n, runtimeDataModel: i, globalOmit: o }) { - return n.isEmpty() || e == null || typeof e != "object" || !i.models[t] ? e : An({ result: e, args: r ?? {}, modelName: t, runtimeDataModel: i, visitor: (a, l, u) => { - let c = Te(l); - return Oa({ result: a, modelName: c, select: u.select, omit: u.select ? void 0 : { ...o?.[c], ...u.omit }, extensions: n }); - } }); + function Nc(e) { + return y(e = new this(e), e.e + 1, 2); } - function _a(e) { - if (e instanceof oe) return Qd(e); - if (Array.isArray(e)) { - let r = [e[0]]; - for (let n = 1; n < e.length; n++) r[n] = br(e[n]); - return r; - } - let t = {}; - for (let r in e) t[r] = br(e[r]); - return t; + function Mc(e, t, r) { + return new this(e).clamp(t, r); } - function Qd(e) { - return new oe(e.strings, e.values); + function $c(e) { + if (!e || typeof e != "object") throw Error(on + "Object expected"); + var t, r, n, i = e.defaults === true, o = ["precision", 1, ze, "rounding", 0, 8, "toExpNeg", -bt, 0, "toExpPos", 0, bt, "maxE", 0, bt, "minE", -bt, 0, "modulo", 0, 9]; + for (t = 0; t < o.length; t += 3) if (r = o[t], i && (this[r] = vi[r]), (n = e[r]) !== void 0) if (ee(n) === n && n >= o[t + 1] && n <= o[t + 2]) this[r] = n; + else throw Error(Ke + r + ": " + n); + if (r = "crypto", i && (this[r] = vi[r]), (n = e[r]) !== void 0) if (n === true || n === false || n === 0 || n === 1) if (n) if (typeof crypto < "u" && crypto && (crypto.getRandomValues || crypto.randomBytes)) this[r] = true; + else throw Error(vs); + else this[r] = false; + else throw Error(Ke + r + ": " + n); + return this; } - function br(e) { - if (typeof e != "object" || e == null || e instanceof Me || It(e)) return e; - if (vt(e)) return new xe(e.toFixed()); - if (Pt(e)) return /* @__PURE__ */ new Date(+e); - if (ArrayBuffer.isView(e)) return e.slice(0); - if (Array.isArray(e)) { - let t = e.length, r; - for (r = Array(t); t--; ) r[t] = br(e[t]); - return r; - } - if (typeof e == "object") { - let t = {}; - for (let r in e) r === "__proto__" ? Object.defineProperty(t, r, { value: br(e[r]), configurable: true, enumerable: true, writable: true }) : t[r] = br(e[r]); - return t; - } - Fe(e, "Unknown value"); + function qc(e) { + return new this(e).cos(); } - function La(e, t, r, n = 0) { - return e._createPrismaPromise((i) => { - let o = t.customDataProxyFetch; - return "transaction" in t && i !== void 0 && (t.transaction?.kind === "batch" && t.transaction.lock.then(), t.transaction = i), n === r.length ? e._executeRequest(t) : r[n]({ model: t.model, operation: t.model ? t.action : t.clientMethod, args: _a(t.args ?? {}), __internalParams: t, query: (s, a = t) => { - let l = a.customDataProxyFetch; - return a.customDataProxyFetch = qa(o, l), a.args = s, La(e, a, r, n + 1); - } }); - }); + function jc(e) { + return new this(e).cosh(); } - function Na(e, t) { - let { jsModelName: r, action: n, clientMethod: i } = t, o = r ? n : i; - if (e._extensions.isEmpty()) return e._executeRequest(t); - let s = e._extensions.getAllQueryCallbacks(r ?? "$none", o); - return La(e, t, s); + function ks(e) { + var t, r, n; + function i(o) { + var s, a, l, u = this; + if (!(u instanceof i)) return new i(o); + if (u.constructor = i, ws(o)) { + u.s = o.s, x ? !o.d || o.e > i.maxE ? (u.e = NaN, u.d = null) : o.e < i.minE ? (u.e = 0, u.d = [0]) : (u.e = o.e, u.d = o.d.slice()) : (u.e = o.e, u.d = o.d ? o.d.slice() : o.d); + return; + } + if (l = typeof o, l === "number") { + if (o === 0) { + u.s = 1 / o < 0 ? -1 : 1, u.e = 0, u.d = [0]; + return; + } + if (o < 0 ? (o = -o, u.s = -1) : u.s = 1, o === ~~o && o < 1e7) { + for (s = 0, a = o; a >= 10; a /= 10) s++; + x ? s > i.maxE ? (u.e = NaN, u.d = null) : s < i.minE ? (u.e = 0, u.d = [0]) : (u.e = s, u.d = [o]) : (u.e = s, u.d = [o]); + return; + } else if (o * 0 !== 0) { + o || (u.s = NaN), u.e = NaN, u.d = null; + return; + } + return Ci(u, o.toString()); + } else if (l !== "string") throw Error(Ke + o); + return (a = o.charCodeAt(0)) === 45 ? (o = o.slice(1), u.s = -1) : (a === 43 && (o = o.slice(1)), u.s = 1), Rs.test(o) ? Ci(u, o) : Tc(u, o); + } + if (i.prototype = m, i.ROUND_UP = 0, i.ROUND_DOWN = 1, i.ROUND_CEIL = 2, i.ROUND_FLOOR = 3, i.ROUND_HALF_UP = 4, i.ROUND_HALF_DOWN = 5, i.ROUND_HALF_EVEN = 6, i.ROUND_HALF_CEIL = 7, i.ROUND_HALF_FLOOR = 8, i.EUCLID = 9, i.config = i.set = $c, i.clone = ks, i.isDecimal = ws, i.abs = Cc, i.acos = Sc, i.acosh = Ac, i.add = Ic, i.asin = Oc, i.asinh = kc, i.atan = Dc, i.atanh = _c, i.atan2 = Fc, i.cbrt = Lc, i.ceil = Nc, i.clamp = Mc, i.cos = qc, i.cosh = jc, i.div = Vc, i.exp = Bc, i.floor = Uc, i.hypot = Gc, i.ln = Qc, i.log = Jc, i.log10 = Hc, i.log2 = Wc, i.max = Kc, i.min = zc, i.mod = Yc, i.mul = Zc, i.pow = Xc, i.random = ep, i.round = tp, i.sign = rp, i.sin = np, i.sinh = ip, i.sqrt = op, i.sub = sp, i.sum = ap, i.tan = lp, i.tanh = up, i.trunc = cp, e === void 0 && (e = {}), e && e.defaults !== true) for (n = ["precision", "rounding", "toExpNeg", "toExpPos", "maxE", "minE", "modulo", "crypto"], t = 0; t < n.length; ) e.hasOwnProperty(r = n[t++]) || (e[r] = this[r]); + return i.config(e), i; } - function Ma(e) { - return (t) => { - let r = { requests: t }, n = t[0].extensions.getAllBatchQueryCallbacks(); - return n.length ? $a(r, n, 0, e) : e(r); - }; + function Vc(e, t) { + return new this(e).div(t); } - function $a(e, t, r, n) { - if (r === t.length) return n(e); - let i = e.customDataProxyFetch, o = e.requests[0].transaction; - return t[r]({ args: { queries: e.requests.map((s) => ({ model: s.modelName, operation: s.action, args: s.args })), transaction: o ? { isolationLevel: o.kind === "batch" ? o.isolationLevel : void 0 } : void 0 }, __internalParams: e, query(s, a = e) { - let l = a.customDataProxyFetch; - return a.customDataProxyFetch = qa(i, l), $a(a, t, r + 1, n); - } }); + function Bc(e) { + return new this(e).exp(); } - var Fa = (e) => e; - function qa(e = Fa, t = Fa) { - return (r) => e(t(r)); + function Uc(e) { + return y(e = new this(e), e.e + 1, 3); } - var ja = L("prisma:client"); - var Va = { Vercel: "vercel", "Netlify CI": "netlify" }; - function Ba({ postinstall: e, ciName: t, clientVersion: r }) { - if (ja("checkPlatformCaching:postinstall", e), ja("checkPlatformCaching:ciName", t), e === true && t && t in Va) { - let n = `Prisma has detected that this project was built on ${t}, which caches dependencies. This leads to an outdated Prisma Client because Prisma's auto-generation isn't triggered. To fix this, make sure to run the \`prisma generate\` command during the build process. - -Learn how: https://pris.ly/d/${Va[t]}-build`; - throw console.error(n), new R(n, r); + function Gc() { + var e, t, r = new this(0); + for (x = false, e = 0; e < arguments.length; ) if (t = new this(arguments[e++]), t.d) r.d && (r = r.plus(t.times(t))); + else { + if (t.s) return x = true, new this(1 / 0); + r = t; } + return x = true, r.sqrt(); } - function Ua(e, t) { - return e ? e.datasources ? e.datasources : e.datasourceUrl ? { [t[0]]: { url: e.datasourceUrl } } : {} : {}; + function ws(e) { + return e instanceof it || e && e.toStringTag === Ts || false; } - var Jd = "Cloudflare-Workers"; - var Wd = "node"; - function Ga() { - return typeof Netlify == "object" ? "netlify" : typeof EdgeRuntime == "string" ? "edge-light" : globalThis.navigator?.userAgent === Jd ? "workerd" : globalThis.Deno ? "deno" : globalThis.__lagon__ ? "lagon" : globalThis.process?.release?.name === Wd ? "node" : globalThis.Bun ? "bun" : globalThis.fastly ? "fastly" : "unknown"; + function Qc(e) { + return new this(e).ln(); } - var Hd = { node: "Node.js", workerd: "Cloudflare Workers", deno: "Deno and Deno Deploy", netlify: "Netlify Edge Functions", "edge-light": "Edge Runtime (Vercel Edge Functions, Vercel Edge Middleware, Next.js (Pages Router) Edge API Routes, Next.js (App Router) Edge Route Handlers or Next.js Middleware)" }; - function In() { - let e = Ga(); - return { id: e, prettyName: Hd[e] || e, isEdge: ["workerd", "deno", "netlify", "edge-light"].includes(e) }; + function Jc(e, t) { + return new this(e).log(t); } - var Ka = k(__require("fs")); - var Er = k(__require("path")); - function On(e) { - let { runtimeBinaryTarget: t } = e; - return `Add "${t}" to \`binaryTargets\` in the "schema.prisma" file and run \`prisma generate\` after saving it: - -${Kd(e)}`; + function Wc(e) { + return new this(e).log(2); } - function Kd(e) { - let { generator: t, generatorBinaryTargets: r, runtimeBinaryTarget: n } = e, i = { fromEnvVar: null, value: n }, o = [...r, i]; - return hi({ ...t, binaryTargets: o }); + function Hc(e) { + return new this(e).log(10); } - function Xe(e) { - let { runtimeBinaryTarget: t } = e; - return `Prisma Client could not locate the Query Engine for runtime "${t}".`; + function Kc() { + return As(this, arguments, "lt"); } - function et(e) { - let { searchedLocations: t } = e; - return `The following locations have been searched: -${[...new Set(t)].map((i) => ` ${i}`).join(` -`)}`; + function zc() { + return As(this, arguments, "gt"); } - function Qa(e) { - let { runtimeBinaryTarget: t } = e; - return `${Xe(e)} - -This happened because \`binaryTargets\` have been pinned, but the actual deployment also required "${t}". -${On(e)} - -${et(e)}`; + function Yc(e, t) { + return new this(e).mod(t); } - function kn(e) { - return `We would appreciate if you could take the time to share some information with us. -Please help us by answering a few questions: https://pris.ly/${e}`; + function Zc(e, t) { + return new this(e).mul(t); + } + function Xc(e, t) { + return new this(e).pow(t); + } + function ep(e) { + var t, r, n, i, o = 0, s = new this(1), a = []; + if (e === void 0 ? e = this.precision : ie(e, 1, ze), n = Math.ceil(e / b), this.crypto) if (crypto.getRandomValues) for (t = crypto.getRandomValues(new Uint32Array(n)); o < n; ) i = t[o], i >= 429e7 ? t[o] = crypto.getRandomValues(new Uint32Array(1))[0] : a[o++] = i % 1e7; + else if (crypto.randomBytes) { + for (t = crypto.randomBytes(n *= 4); o < n; ) i = t[o] + (t[o + 1] << 8) + (t[o + 2] << 16) + ((t[o + 3] & 127) << 24), i >= 214e7 ? crypto.randomBytes(4).copy(t, o) : (a.push(i % 1e7), o += 4); + o = n / 4; + } else throw Error(vs); + else for (; o < n; ) a[o++] = Math.random() * 1e7 | 0; + for (n = a[--o], e %= b, n && e && (i = G(10, b - e), a[o] = (n / i | 0) * i); a[o] === 0; o--) a.pop(); + if (o < 0) r = 0, a = [0]; + else { + for (r = -1; a[0] === 0; r -= b) a.shift(); + for (n = 1, i = a[0]; i >= 10; i /= 10) n++; + n < b && (r -= b - n); + } + return s.e = r, s.d = a, s; } - function Dn(e) { - let { errorStack: t } = e; - return t?.match(/\/\.next|\/next@|\/next\//) ? ` - -We detected that you are using Next.js, learn how to fix this: https://pris.ly/d/engine-not-found-nextjs.` : ""; + function tp(e) { + return y(e = new this(e), e.e + 1, this.rounding); } - function Ja(e) { - let { queryEngineName: t } = e; - return `${Xe(e)}${Dn(e)} - -This is likely caused by a bundler that has not copied "${t}" next to the resulting bundle. -Ensure that "${t}" has been copied next to the bundle or in "${e.expectedLocation}". - -${kn("engine-not-found-bundler-investigation")} - -${et(e)}`; + function rp(e) { + return e = new this(e), e.d ? e.d[0] ? e.s : 0 * e.s : e.s || NaN; } - function Wa(e) { - let { runtimeBinaryTarget: t, generatorBinaryTargets: r } = e, n = r.find((i) => i.native); - return `${Xe(e)} - -This happened because Prisma Client was generated for "${n?.value ?? "unknown"}", but the actual deployment required "${t}". -${On(e)} - -${et(e)}`; + function np(e) { + return new this(e).sin(); } - function Ha(e) { - let { queryEngineName: t } = e; - return `${Xe(e)}${Dn(e)} - -This is likely caused by tooling that has not copied "${t}" to the deployment folder. -Ensure that you ran \`prisma generate\` and that "${t}" has been copied to "${e.expectedLocation}". - -${kn("engine-not-found-tooling-investigation")} - -${et(e)}`; + function ip(e) { + return new this(e).sinh(); } - var zd = L("prisma:client:engines:resolveEnginePath"); - var Yd = () => new RegExp("runtime[\\\\/]library\\.m?js$"); - async function za(e, t) { - let r = { binary: process.env.PRISMA_QUERY_ENGINE_BINARY, library: process.env.PRISMA_QUERY_ENGINE_LIBRARY }[e] ?? t.prismaPath; - if (r !== void 0) return r; - let { enginePath: n, searchedLocations: i } = await Zd(e, t); - if (zd("enginePath", n), n !== void 0 && e === "binary" && li(n), n !== void 0) return t.prismaPath = n; - let o = await nt(), s = t.generator?.binaryTargets ?? [], a = s.some((d) => d.native), l = !s.some((d) => d.value === o), u = __filename.match(Yd()) === null, c = { searchedLocations: i, generatorBinaryTargets: s, generator: t.generator, runtimeBinaryTarget: o, queryEngineName: Ya(e, o), expectedLocation: Er.default.relative(process.cwd(), t.dirname), errorStack: new Error().stack }, p; - throw a && l ? p = Wa(c) : l ? p = Qa(c) : u ? p = Ja(c) : p = Ha(c), new R(p, t.clientVersion); + function op(e) { + return new this(e).sqrt(); } - async function Zd(engineType, config) { - let binaryTarget = await nt(), searchedLocations = [], dirname = eval("__dirname"), searchLocations = [config.dirname, Er.default.resolve(dirname, ".."), config.generator?.output?.value ?? dirname, Er.default.resolve(dirname, "../../../.prisma/client"), "/tmp/prisma-engines", config.cwd]; - __filename.includes("resolveEnginePath") && searchLocations.push(Yo()); - for (let e of searchLocations) { - let t = Ya(engineType, binaryTarget), r = Er.default.join(e, t); - if (searchedLocations.push(e), Ka.default.existsSync(r)) return { enginePath: r, searchedLocations }; - } - return { enginePath: void 0, searchedLocations }; + function sp(e, t) { + return new this(e).sub(t); } - function Ya(e, t) { - return e === "library" ? qr(t, "fs") : `query-engine-${t}${t === "windows" ? ".exe" : ""}`; + function ap() { + var e = 0, t = arguments, r = new this(t[e]); + for (x = false; r.s && ++e < t.length; ) r = r.plus(t[e]); + return x = true, y(r, this.precision, this.rounding); } - var Hi = k(bi()); - function Za(e) { - return e ? e.replace(/".*"/g, '"X"').replace(/[\s:\[]([+-]?([0-9]*[.])?[0-9]+)/g, (t) => `${t[0]}5`) : ""; + function lp(e) { + return new this(e).tan(); } - function Xa(e) { - return e.split(` -`).map((t) => t.replace(/^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)\s*/, "").replace(/\+\d+\s*ms$/, "")).join(` -`); + function up(e) { + return new this(e).tanh(); } - var el = k(hs()); - function tl({ title: e, user: t = "prisma", repo: r = "prisma", template: n = "bug_report.yml", body: i }) { - return (0, el.default)({ user: t, repo: r, template: n, title: e, body: i }); + function cp(e) { + return y(e = new this(e), e.e + 1, 1); } - function rl({ version: e, binaryTarget: t, title: r, description: n, engineVersion: i, database: o, query: s }) { - let a = So(6e3 - (s?.length ?? 0)), l = Xa((0, Hi.default)(a)), u = n ? `# Description -\`\`\` -${n} -\`\`\`` : "", c = (0, Hi.default)(`Hi Prisma Team! My Prisma Client just crashed. This is the report: -## Versions - -| Name | Version | -|-----------------|--------------------| -| Node | ${process.version?.padEnd(19)}| -| OS | ${t?.padEnd(19)}| -| Prisma Client | ${e?.padEnd(19)}| -| Query Engine | ${i?.padEnd(19)}| -| Database | ${o?.padEnd(19)}| - -${u} - -## Logs -\`\`\` -${l} -\`\`\` - -## Client Snippet -\`\`\`ts -// PLEASE FILL YOUR CODE SNIPPET HERE -\`\`\` - -## Schema -\`\`\`prisma -// PLEASE ADD YOUR SCHEMA HERE IF POSSIBLE -\`\`\` - -## Prisma Engine Query -\`\`\` -${s ? Za(s) : ""} -\`\`\` -`), p = tl({ title: r, body: c }); - return `${r} - -This is a non-recoverable error which probably happens when the Prisma Query Engine has a panic. - -${X(p)} - -If you want the Prisma team to look into it, please open the link above \u{1F64F} -To increase the chance of success, please post your schema and a snippet of -how you used Prisma Client in the issue. -`; + m[Symbol.for("nodejs.util.inspect.custom")] = m.toString; + m[Symbol.toStringTag] = "Decimal"; + var it = m.constructor = ks(vi); + tn = new it(tn); + rn = new it(rn); + var xe = it; + function wt(e) { + return e === null ? e : Array.isArray(e) ? e.map(wt) : typeof e == "object" ? pp(e) ? dp(e) : yt(e, wt) : e; } - function Nt({ inlineDatasources: e, overrideDatasources: t, env: r, clientVersion: n }) { - let i, o = Object.keys(e)[0], s = e[o]?.url, a = t[o]?.url; - if (o === void 0 ? i = void 0 : a ? i = a : s?.value ? i = s.value : s?.fromEnvVar && (i = r[s.fromEnvVar]), s?.fromEnvVar !== void 0 && i === void 0) throw new R(`error: Environment variable not found: ${s.fromEnvVar}.`, n); - if (i === void 0) throw new R("error: Missing URL environment variable, value, or override.", n); - return i; + function pp(e) { + return e !== null && typeof e == "object" && typeof e.$type == "string"; } - var _n = class extends Error { - constructor(t, r) { - super(t), this.clientVersion = r.clientVersion, this.cause = r.cause; - } - get [Symbol.toStringTag]() { - return this.name; - } - }; - var se = class extends _n { - constructor(t, r) { - super(t, r), this.isRetryable = r.isRetryable ?? true; + function dp({ $type: e, value: t }) { + switch (e) { + case "BigInt": + return BigInt(t); + case "Bytes": + return Buffer.from(t, "base64"); + case "DateTime": + return new Date(t); + case "Decimal": + return new xe(t); + case "Json": + return JSON.parse(t); + default: + Fe(t, "Unknown tagged value"); } - }; - function A(e, t) { - return { ...e, isRetryable: t }; } - var Mt = class extends se { - constructor(r) { - super("This request must be retried", A(r, true)); - this.name = "ForcedRetryError"; - this.code = "P5001"; + function xt(e) { + return e.substring(0, 1).toLowerCase() + e.substring(1); + } + function Pt(e) { + return e instanceof Date || Object.prototype.toString.call(e) === "[object Date]"; + } + function ln(e) { + return e.toString() !== "Invalid Date"; + } + function vt(e) { + return it.isDecimal(e) ? true : e !== null && typeof e == "object" && typeof e.s == "number" && typeof e.e == "number" && typeof e.toFixed == "function" && Array.isArray(e.d); + } + var Ms = k(fi()); + var Ns = k(__require("fs")); + var Ds = { keyword: De, entity: De, value: (e) => H(rt(e)), punctuation: rt, directive: De, function: De, variable: (e) => H(rt(e)), string: (e) => H(qe(e)), boolean: ke, number: De, comment: Gt }; + var mp = (e) => e; + var un = {}; + var fp = 0; + var P = { manual: un.Prism && un.Prism.manual, disableWorkerMessageHandler: un.Prism && un.Prism.disableWorkerMessageHandler, util: { encode: function(e) { + if (e instanceof he) { + let t = e; + return new he(t.type, P.util.encode(t.content), t.alias); + } else return Array.isArray(e) ? e.map(P.util.encode) : e.replace(/&/g, "&").replace(/ e.length) return; + if (Ie instanceof he) continue; + if (me && U != t.length - 1) { + S.lastIndex = ne; + var p = S.exec(e); + if (!p) break; + var c = p.index + (E ? p[1].length : 0), d = p.index + p[0].length, a = U, l = ne; + for (let _ = t.length; a < _ && (l < d || !t[a].type && !t[a - 1].greedy); ++a) l += t[a].length, c >= l && (++U, ne = l); + if (t[U] instanceof he) continue; + u = a - U, Ie = e.slice(ne, l), p.index -= ne; + } else { + S.lastIndex = 0; + var p = S.exec(Ie), u = 1; + } + if (!p) { + if (o) break; + continue; + } + E && (ae = p[1] ? p[1].length : 0); + var c = p.index + ae, p = p[0].slice(ae), d = c + p.length, f = Ie.slice(0, c), g = Ie.slice(d); + let z = [U, u]; + f && (++U, ne += f.length, z.push(f)); + let dt = new he(h, C ? P.tokenize(p, C) : p, Bt, p, me); + if (z.push(dt), g && z.push(g), Array.prototype.splice.apply(t, z), u != 1 && P.matchGrammar(e, t, r, U, ne, true, h), o) break; + } } } - }; - var ut = class extends q { - constructor(r) { - super("Schema needs to be uploaded", A(r, true)); - this.name = "SchemaMissingError"; - this.code = "P5005"; + }, tokenize: function(e, t) { + let r = [e], n = t.rest; + if (n) { + for (let i in n) t[i] = n[i]; + delete t.rest; } + return P.matchGrammar(e, r, t, 0, 0, false), r; + }, hooks: { all: {}, add: function(e, t) { + let r = P.hooks.all; + r[e] = r[e] || [], r[e].push(t); + }, run: function(e, t) { + let r = P.hooks.all[e]; + if (!(!r || !r.length)) for (var n = 0, i; i = r[n++]; ) i(t); + } }, Token: he }; + P.languages.clike = { comment: [{ pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/, lookbehind: true }, { pattern: /(^|[^\\:])\/\/.*/, lookbehind: true, greedy: true }], string: { pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, greedy: true }, "class-name": { pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i, lookbehind: true, inside: { punctuation: /[.\\]/ } }, keyword: /\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/, boolean: /\b(?:true|false)\b/, function: /\w+(?=\()/, number: /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i, operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/, punctuation: /[{}[\];(),.:]/ }; + P.languages.javascript = P.languages.extend("clike", { "class-name": [P.languages.clike["class-name"], { pattern: /(^|[^$\w\xA0-\uFFFF])[_$A-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\.(?:prototype|constructor))/, lookbehind: true }], keyword: [{ pattern: /((?:^|})\s*)(?:catch|finally)\b/, lookbehind: true }, { pattern: /(^|[^.])\b(?:as|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/, lookbehind: true }], number: /\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/, function: /[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/, operator: /-[-=]?|\+[+=]?|!=?=?|<>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3}/ }); + P.languages.javascript["class-name"][0].pattern = /(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/; + P.languages.insertBefore("javascript", "keyword", { regex: { pattern: /((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^/\\\[\r\n])+\/[gimyus]{0,6}(?=\s*($|[\r\n,.;})\]]))/, lookbehind: true, greedy: true }, "function-variable": { pattern: /[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/, alias: "function" }, parameter: [{ pattern: /(function(?:\s+[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)?\s*\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\))/, lookbehind: true, inside: P.languages.javascript }, { pattern: /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=>)/i, inside: P.languages.javascript }, { pattern: /(\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*=>)/, lookbehind: true, inside: P.languages.javascript }, { pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*\s*)\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*\{)/, lookbehind: true, inside: P.languages.javascript }], constant: /\b[A-Z](?:[A-Z_]|\dx?)*\b/ }); + P.languages.markup && P.languages.markup.tag.addInlined("script", "javascript"); + P.languages.js = P.languages.javascript; + P.languages.typescript = P.languages.extend("javascript", { keyword: /\b(?:abstract|as|async|await|break|case|catch|class|const|constructor|continue|debugger|declare|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|is|keyof|let|module|namespace|new|null|of|package|private|protected|public|readonly|return|require|set|static|super|switch|this|throw|try|type|typeof|var|void|while|with|yield)\b/, builtin: /\b(?:string|Function|any|number|boolean|Array|symbol|console|Promise|unknown|never)\b/ }); + P.languages.ts = P.languages.typescript; + function he(e, t, r, n, i) { + this.type = e, this.content = t, this.alias = r, this.length = (n || "").length | 0, this.greedy = !!i; + } + he.stringify = function(e, t) { + return typeof e == "string" ? e : Array.isArray(e) ? e.map(function(r) { + return he.stringify(r, t); + }).join("") : gp(e.type)(e.content); }; - w(ut, "SchemaMissingError"); - var Ki = "This request could not be understood by the server"; - var wr = class extends q { - constructor(r, n, i) { - super(n || Ki, A(r, false)); - this.name = "BadRequestError"; - this.code = "P5000"; - i && (this.code = i); + function gp(e) { + return Ds[e] || mp; + } + function _s(e) { + return hp(e, P.languages.javascript); + } + function hp(e, t) { + return P.tokenize(e, t).map((n) => he.stringify(n)).join(""); + } + var Fs = k(us()); + function Ls(e) { + return (0, Fs.default)(e); + } + var cn = class e { + static read(t) { + let r; + try { + r = Ns.default.readFileSync(t, "utf-8"); + } catch { + return null; + } + return e.fromContent(r); } - }; - w(wr, "BadRequestError"); - var xr = class extends q { - constructor(r, n) { - super("Engine not started: healthcheck timeout", A(r, true)); - this.name = "HealthcheckTimeoutError"; - this.code = "P5013"; - this.logs = n; + static fromContent(t) { + let r = t.split(/\r?\n/); + return new e(1, r); } - }; - w(xr, "HealthcheckTimeoutError"); - var Pr = class extends q { - constructor(r, n, i) { - super(n, A(r, true)); - this.name = "EngineStartupError"; - this.code = "P5014"; - this.logs = i; + constructor(t, r) { + this.firstLineNumber = t, this.lines = r; } - }; - w(Pr, "EngineStartupError"); - var vr = class extends q { - constructor(r) { - super("Engine version is not supported", A(r, false)); - this.name = "EngineVersionNotSupportedError"; - this.code = "P5012"; + get lastLineNumber() { + return this.firstLineNumber + this.lines.length - 1; } - }; - w(vr, "EngineVersionNotSupportedError"); - var zi = "Request timed out"; - var Tr = class extends q { - constructor(r, n = zi) { - super(n, A(r, false)); - this.name = "GatewayTimeoutError"; - this.code = "P5009"; + mapLineAt(t, r) { + if (t < this.firstLineNumber || t > this.lines.length + this.firstLineNumber) return this; + let n = t - this.firstLineNumber, i = [...this.lines]; + return i[n] = r(i[n]), new e(this.firstLineNumber, i); } - }; - w(Tr, "GatewayTimeoutError"); - var Xd = "Interactive transaction error"; - var Rr = class extends q { - constructor(r, n = Xd) { - super(n, A(r, false)); - this.name = "InteractiveTransactionError"; - this.code = "P5015"; + mapLines(t) { + return new e(this.firstLineNumber, this.lines.map((r, n) => t(r, this.firstLineNumber + n))); } - }; - w(Rr, "InteractiveTransactionError"); - var em = "Request parameters are invalid"; - var Cr = class extends q { - constructor(r, n = em) { - super(n, A(r, false)); - this.name = "InvalidRequestError"; - this.code = "P5011"; + lineAt(t) { + return this.lines[t - this.firstLineNumber]; } - }; - w(Cr, "InvalidRequestError"); - var Yi = "Requested resource does not exist"; - var Sr = class extends q { - constructor(r, n = Yi) { - super(n, A(r, false)); - this.name = "NotFoundError"; - this.code = "P5003"; + prependSymbolAt(t, r) { + return this.mapLines((n, i) => i === t ? `${r} ${n}` : ` ${n}`); } - }; - w(Sr, "NotFoundError"); - var Zi = "Unknown server error"; - var $t = class extends q { - constructor(r, n, i) { - super(n || Zi, A(r, true)); - this.name = "ServerError"; - this.code = "P5006"; - this.logs = i; + slice(t, r) { + let n = this.lines.slice(t - 1, r).join(` +`); + return new e(t, Ls(n).split(` +`)); } - }; - w($t, "ServerError"); - var Xi = "Unauthorized, check your connection string"; - var Ar = class extends q { - constructor(r, n = Xi) { - super(n, A(r, false)); - this.name = "UnauthorizedError"; - this.code = "P5007"; + highlight() { + let t = _s(this.toString()); + return new e(this.firstLineNumber, t.split(` +`)); } - }; - w(Ar, "UnauthorizedError"); - var eo = "Usage exceeded, retry again later"; - var Ir = class extends q { - constructor(r, n = eo) { - super(n, A(r, true)); - this.name = "UsageExceededError"; - this.code = "P5008"; + toString() { + return this.lines.join(` +`); } }; - w(Ir, "UsageExceededError"); - async function tm(e) { - let t; - try { - t = await e.text(); - } catch { - return { type: "EmptyError" }; - } - try { - let r = JSON.parse(t); - if (typeof r == "string") switch (r) { - case "InternalDataProxyError": - return { type: "DataProxyError", body: r }; - default: - return { type: "UnknownTextError", body: r }; - } - if (typeof r == "object" && r !== null) { - if ("is_panic" in r && "message" in r && "error_code" in r) return { type: "QueryEngineError", body: r }; - if ("EngineNotStarted" in r || "InteractiveTransactionMisrouted" in r || "InvalidRequestError" in r) { - let n = Object.values(r)[0].reason; - return typeof n == "string" && !["SchemaMissing", "EngineVersionNotSupported"].includes(n) ? { type: "UnknownJsonError", body: r } : { type: "DataProxyError", body: r }; - } + var yp = { red: ce, gray: Gt, dim: Oe, bold: H, underline: X, highlightSource: (e) => e.highlight() }; + var bp = { red: (e) => e, gray: (e) => e, dim: (e) => e, bold: (e) => e, underline: (e) => e, highlightSource: (e) => e }; + function Ep({ message: e, originalMethod: t, isPanic: r, callArguments: n }) { + return { functionName: `prisma.${t}()`, message: e, isPanic: r ?? false, callArguments: n }; + } + function wp({ callsite: e, message: t, originalMethod: r, isPanic: n, callArguments: i }, o) { + let s = Ep({ message: t, originalMethod: r, isPanic: n, callArguments: i }); + if (!e || typeof window < "u" || process.env.NODE_ENV === "production") return s; + let a = e.getLocation(); + if (!a || !a.lineNumber || !a.columnNumber) return s; + let l = Math.max(1, a.lineNumber - 3), u = cn.read(a.fileName)?.slice(l, a.lineNumber), c = u?.lineAt(a.lineNumber); + if (u && c) { + let p = Pp(c), d = xp(c); + if (!d) return s; + s.functionName = `${d.code})`, s.location = a, n || (u = u.mapLineAt(a.lineNumber, (g) => g.slice(0, d.openingBraceIndex))), u = o.highlightSource(u); + let f = String(u.lastLineNumber).length; + if (s.contextLines = u.mapLines((g, h) => o.gray(String(h).padStart(f)) + " " + g).mapLines((g) => o.dim(g)).prependSymbolAt(a.lineNumber, o.bold(o.red("\u2192"))), i) { + let g = p + f + 1; + g += 2, s.callArguments = (0, Ms.default)(i, g).slice(g); } - return { type: "UnknownJsonError", body: r }; - } catch { - return t === "" ? { type: "EmptyError" } : { type: "UnknownTextError", body: t }; } + return s; } - async function Or(e, t) { - if (e.ok) return; - let r = { clientVersion: t, response: e }, n = await tm(e); - if (n.type === "QueryEngineError") throw new V(n.body.message, { code: n.body.error_code, clientVersion: t }); - if (n.type === "DataProxyError") { - if (n.body === "InternalDataProxyError") throw new $t(r, "Internal Data Proxy error"); - if ("EngineNotStarted" in n.body) { - if (n.body.EngineNotStarted.reason === "SchemaMissing") return new ut(r); - if (n.body.EngineNotStarted.reason === "EngineVersionNotSupported") throw new vr(r); - if ("EngineStartupError" in n.body.EngineNotStarted.reason) { - let { msg: i, logs: o } = n.body.EngineNotStarted.reason.EngineStartupError; - throw new Pr(r, i, o); - } - if ("KnownEngineStartupError" in n.body.EngineNotStarted.reason) { - let { msg: i, error_code: o } = n.body.EngineNotStarted.reason.KnownEngineStartupError; - throw new R(i, t, o); - } - if ("HealthcheckTimeout" in n.body.EngineNotStarted.reason) { - let { logs: i } = n.body.EngineNotStarted.reason.HealthcheckTimeout; - throw new xr(r, i); - } - } - if ("InteractiveTransactionMisrouted" in n.body) { - let i = { IDParseError: "Could not parse interactive transaction ID", NoQueryEngineFoundError: "Could not find Query Engine for the specified host and transaction ID", TransactionStartError: "Could not start interactive transaction" }; - throw new Rr(r, i[n.body.InteractiveTransactionMisrouted.reason]); - } - if ("InvalidRequestError" in n.body) throw new Cr(r, n.body.InvalidRequestError.reason); + function xp(e) { + let t = Object.keys(Je.ModelAction).join("|"), n = new RegExp(String.raw`\.(${t})\(`).exec(e); + if (n) { + let i = n.index + n[0].length, o = e.lastIndexOf(" ", n.index) + 1; + return { code: e.slice(o, i), openingBraceIndex: i }; } - if (e.status === 401 || e.status === 403) throw new Ar(r, qt(Xi, n)); - if (e.status === 404) return new Sr(r, qt(Yi, n)); - if (e.status === 429) throw new Ir(r, qt(eo, n)); - if (e.status === 504) throw new Tr(r, qt(zi, n)); - if (e.status >= 500) throw new $t(r, qt(Zi, n)); - if (e.status >= 400) throw new wr(r, qt(Ki, n)); + return null; } - function qt(e, t) { - return t.type === "EmptyError" ? e : `${e}: ${JSON.stringify(t)}`; + function Pp(e) { + let t = 0; + for (let r = 0; r < e.length; r++) { + if (e.charAt(r) !== " ") return t; + t++; + } + return t; } - function nl(e) { - let t = Math.pow(2, e) * 50, r = Math.ceil(Math.random() * t) - Math.ceil(t / 2), n = t + r; - return new Promise((i) => setTimeout(() => i(n), n)); + function vp({ functionName: e, location: t, message: r, isPanic: n, contextLines: i, callArguments: o }, s) { + let a = [""], l = t ? " in" : ":"; + if (n ? (a.push(s.red(`Oops, an unknown error occurred! This is ${s.bold("on us")}, you did nothing wrong.`)), a.push(s.red(`It occurred in the ${s.bold(`\`${e}\``)} invocation${l}`))) : a.push(s.red(`Invalid ${s.bold(`\`${e}\``)} invocation${l}`)), t && a.push(s.underline(Tp(t))), i) { + a.push(""); + let u = [i.toString()]; + o && (u.push(o), u.push(s.dim(")"))), a.push(u.join("")), o && a.push(""); + } else a.push(""), o && a.push(o), a.push(""); + return a.push(r), a.join(` +`); } - var $e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - function il(e) { - let t = new TextEncoder().encode(e), r = "", n = t.byteLength, i = n % 3, o = n - i, s, a, l, u, c; - for (let p = 0; p < o; p = p + 3) c = t[p] << 16 | t[p + 1] << 8 | t[p + 2], s = (c & 16515072) >> 18, a = (c & 258048) >> 12, l = (c & 4032) >> 6, u = c & 63, r += $e[s] + $e[a] + $e[l] + $e[u]; - return i == 1 ? (c = t[o], s = (c & 252) >> 2, a = (c & 3) << 4, r += $e[s] + $e[a] + "==") : i == 2 && (c = t[o] << 8 | t[o + 1], s = (c & 64512) >> 10, a = (c & 1008) >> 4, l = (c & 15) << 2, r += $e[s] + $e[a] + $e[l] + "="), r; + function Tp(e) { + let t = [e.fileName]; + return e.lineNumber && t.push(String(e.lineNumber)), e.columnNumber && t.push(String(e.columnNumber)), t.join(":"); } - function ol(e) { - if (!!e.generator?.previewFeatures.some((r) => r.toLowerCase().includes("metrics"))) throw new R("The `metrics` preview feature is not yet available with Accelerate.\nPlease remove `metrics` from the `previewFeatures` in your schema.\n\nMore information about Accelerate: https://pris.ly/d/accelerate", e.clientVersion); + function Tt(e) { + let t = e.showColors ? yp : bp, r; + return r = wp(e, t), vp(r, t); } - function rm(e) { - return e[0] * 1e3 + e[1] / 1e6; + var Gs = k(Ai()); + function Vs(e, t, r) { + let n = Bs(e), i = Rp(n), o = Sp(i); + o ? pn(o, t, r) : t.addErrorMessage(() => "Unknown error"); } - function sl(e) { - return new Date(rm(e)); + function Bs(e) { + return e.errors.flatMap((t) => t.kind === "Union" ? Bs(t) : [t]); } - var al = { "@prisma/debug": "workspace:*", "@prisma/engines-version": "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2", "@prisma/fetch-engine": "workspace:*", "@prisma/get-platform": "workspace:*" }; - var kr = class extends se { - constructor(r, n) { - super(`Cannot fetch data from service: -${r}`, A(n, true)); - this.name = "RequestError"; - this.code = "P5010"; - } - }; - w(kr, "RequestError"); - async function ct(e, t, r = (n) => n) { - let n = t.clientVersion; - try { - return typeof fetch == "function" ? await r(fetch)(e, t) : await r(to)(e, t); - } catch (i) { - let o = i.message ?? "Unknown error"; - throw new kr(o, { clientVersion: n }); + function Rp(e) { + let t = /* @__PURE__ */ new Map(), r = []; + for (let n of e) { + if (n.kind !== "InvalidArgumentType") { + r.push(n); + continue; + } + let i = `${n.selectionPath.join(".")}:${n.argumentPath.join(".")}`, o = t.get(i); + o ? t.set(i, { ...n, argument: { ...n.argument, typeNames: Cp(o.argument.typeNames, n.argument.typeNames) } }) : t.set(i, n); } + return r.push(...t.values()), r; } - function im(e) { - return { ...e.headers, "Content-Type": "application/json" }; + function Cp(e, t) { + return [...new Set(e.concat(t))]; } - function om(e) { - return { method: e.method, headers: im(e) }; + function Sp(e) { + return xi(e, (t, r) => { + let n = qs(t), i = qs(r); + return n !== i ? n - i : js(t) - js(r); + }); } - function sm(e, t) { - return { text: () => Promise.resolve(Buffer.concat(e).toString()), json: () => Promise.resolve().then(() => JSON.parse(Buffer.concat(e).toString())), ok: t.statusCode >= 200 && t.statusCode <= 299, status: t.statusCode, url: t.url, headers: new ro(t.headers) }; + function qs(e) { + let t = 0; + return Array.isArray(e.selectionPath) && (t += e.selectionPath.length), Array.isArray(e.argumentPath) && (t += e.argumentPath.length), t; } - async function to(e, t = {}) { - let r = am("https"), n = om(t), i = [], { origin: o } = new URL(e); - return new Promise((s, a) => { - let l = r.request(e, n, (u) => { - let { statusCode: c, headers: { location: p } } = u; - c >= 301 && c <= 399 && p && (p.startsWith("http") === false ? s(to(`${o}${p}`, t)) : s(to(p, t))), u.on("data", (d) => i.push(d)), u.on("end", () => s(sm(i, u))), u.on("error", a); - }); - l.on("error", a), l.end(t.body ?? ""); - }); + function js(e) { + switch (e.kind) { + case "InvalidArgumentValue": + case "ValueTooLarge": + return 20; + case "InvalidArgumentType": + return 10; + case "RequiredArgumentMissing": + return -10; + default: + return 0; + } } - var am = typeof __require < "u" ? __require : () => { + var ue = class { + constructor(t, r) { + this.name = t; + this.value = r; + this.isRequired = false; + } + makeRequired() { + return this.isRequired = true, this; + } + write(t) { + let { colors: { green: r } } = t.context; + t.addMarginSymbol(r(this.isRequired ? "+" : "?")), t.write(r(this.name)), this.isRequired || t.write(r("?")), t.write(r(": ")), typeof this.value == "string" ? t.write(r(this.value)) : t.write(this.value); + } }; - var ro = class { - constructor(t = {}) { - this.headers = /* @__PURE__ */ new Map(); - for (let [r, n] of Object.entries(t)) if (typeof n == "string") this.headers.set(r, n); - else if (Array.isArray(n)) for (let i of n) this.headers.set(r, i); + var Rt = class { + constructor(t = 0, r) { + this.context = r; + this.lines = []; + this.currentLine = ""; + this.currentIndent = 0; + this.currentIndent = t; } - append(t, r) { - this.headers.set(t, r); + write(t) { + return typeof t == "string" ? this.currentLine += t : t.write(this), this; } - delete(t) { - this.headers.delete(t); + writeJoined(t, r, n = (i, o) => o.write(i)) { + let i = r.length - 1; + for (let o = 0; o < r.length; o++) n(r[o], this), o !== i && this.write(t); + return this; } - get(t) { - return this.headers.get(t) ?? null; + writeLine(t) { + return this.write(t).newLine(); } - has(t) { - return this.headers.has(t); + newLine() { + this.lines.push(this.indentedCurrentLine()), this.currentLine = "", this.marginSymbol = void 0; + let t = this.afterNextNewLineCallback; + return this.afterNextNewLineCallback = void 0, t?.(), this; } - set(t, r) { - this.headers.set(t, r); + withIndent(t) { + return this.indent(), t(this), this.unindent(), this; } - forEach(t, r) { - for (let [n, i] of this.headers) t.call(r, i, n, this); + afterNextNewline(t) { + return this.afterNextNewLineCallback = t, this; } - }; - var lm = /^[1-9][0-9]*\.[0-9]+\.[0-9]+$/; - var ll = L("prisma:client:dataproxyEngine"); - async function um(e, t) { - let r = al["@prisma/engines-version"], n = t.clientVersion ?? "unknown"; - if (process.env.PRISMA_CLIENT_DATA_PROXY_CLIENT_VERSION) return process.env.PRISMA_CLIENT_DATA_PROXY_CLIENT_VERSION; - if (e.includes("accelerate") && n !== "0.0.0" && n !== "in-memory") return n; - let [i, o] = n?.split("-") ?? []; - if (o === void 0 && lm.test(i)) return i; - if (o !== void 0 || n === "0.0.0" || n === "in-memory") { - if (e.startsWith("localhost") || e.startsWith("127.0.0.1")) return "0.0.0"; - let [s] = r.split("-") ?? [], [a, l, u] = s.split("."), c = cm(`<=${a}.${l}.${u}`), p = await ct(c, { clientVersion: n }); - if (!p.ok) throw new Error(`Failed to fetch stable Prisma version, unpkg.com status ${p.status} ${p.statusText}, response body: ${await p.text() || ""}`); - let d = await p.text(); - ll("length of body fetched from unpkg.com", d.length); - let f; - try { - f = JSON.parse(d); - } catch (g) { - throw console.error("JSON.parse error: body fetched from unpkg.com: ", d), g; - } - return f.version; + indent() { + return this.currentIndent++, this; } - throw new lt("Only `major.minor.patch` versions are supported by Accelerate.", { clientVersion: n }); - } - async function ul(e, t) { - let r = await um(e, t); - return ll("version", r), r; - } - function cm(e) { - return encodeURI(`https://unpkg.com/prisma@${e}/package.json`); - } - var cl = 3; - var no = L("prisma:client:dataproxyEngine"); - var io = class { - constructor({ apiKey: t, tracingHelper: r, logLevel: n, logQueries: i, engineHash: o }) { - this.apiKey = t, this.tracingHelper = r, this.logLevel = n, this.logQueries = i, this.engineHash = o; + unindent() { + return this.currentIndent > 0 && this.currentIndent--, this; } - build({ traceparent: t, interactiveTransaction: r } = {}) { - let n = { Authorization: `Bearer ${this.apiKey}`, "Prisma-Engine-Hash": this.engineHash }; - this.tracingHelper.isEnabled() && (n.traceparent = t ?? this.tracingHelper.getTraceParent()), r && (n["X-transaction-id"] = r.id); - let i = this.buildCaptureSettings(); - return i.length > 0 && (n["X-capture-telemetry"] = i.join(", ")), n; + addMarginSymbol(t) { + return this.marginSymbol = t, this; } - buildCaptureSettings() { - let t = []; - return this.tracingHelper.isEnabled() && t.push("tracing"), this.logLevel && t.push(this.logLevel), this.logQueries && t.push("query"), t; + toString() { + return this.lines.concat(this.indentedCurrentLine()).join(` +`); } - }; - var Dr = class { - constructor(t) { - this.name = "DataProxyEngine"; - ol(t), this.config = t, this.env = { ...t.env, ...typeof process < "u" ? process.env : {} }, this.inlineSchema = il(t.inlineSchema), this.inlineDatasources = t.inlineDatasources, this.inlineSchemaHash = t.inlineSchemaHash, this.clientVersion = t.clientVersion, this.engineHash = t.engineVersion, this.logEmitter = t.logEmitter, this.tracingHelper = t.tracingHelper; + getCurrentLineLength() { + return this.currentLine.length; } - apiKey() { - return this.headerBuilder.apiKey; + indentedCurrentLine() { + let t = this.currentLine.padStart(this.currentLine.length + 2 * this.currentIndent); + return this.marginSymbol ? this.marginSymbol + t.slice(1) : t; } - version() { - return this.engineHash; + }; + var dn = class { + constructor(t) { + this.value = t; } - async start() { - this.startPromise !== void 0 && await this.startPromise, this.startPromise = (async () => { - let [t, r] = this.extractHostAndApiKey(); - this.host = t, this.headerBuilder = new io({ apiKey: r, tracingHelper: this.tracingHelper, logLevel: this.config.logLevel, logQueries: this.config.logQueries, engineHash: this.engineHash }), this.remoteClientVersion = await ul(t, this.config), no("host", this.host); - })(), await this.startPromise; + write(t) { + t.write(this.value); } - async stop() { + markAsError() { + this.value.markAsError(); } - propagateResponseExtensions(t) { - t?.logs?.length && t.logs.forEach((r) => { - switch (r.level) { - case "debug": - case "error": - case "trace": - case "warn": - case "info": - break; - case "query": { - let n = typeof r.attributes.query == "string" ? r.attributes.query : ""; - if (!this.tracingHelper.isEnabled()) { - let [i] = n.split("/* traceparent"); - n = i; - } - this.logEmitter.emit("query", { query: n, timestamp: sl(r.timestamp), duration: Number(r.attributes.duration_ms), params: r.attributes.params, target: r.attributes.target }); - } - } - }), t?.traces?.length && this.tracingHelper.createEngineSpan({ span: true, spans: t.traces }); + }; + var mn = (e) => e; + var fn = { bold: mn, red: mn, green: mn, dim: mn, enabled: false }; + var Us = { bold: H, red: ce, green: qe, dim: Oe, enabled: true }; + var Ct = { write(e) { + e.writeLine(","); + } }; + var Pe = class { + constructor(t) { + this.contents = t; + this.isUnderlined = false; + this.color = (t2) => t2; } - onBeforeExit() { - throw new Error('"beforeExit" hook is not applicable to the remote query engine'); + underline() { + return this.isUnderlined = true, this; } - async url(t) { - return await this.start(), `https://${this.host}/${this.remoteClientVersion}/${this.inlineSchemaHash}/${t}`; + setColor(t) { + return this.color = t, this; } - async uploadSchema() { - let t = { name: "schemaUpload", internal: true }; - return this.tracingHelper.runInChildSpan(t, async () => { - let r = await ct(await this.url("schema"), { method: "PUT", headers: this.headerBuilder.build(), body: this.inlineSchema, clientVersion: this.clientVersion }); - r.ok || no("schema response status", r.status); - let n = await Or(r, this.clientVersion); - if (n) throw this.logEmitter.emit("warn", { message: `Error while uploading schema: ${n.message}`, timestamp: /* @__PURE__ */ new Date(), target: "" }), n; - this.logEmitter.emit("info", { message: `Schema (re)uploaded (hash: ${this.inlineSchemaHash})`, timestamp: /* @__PURE__ */ new Date(), target: "" }); + write(t) { + let r = t.getCurrentLineLength(); + t.write(this.color(this.contents)), this.isUnderlined && t.afterNextNewline(() => { + t.write(" ".repeat(r)).writeLine(this.color("~".repeat(this.contents.length))); }); } - request(t, { traceparent: r, interactiveTransaction: n, customDataProxyFetch: i }) { - return this.requestInternal({ body: t, traceparent: r, interactiveTransaction: n, customDataProxyFetch: i }); + }; + var Ye = class { + constructor() { + this.hasError = false; } - async requestBatch(t, { traceparent: r, transaction: n, customDataProxyFetch: i }) { - let o = n?.kind === "itx" ? n.options : void 0, s = Ft(t, n), { batchResult: a, elapsed: l } = await this.requestInternal({ body: s, customDataProxyFetch: i, interactiveTransaction: o, traceparent: r }); - return a.map((u) => "errors" in u && u.errors.length > 0 ? st(u.errors[0], this.clientVersion, this.config.activeProvider) : { data: u, elapsed: l }); + markAsError() { + return this.hasError = true, this; } - requestInternal({ body: t, traceparent: r, customDataProxyFetch: n, interactiveTransaction: i }) { - return this.withRetry({ actionGerund: "querying", callback: async ({ logHttpCall: o }) => { - let s = i ? `${i.payload.endpoint}/graphql` : await this.url("graphql"); - o(s); - let a = await ct(s, { method: "POST", headers: this.headerBuilder.build({ traceparent: r, interactiveTransaction: i }), body: JSON.stringify(t), clientVersion: this.clientVersion }, n); - a.ok || no("graphql response status", a.status), await this.handleError(await Or(a, this.clientVersion)); - let l = await a.json(), u = l.extensions; - if (u && this.propagateResponseExtensions(u), l.errors) throw l.errors.length === 1 ? st(l.errors[0], this.config.clientVersion, this.config.activeProvider) : new B(l.errors, { clientVersion: this.config.clientVersion }); - return l; - } }); + }; + var St = class extends Ye { + constructor() { + super(...arguments); + this.items = []; } - async transaction(t, r, n) { - let i = { start: "starting", commit: "committing", rollback: "rolling back" }; - return this.withRetry({ actionGerund: `${i[t]} transaction`, callback: async ({ logHttpCall: o }) => { - if (t === "start") { - let s = JSON.stringify({ max_wait: n.maxWait, timeout: n.timeout, isolation_level: n.isolationLevel }), a = await this.url("transaction/start"); - o(a); - let l = await ct(a, { method: "POST", headers: this.headerBuilder.build({ traceparent: r.traceparent }), body: s, clientVersion: this.clientVersion }); - await this.handleError(await Or(l, this.clientVersion)); - let u = await l.json(), c = u.extensions; - c && this.propagateResponseExtensions(c); - let p = u.id, d = u["data-proxy"].endpoint; - return { id: p, payload: { endpoint: d } }; - } else { - let s = `${n.payload.endpoint}/${t}`; - o(s); - let a = await ct(s, { method: "POST", headers: this.headerBuilder.build({ traceparent: r.traceparent }), clientVersion: this.clientVersion }); - await this.handleError(await Or(a, this.clientVersion)); - let u = (await a.json()).extensions; - u && this.propagateResponseExtensions(u); - return; - } - } }); + addItem(r) { + return this.items.push(new dn(r)), this; } - extractHostAndApiKey() { - let t = { clientVersion: this.clientVersion }, r = Object.keys(this.inlineDatasources)[0], n = Nt({ inlineDatasources: this.inlineDatasources, overrideDatasources: this.config.overrideDatasources, clientVersion: this.clientVersion, env: this.env }), i; - try { - i = new URL(n); - } catch { - throw new at(`Error validating datasource \`${r}\`: the URL must start with the protocol \`prisma://\``, t); - } - let { protocol: o, host: s, searchParams: a } = i; - if (o !== "prisma:" && o !== "prisma+postgres:") throw new at(`Error validating datasource \`${r}\`: the URL must start with the protocol \`prisma://\``, t); - let l = a.get("api_key"); - if (l === null || l.length < 1) throw new at(`Error validating datasource \`${r}\`: the URL must contain a valid API key`, t); - return [s, l]; + getField(r) { + return this.items[r]; } - metrics() { - throw new lt("Metrics are not yet supported for Accelerate", { clientVersion: this.clientVersion }); + getPrintWidth() { + return this.items.length === 0 ? 2 : Math.max(...this.items.map((n) => n.value.getPrintWidth())) + 2; } - async withRetry(t) { - for (let r = 0; ; r++) { - let n = (i) => { - this.logEmitter.emit("info", { message: `Calling ${i} (n=${r})`, timestamp: /* @__PURE__ */ new Date(), target: "" }); - }; - try { - return await t.callback({ logHttpCall: n }); - } catch (i) { - if (!(i instanceof se) || !i.isRetryable) throw i; - if (r >= cl) throw i instanceof Mt ? i.cause : i; - this.logEmitter.emit("warn", { message: `Attempt ${r + 1}/${cl} failed for ${t.actionGerund}: ${i.message ?? "(unknown)"}`, timestamp: /* @__PURE__ */ new Date(), target: "" }); - let o = await nl(r); - this.logEmitter.emit("warn", { message: `Retrying after ${o}ms`, timestamp: /* @__PURE__ */ new Date(), target: "" }); - } + write(r) { + if (this.items.length === 0) { + this.writeEmpty(r); + return; } + this.writeWithItems(r); } - async handleError(t) { - if (t instanceof ut) throw await this.uploadSchema(), new Mt({ clientVersion: this.clientVersion, cause: t }); - if (t) throw t; + writeEmpty(r) { + let n = new Pe("[]"); + this.hasError && n.setColor(r.context.colors.red).underline(), r.write(n); } - applyPendingMigrations() { - throw new Error("Method not implemented."); + writeWithItems(r) { + let { colors: n } = r.context; + r.writeLine("[").withIndent(() => r.writeJoined(Ct, this.items).newLine()).write("]"), this.hasError && r.afterNextNewline(() => { + r.writeLine(n.red("~".repeat(this.getPrintWidth()))); + }); } - }; - function pl(e) { - if (e?.kind === "itx") return e.options.id; - } - var so = k(__require("os")); - var dl = k(__require("path")); - var oo = Symbol("PrismaLibraryEngineCache"); - function pm() { - let e = globalThis; - return e[oo] === void 0 && (e[oo] = {}), e[oo]; - } - function dm(e) { - let t = pm(); - if (t[e] !== void 0) return t[e]; - let r = dl.default.toNamespacedPath(e), n = { exports: {} }, i = 0; - return process.platform !== "win32" && (i = so.default.constants.dlopen.RTLD_LAZY | so.default.constants.dlopen.RTLD_DEEPBIND), process.dlopen(n, r, i), t[e] = n.exports, n.exports; - } - var ml = { async loadLibrary(e) { - let t = await Yn(), r = await za("library", e); - try { - return e.tracingHelper.runInChildSpan({ name: "loadLibrary", internal: true }, () => dm(r)); - } catch (n) { - let i = ui({ e: n, platformInfo: t, id: r }); - throw new R(i, e.clientVersion); + asObject() { } - } }; - var ao; - var fl = { async loadLibrary(e) { - let { clientVersion: t, adapter: r, engineWasm: n } = e; - if (r === void 0) throw new R(`The \`adapter\` option for \`PrismaClient\` is required in this context (${In().prettyName})`, t); - if (n === void 0) throw new R("WASM engine was unexpectedly `undefined`", t); - ao === void 0 && (ao = (async () => { - let o = n.getRuntime(), s = await n.getQueryEngineWasmModule(); - if (s == null) throw new R("The loaded wasm module was unexpectedly `undefined` or `null` once loaded", t); - let a = { "./query_engine_bg.js": o }, l = new WebAssembly.Instance(s, a); - return o.__wbg_set_wasm(l.exports), o.QueryEngine; - })()); - let i = await ao; - return { debugPanic() { - return Promise.reject("{}"); - }, dmmf() { - return Promise.resolve("{}"); - }, version() { - return { commit: "unknown", version: "unknown" }; - }, QueryEngine: i }; - } }; - var mm = "P2036"; - var Ae = L("prisma:client:libraryEngine"); - function fm(e) { - return e.item_type === "query" && "query" in e; - } - function gm(e) { - return "level" in e ? e.level === "error" && e.message === "PANIC" : false; - } - var gl = [...Jn, "native"]; - var _r = class { - constructor(t, r) { - this.name = "LibraryEngine"; - this.libraryLoader = r ?? ml, t.engineWasm !== void 0 && (this.libraryLoader = r ?? fl), this.config = t, this.libraryStarted = false, this.logQueries = t.logQueries ?? false, this.logLevel = t.logLevel ?? "error", this.logEmitter = t.logEmitter, this.datamodel = t.inlineSchema, t.enableDebugLogs && (this.logLevel = "debug"); - let n = Object.keys(t.overrideDatasources)[0], i = t.overrideDatasources[n]?.url; - n !== void 0 && i !== void 0 && (this.datasourceOverrides = { [n]: i }), this.libraryInstantiationPromise = this.instantiateLibrary(); + }; + var At = class e extends Ye { + constructor() { + super(...arguments); + this.fields = {}; + this.suggestions = []; } - async applyPendingMigrations() { - throw new Error("Cannot call this method from this type of engine instance"); + addField(r) { + this.fields[r.name] = r; } - async transaction(t, r, n) { - await this.start(); - let i = JSON.stringify(r), o; - if (t === "start") { - let a = JSON.stringify({ max_wait: n.maxWait, timeout: n.timeout, isolation_level: n.isolationLevel }); - o = await this.engine?.startTransaction(a, i); - } else t === "commit" ? o = await this.engine?.commitTransaction(n.id, i) : t === "rollback" && (o = await this.engine?.rollbackTransaction(n.id, i)); - let s = this.parseEngineResponse(o); - if (hm(s)) { - let a = this.getExternalAdapterError(s); - throw a ? a.error : new V(s.message, { code: s.error_code, clientVersion: this.config.clientVersion, meta: s.meta }); + addSuggestion(r) { + this.suggestions.push(r); + } + getField(r) { + return this.fields[r]; + } + getDeepField(r) { + let [n, ...i] = r, o = this.getField(n); + if (!o) return; + let s = o; + for (let a of i) { + let l; + if (s.value instanceof e ? l = s.value.getField(a) : s.value instanceof St && (l = s.value.getField(Number(a))), !l) return; + s = l; } return s; } - async instantiateLibrary() { - if (Ae("internalSetup"), this.libraryInstantiationPromise) return this.libraryInstantiationPromise; - Qn(), this.binaryTarget = await this.getCurrentBinaryTarget(), await this.loadEngine(), this.version(); + getDeepFieldValue(r) { + return r.length === 0 ? this : this.getDeepField(r)?.value; } - async getCurrentBinaryTarget() { - { - if (this.binaryTarget) return this.binaryTarget; - let t = await nt(); - if (!gl.includes(t)) throw new R(`Unknown ${ce("PRISMA_QUERY_ENGINE_LIBRARY")} ${ce(H(t))}. Possible binaryTargets: ${qe(gl.join(", "))} or a path to the query engine library. -You may have to run ${qe("prisma generate")} for your changes to take effect.`, this.config.clientVersion); - return t; - } + hasField(r) { + return !!this.getField(r); } - parseEngineResponse(t) { - if (!t) throw new B("Response from the Engine was empty", { clientVersion: this.config.clientVersion }); - try { - return JSON.parse(t); - } catch { - throw new B("Unable to JSON.parse response from engine", { clientVersion: this.config.clientVersion }); - } + removeAllFields() { + this.fields = {}; } - async loadEngine() { - if (!this.engine) { - this.QueryEngineConstructor || (this.library = await this.libraryLoader.loadLibrary(this.config), this.QueryEngineConstructor = this.library.QueryEngine); - try { - let t = new WeakRef(this), { adapter: r } = this.config; - r && Ae("Using driver adapter: %O", r), this.engine = new this.QueryEngineConstructor({ datamodel: this.datamodel, env: process.env, logQueries: this.config.logQueries ?? false, ignoreEnvVarErrors: true, datasourceOverrides: this.datasourceOverrides ?? {}, logLevel: this.logLevel, configDir: this.config.cwd, engineProtocol: "json" }, (n) => { - t.deref()?.logger(n); - }, r); - } catch (t) { - let r = t, n = this.parseInitError(r.message); - throw typeof n == "string" ? r : new R(n.message, this.config.clientVersion, n.error_code); - } - } + removeField(r) { + delete this.fields[r]; } - logger(t) { - let r = this.parseEngineResponse(t); - if (r) { - if ("span" in r) { - this.config.tracingHelper.createEngineSpan(r); - return; - } - r.level = r?.level.toLowerCase() ?? "unknown", fm(r) ? this.logEmitter.emit("query", { timestamp: /* @__PURE__ */ new Date(), query: r.query, params: r.params, duration: Number(r.duration_ms), target: r.module_path }) : gm(r) ? this.loggerRustPanic = new le(lo(this, `${r.message}: ${r.reason} in ${r.file}:${r.line}:${r.column}`), this.config.clientVersion) : this.logEmitter.emit(r.level, { timestamp: /* @__PURE__ */ new Date(), message: r.message, target: r.module_path }); + getFields() { + return this.fields; + } + isEmpty() { + return Object.keys(this.fields).length === 0; + } + getFieldValue(r) { + return this.getField(r)?.value; + } + getDeepSubSelectionValue(r) { + let n = this; + for (let i of r) { + if (!(n instanceof e)) return; + let o = n.getSubSelectionValue(i); + if (!o) return; + n = o; } + return n; } - parseInitError(t) { - try { - return JSON.parse(t); - } catch { + getDeepSelectionParent(r) { + let n = this.getSelectionParent(); + if (!n) return; + let i = n; + for (let o of r) { + let s = i.value.getFieldValue(o); + if (!s || !(s instanceof e)) return; + let a = s.getSelectionParent(); + if (!a) return; + i = a; } - return t; + return i; } - parseRequestError(t) { - try { - return JSON.parse(t); - } catch { + getSelectionParent() { + let r = this.getField("select")?.value.asObject(); + if (r) return { kind: "select", value: r }; + let n = this.getField("include")?.value.asObject(); + if (n) return { kind: "include", value: n }; + } + getSubSelectionValue(r) { + return this.getSelectionParent()?.value.fields[r].value; + } + getPrintWidth() { + let r = Object.values(this.fields); + return r.length == 0 ? 2 : Math.max(...r.map((i) => i.getPrintWidth())) + 2; + } + write(r) { + let n = Object.values(this.fields); + if (n.length === 0 && this.suggestions.length === 0) { + this.writeEmpty(r); + return; } - return t; + this.writeWithContents(r, n); } - onBeforeExit() { - throw new Error('"beforeExit" hook is not applicable to the library engine since Prisma 5.0.0, it is only relevant and implemented for the binary engine. Please add your event listener to the `process` object directly instead.'); + asObject() { + return this; } - async start() { - if (await this.libraryInstantiationPromise, await this.libraryStoppingPromise, this.libraryStartingPromise) return Ae(`library already starting, this.libraryStarted: ${this.libraryStarted}`), this.libraryStartingPromise; - if (this.libraryStarted) return; - let t = async () => { - Ae("library starting"); - try { - let r = { traceparent: this.config.tracingHelper.getTraceParent() }; - await this.engine?.connect(JSON.stringify(r)), this.libraryStarted = true, Ae("library started"); - } catch (r) { - let n = this.parseInitError(r.message); - throw typeof n == "string" ? r : new R(n.message, this.config.clientVersion, n.error_code); - } finally { - this.libraryStartingPromise = void 0; - } - }; - return this.libraryStartingPromise = this.config.tracingHelper.runInChildSpan("connect", t), this.libraryStartingPromise; + writeEmpty(r) { + let n = new Pe("{}"); + this.hasError && n.setColor(r.context.colors.red).underline(), r.write(n); } - async stop() { - if (await this.libraryStartingPromise, await this.executingQueryPromise, this.libraryStoppingPromise) return Ae("library is already stopping"), this.libraryStoppingPromise; - if (!this.libraryStarted) return; - let t = async () => { - await new Promise((n) => setTimeout(n, 5)), Ae("library stopping"); - let r = { traceparent: this.config.tracingHelper.getTraceParent() }; - await this.engine?.disconnect(JSON.stringify(r)), this.libraryStarted = false, this.libraryStoppingPromise = void 0, Ae("library stopped"); - }; - return this.libraryStoppingPromise = this.config.tracingHelper.runInChildSpan("disconnect", t), this.libraryStoppingPromise; + writeWithContents(r, n) { + r.writeLine("{").withIndent(() => { + r.writeJoined(Ct, [...n, ...this.suggestions]).newLine(); + }), r.write("}"), this.hasError && r.afterNextNewline(() => { + r.writeLine(r.context.colors.red("~".repeat(this.getPrintWidth()))); + }); } - version() { - return this.versionInfo = this.library?.version(), this.versionInfo?.version ?? "unknown"; + }; + var W = class extends Ye { + constructor(r) { + super(); + this.text = r; } - debugPanic(t) { - return this.library?.debugPanic(t); + getPrintWidth() { + return this.text.length; } - async request(t, { traceparent: r, interactiveTransaction: n }) { - Ae(`sending request, this.libraryStarted: ${this.libraryStarted}`); - let i = JSON.stringify({ traceparent: r }), o = JSON.stringify(t); - try { - await this.start(), this.executingQueryPromise = this.engine?.query(o, i, n?.id), this.lastQuery = o; - let s = this.parseEngineResponse(await this.executingQueryPromise); - if (s.errors) throw s.errors.length === 1 ? this.buildQueryError(s.errors[0]) : new B(JSON.stringify(s.errors), { clientVersion: this.config.clientVersion }); - if (this.loggerRustPanic) throw this.loggerRustPanic; - return { data: s, elapsed: 0 }; - } catch (s) { - if (s instanceof R) throw s; - if (s.code === "GenericFailure" && s.message?.startsWith("PANIC:")) throw new le(lo(this, s.message), this.config.clientVersion); - let a = this.parseRequestError(s.message); - throw typeof a == "string" ? s : new B(`${a.message} -${a.backtrace}`, { clientVersion: this.config.clientVersion }); + write(r) { + let n = new Pe(this.text); + this.hasError && n.underline().setColor(r.context.colors.red), r.write(n); + } + asObject() { + } + }; + var nr = class { + constructor() { + this.fields = []; + } + addField(t, r) { + return this.fields.push({ write(n) { + let { green: i, dim: o } = n.context.colors; + n.write(i(o(`${t}: ${r}`))).addMarginSymbol(i(o("+"))); + } }), this; + } + write(t) { + let { colors: { green: r } } = t.context; + t.writeLine(r("{")).withIndent(() => { + t.writeJoined(Ct, this.fields).newLine(); + }).write(r("}")).addMarginSymbol(r("+")); + } + }; + function pn(e, t, r) { + switch (e.kind) { + case "MutuallyExclusiveFields": + Ip(e, t); + break; + case "IncludeOnScalar": + Op(e, t); + break; + case "EmptySelection": + kp(e, t, r); + break; + case "UnknownSelectionField": + Lp(e, t); + break; + case "InvalidSelectionValue": + Np(e, t); + break; + case "UnknownArgument": + Mp(e, t); + break; + case "UnknownInputField": + $p(e, t); + break; + case "RequiredArgumentMissing": + qp(e, t); + break; + case "InvalidArgumentType": + jp(e, t); + break; + case "InvalidArgumentValue": + Vp(e, t); + break; + case "ValueTooLarge": + Bp(e, t); + break; + case "SomeFieldsMissing": + Up(e, t); + break; + case "TooManyFieldsGiven": + Gp(e, t); + break; + case "Union": + Vs(e, t, r); + break; + default: + throw new Error("not implemented: " + e.kind); + } + } + function Ip(e, t) { + let r = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + r && (r.getField(e.firstField)?.markAsError(), r.getField(e.secondField)?.markAsError()), t.addErrorMessage((n) => `Please ${n.bold("either")} use ${n.green(`\`${e.firstField}\``)} or ${n.green(`\`${e.secondField}\``)}, but ${n.red("not both")} at the same time.`); + } + function Op(e, t) { + let [r, n] = ir(e.selectionPath), i = e.outputType, o = t.arguments.getDeepSelectionParent(r)?.value; + if (o && (o.getField(n)?.markAsError(), i)) for (let s of i.fields) s.isRelation && o.addSuggestion(new ue(s.name, "true")); + t.addErrorMessage((s) => { + let a = `Invalid scalar field ${s.red(`\`${n}\``)} for ${s.bold("include")} statement`; + return i ? a += ` on model ${s.bold(i.name)}. ${or(s)}` : a += ".", a += ` +Note that ${s.bold("include")} statements only accept relation fields.`, a; + }); + } + function kp(e, t, r) { + let n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + if (n) { + let i = n.getField("omit")?.value.asObject(); + if (i) { + Dp(e, t, i); + return; + } + if (n.hasField("select")) { + _p(e, t); + return; } } - async requestBatch(t, { transaction: r, traceparent: n }) { - Ae("requestBatch"); - let i = Ft(t, r); - await this.start(), this.lastQuery = JSON.stringify(i), this.executingQueryPromise = this.engine.query(this.lastQuery, JSON.stringify({ traceparent: n }), pl(r)); - let o = await this.executingQueryPromise, s = this.parseEngineResponse(o); - if (s.errors) throw s.errors.length === 1 ? this.buildQueryError(s.errors[0]) : new B(JSON.stringify(s.errors), { clientVersion: this.config.clientVersion }); - let { batchResult: a, errors: l } = s; - if (Array.isArray(a)) return a.map((u) => u.errors && u.errors.length > 0 ? this.loggerRustPanic ?? this.buildQueryError(u.errors[0]) : { data: u, elapsed: 0 }); - throw l && l.length === 1 ? new Error(l[0].error) : new Error(JSON.stringify(s)); + if (r?.[xt(e.outputType.name)]) { + Fp(e, t); + return; } - buildQueryError(t) { - if (t.user_facing_error.is_panic) return new le(lo(this, t.user_facing_error.message), this.config.clientVersion); - let r = this.getExternalAdapterError(t.user_facing_error); - return r ? r.error : st(t, this.config.clientVersion, this.config.activeProvider); + t.addErrorMessage(() => `Unknown field at "${e.selectionPath.join(".")} selection"`); + } + function Dp(e, t, r) { + r.removeAllFields(); + for (let n of e.outputType.fields) r.addSuggestion(new ue(n.name, "false")); + t.addErrorMessage((n) => `The ${n.red("omit")} statement includes every field of the model ${n.bold(e.outputType.name)}. At least one field must be included in the result`); + } + function _p(e, t) { + let r = e.outputType, n = t.arguments.getDeepSelectionParent(e.selectionPath)?.value, i = n?.isEmpty() ?? false; + n && (n.removeAllFields(), Ws(n, r)), t.addErrorMessage((o) => i ? `The ${o.red("`select`")} statement for type ${o.bold(r.name)} must not be empty. ${or(o)}` : `The ${o.red("`select`")} statement for type ${o.bold(r.name)} needs ${o.bold("at least one truthy value")}.`); + } + function Fp(e, t) { + let r = new nr(); + for (let i of e.outputType.fields) i.isRelation || r.addField(i.name, "false"); + let n = new ue("omit", r).makeRequired(); + if (e.selectionPath.length === 0) t.arguments.addSuggestion(n); + else { + let [i, o] = ir(e.selectionPath), a = t.arguments.getDeepSelectionParent(i)?.value.asObject()?.getField(o); + if (a) { + let l = a?.value.asObject() ?? new At(); + l.addSuggestion(n), a.value = l; + } } - getExternalAdapterError(t) { - if (t.error_code === mm && this.config.adapter) { - let r = t.meta?.id; - Yr(typeof r == "number", "Malformed external JS error received from the engine"); - let n = this.config.adapter.errorRegistry.consumeError(r); - return Yr(n, "External error with reported id was not registered"), n; + t.addErrorMessage((i) => `The global ${i.red("omit")} configuration excludes every field of the model ${i.bold(e.outputType.name)}. At least one field must be included in the result`); + } + function Lp(e, t) { + let r = Hs(e.selectionPath, t); + if (r.parentKind !== "unknown") { + r.field.markAsError(); + let n = r.parent; + switch (r.parentKind) { + case "select": + Ws(n, e.outputType); + break; + case "include": + Qp(n, e.outputType); + break; + case "omit": + Jp(n, e.outputType); + break; } } - async metrics(t) { - await this.start(); - let r = await this.engine.metrics(JSON.stringify(t)); - return t.format === "prometheus" ? r : this.parseEngineResponse(r); + t.addErrorMessage((n) => { + let i = [`Unknown field ${n.red(`\`${r.fieldName}\``)}`]; + return r.parentKind !== "unknown" && i.push(`for ${n.bold(r.parentKind)} statement`), i.push(`on model ${n.bold(`\`${e.outputType.name}\``)}.`), i.push(or(n)), i.join(" "); + }); + } + function Np(e, t) { + let r = Hs(e.selectionPath, t); + r.parentKind !== "unknown" && r.field.value.markAsError(), t.addErrorMessage((n) => `Invalid value for selection field \`${n.red(r.fieldName)}\`: ${e.underlyingError}`); + } + function Mp(e, t) { + let r = e.argumentPath[0], n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + n && (n.getField(r)?.markAsError(), Wp(n, e.arguments)), t.addErrorMessage((i) => Qs(i, r, e.arguments.map((o) => o.name))); + } + function $p(e, t) { + let [r, n] = ir(e.argumentPath), i = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + if (i) { + i.getDeepField(e.argumentPath)?.markAsError(); + let o = i.getDeepFieldValue(r)?.asObject(); + o && Ks(o, e.inputType); } - }; - function hm(e) { - return typeof e == "object" && e !== null && e.error_code !== void 0; + t.addErrorMessage((o) => Qs(o, n, e.inputType.fields.map((s) => s.name))); } - function lo(e, t) { - return rl({ binaryTarget: e.binaryTarget, title: t, version: e.config.clientVersion, engineVersion: e.versionInfo?.commit, database: e.config.activeProvider, query: e.lastQuery }); + function Qs(e, t, r) { + let n = [`Unknown argument \`${e.red(t)}\`.`], i = Kp(t, r); + return i && n.push(`Did you mean \`${e.green(i)}\`?`), r.length > 0 && n.push(or(e)), n.join(" "); } - function hl({ copyEngine: e = true }, t) { + function qp(e, t) { let r; - try { - r = Nt({ inlineDatasources: t.inlineDatasources, overrideDatasources: t.overrideDatasources, env: { ...t.env, ...process.env }, clientVersion: t.clientVersion }); - } catch { + t.addErrorMessage((l) => r?.value instanceof W && r.value.text === "null" ? `Argument \`${l.green(o)}\` must not be ${l.red("null")}.` : `Argument \`${l.green(o)}\` is missing.`); + let n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + if (!n) return; + let [i, o] = ir(e.argumentPath), s = new nr(), a = n.getDeepFieldValue(i)?.asObject(); + if (a) if (r = a.getField(o), r && a.removeField(o), e.inputTypes.length === 1 && e.inputTypes[0].kind === "object") { + for (let l of e.inputTypes[0].fields) s.addField(l.name, l.typeNames.join(" | ")); + a.addSuggestion(new ue(o, s).makeRequired()); + } else { + let l = e.inputTypes.map(Js).join(" | "); + a.addSuggestion(new ue(o, l).makeRequired()); } - let n = !!(r?.startsWith("prisma://") || r?.startsWith("prisma+postgres://")); - e && n && tr("recommend--no-engine", "In production, we recommend using `prisma generate --no-engine` (See: `prisma generate --help`)"); - let i = Yt(t.generator), o = n || !e, s = !!t.adapter, a = i === "library", l = i === "binary"; - if (o && s || s && false) { - let u; - throw e ? r?.startsWith("prisma://") ? u = ["Prisma Client was configured to use the `adapter` option but the URL was a `prisma://` URL.", "Please either use the `prisma://` URL or remove the `adapter` from the Prisma Client constructor."] : u = ["Prisma Client was configured to use both the `adapter` and Accelerate, please chose one."] : u = ["Prisma Client was configured to use the `adapter` option but `prisma generate` was run with `--no-engine`.", "Please run `prisma generate` without `--no-engine` to be able to use Prisma Client with the adapter."], new J(u.join(` -`), { clientVersion: t.clientVersion }); + } + function Js(e) { + return e.kind === "list" ? `${Js(e.elementType)}[]` : e.name; + } + function jp(e, t) { + let r = e.argument.name, n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + n && n.getDeepFieldValue(e.argumentPath)?.markAsError(), t.addErrorMessage((i) => { + let o = gn("or", e.argument.typeNames.map((s) => i.green(s))); + return `Argument \`${i.bold(r)}\`: Invalid value provided. Expected ${o}, provided ${i.red(e.inferredType)}.`; + }); + } + function Vp(e, t) { + let r = e.argument.name, n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + n && n.getDeepFieldValue(e.argumentPath)?.markAsError(), t.addErrorMessage((i) => { + let o = [`Invalid value for argument \`${i.bold(r)}\``]; + if (e.underlyingError && o.push(`: ${e.underlyingError}`), o.push("."), e.argument.typeNames.length > 0) { + let s = gn("or", e.argument.typeNames.map((a) => i.green(a))); + o.push(` Expected ${s}.`); + } + return o.join(""); + }); + } + function Bp(e, t) { + let r = e.argument.name, n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(), i; + if (n) { + let s = n.getDeepField(e.argumentPath)?.value; + s?.markAsError(), s instanceof W && (i = s.text); } - if (o) return new Dr(t); - if (a) return new _r(t); - throw new J("Invalid client engine type, please use `library` or `binary`", { clientVersion: t.clientVersion }); + t.addErrorMessage((o) => { + let s = ["Unable to fit value"]; + return i && s.push(o.red(i)), s.push(`into a 64-bit signed integer for field \`${o.bold(r)}\``), s.join(" "); + }); } - function Fn({ generator: e }) { - return e?.previewFeatures ?? []; + function Up(e, t) { + let r = e.argumentPath[e.argumentPath.length - 1], n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(); + if (n) { + let i = n.getDeepFieldValue(e.argumentPath)?.asObject(); + i && Ks(i, e.inputType); + } + t.addErrorMessage((i) => { + let o = [`Argument \`${i.bold(r)}\` of type ${i.bold(e.inputType.name)} needs`]; + return e.constraints.minFieldCount === 1 ? e.constraints.requiredFields ? o.push(`${i.green("at least one of")} ${gn("or", e.constraints.requiredFields.map((s) => `\`${i.bold(s)}\``))} arguments.`) : o.push(`${i.green("at least one")} argument.`) : o.push(`${i.green(`at least ${e.constraints.minFieldCount}`)} arguments.`), o.push(or(i)), o.join(" "); + }); } - var yl = (e) => ({ command: e }); - var bl = (e) => e.strings.reduce((t, r, n) => `${t}@P${n}${r}`); - function jt(e) { - try { - return El(e, "fast"); - } catch { - return El(e, "slow"); + function Gp(e, t) { + let r = e.argumentPath[e.argumentPath.length - 1], n = t.arguments.getDeepSubSelectionValue(e.selectionPath)?.asObject(), i = []; + if (n) { + let o = n.getDeepFieldValue(e.argumentPath)?.asObject(); + o && (o.markAsError(), i = Object.keys(o.getFields())); } + t.addErrorMessage((o) => { + let s = [`Argument \`${o.bold(r)}\` of type ${o.bold(e.inputType.name)} needs`]; + return e.constraints.minFieldCount === 1 && e.constraints.maxFieldCount == 1 ? s.push(`${o.green("exactly one")} argument,`) : e.constraints.maxFieldCount == 1 ? s.push(`${o.green("at most one")} argument,`) : s.push(`${o.green(`at most ${e.constraints.maxFieldCount}`)} arguments,`), s.push(`but you provided ${gn("and", i.map((a) => o.red(a)))}. Please choose`), e.constraints.maxFieldCount === 1 ? s.push("one.") : s.push(`${e.constraints.maxFieldCount}.`), s.join(" "); + }); } - function El(e, t) { - return JSON.stringify(e.map((r) => xl(r, t))); + function Ws(e, t) { + for (let r of t.fields) e.hasField(r.name) || e.addSuggestion(new ue(r.name, "true")); } - function xl(e, t) { - return Array.isArray(e) ? e.map((r) => xl(r, t)) : typeof e == "bigint" ? { prisma__type: "bigint", prisma__value: e.toString() } : Pt(e) ? { prisma__type: "date", prisma__value: e.toJSON() } : xe.isDecimal(e) ? { prisma__type: "decimal", prisma__value: e.toJSON() } : Buffer.isBuffer(e) ? { prisma__type: "bytes", prisma__value: e.toString("base64") } : ym(e) || ArrayBuffer.isView(e) ? { prisma__type: "bytes", prisma__value: Buffer.from(e).toString("base64") } : typeof e == "object" && t === "slow" ? Pl(e) : e; + function Qp(e, t) { + for (let r of t.fields) r.isRelation && !e.hasField(r.name) && e.addSuggestion(new ue(r.name, "true")); } - function ym(e) { - return e instanceof ArrayBuffer || e instanceof SharedArrayBuffer ? true : typeof e == "object" && e !== null ? e[Symbol.toStringTag] === "ArrayBuffer" || e[Symbol.toStringTag] === "SharedArrayBuffer" : false; + function Jp(e, t) { + for (let r of t.fields) !e.hasField(r.name) && !r.isRelation && e.addSuggestion(new ue(r.name, "true")); } - function Pl(e) { - if (typeof e != "object" || e === null) return e; - if (typeof e.toJSON == "function") return e.toJSON(); - if (Array.isArray(e)) return e.map(wl); - let t = {}; - for (let r of Object.keys(e)) t[r] = wl(e[r]); - return t; + function Wp(e, t) { + for (let r of t) e.hasField(r.name) || e.addSuggestion(new ue(r.name, r.typeNames.join(" | "))); + } + function Hs(e, t) { + let [r, n] = ir(e), i = t.arguments.getDeepSubSelectionValue(r)?.asObject(); + if (!i) return { parentKind: "unknown", fieldName: n }; + let o = i.getFieldValue("select")?.asObject(), s = i.getFieldValue("include")?.asObject(), a = i.getFieldValue("omit")?.asObject(), l = o?.getField(n); + return o && l ? { parentKind: "select", parent: o, field: l, fieldName: n } : (l = s?.getField(n), s && l ? { parentKind: "include", field: l, parent: s, fieldName: n } : (l = a?.getField(n), a && l ? { parentKind: "omit", field: l, parent: a, fieldName: n } : { parentKind: "unknown", fieldName: n })); + } + function Ks(e, t) { + if (t.kind === "object") for (let r of t.fields) e.hasField(r.name) || e.addSuggestion(new ue(r.name, r.typeNames.join(" | "))); + } + function ir(e) { + let t = [...e], r = t.pop(); + if (!r) throw new Error("unexpected empty path"); + return [t, r]; + } + function or({ green: e, enabled: t }) { + return "Available options are " + (t ? `listed in ${e("green")}` : "marked with ?") + "."; + } + function gn(e, t) { + if (t.length === 1) return t[0]; + let r = [...t], n = r.pop(); + return `${r.join(", ")} ${e} ${n}`; } - function wl(e) { - return typeof e == "bigint" ? e.toString() : Pl(e); + var Hp = 3; + function Kp(e, t) { + let r = 1 / 0, n; + for (let i of t) { + let o = (0, Gs.default)(e, i); + o > Hp || o < r && (r = o, n = i); + } + return n; } - var bm = ["$connect", "$disconnect", "$on", "$transaction", "$use", "$extends"]; - var vl = bm; - var Em = /^(\s*alter\s)/i; - var Tl = L("prisma:client"); - function uo(e, t, r, n) { - if (!(e !== "postgresql" && e !== "cockroachdb") && r.length > 0 && Em.exec(t)) throw new Error(`Running ALTER using ${n} is not supported -Using the example below you can still execute your query with Prisma, but please note that it is vulnerable to SQL injection attacks and requires you to take care of input sanitization. - -Example: - await prisma.$executeRawUnsafe(\`ALTER USER prisma WITH PASSWORD '\${password}'\`) - -More Information: https://pris.ly/d/execute-raw -`); + function zs(e) { + return e.substring(0, 1).toLowerCase() + e.substring(1); } - var co = ({ clientMethod: e, activeProvider: t }) => (r) => { - let n = "", i; - if (pa(r)) n = r.sql, i = { values: jt(r.values), __prismaRawParameters__: true }; - else if (Array.isArray(r)) { - let [o, ...s] = r; - n = o, i = { values: jt(s || []), __prismaRawParameters__: true }; - } else switch (t) { - case "sqlite": - case "mysql": { - n = r.sql, i = { values: jt(r.values), __prismaRawParameters__: true }; - break; - } - case "cockroachdb": - case "postgresql": - case "postgres": { - n = r.text, i = { values: jt(r.values), __prismaRawParameters__: true }; - break; - } - case "sqlserver": { - n = bl(r), i = { values: jt(r.values), __prismaRawParameters__: true }; - break; - } - default: - throw new Error(`The ${t} provider does not support ${e}`); + var sr = class { + constructor(t, r, n, i, o) { + this.modelName = t, this.name = r, this.typeName = n, this.isList = i, this.isEnum = o; + } + _toGraphQLInputType() { + let t = this.isList ? "List" : "", r = this.isEnum ? "Enum" : ""; + return `${t}${r}${this.typeName}FieldRefInput<${this.modelName}>`; } - return i?.values ? Tl(`prisma.${e}(${n}, ${i.values})`) : Tl(`prisma.${e}(${n})`), { query: n, parameters: i }; }; - var Rl = { requestArgsToMiddlewareArgs(e) { - return [e.strings, ...e.values]; - }, middlewareArgsToRequestArgs(e) { - let [t, ...r] = e; - return new oe(t, r); - } }; - var Cl = { requestArgsToMiddlewareArgs(e) { - return [e]; - }, middlewareArgsToRequestArgs(e) { - return e[0]; - } }; - function po(e) { - return function(r) { - let n, i = (o = e) => { - try { - return o === void 0 || o?.kind === "itx" ? n ??= Sl(r(o)) : Sl(r(o)); - } catch (s) { - return Promise.reject(s); - } - }; - return { then(o, s) { - return i().then(o, s); - }, catch(o) { - return i().catch(o); - }, finally(o) { - return i().finally(o); - }, requestTransaction(o) { - let s = i(o); - return s.requestTransaction ? s.requestTransaction(o) : s; - }, [Symbol.toStringTag]: "PrismaPromise" }; - }; + function It(e) { + return e instanceof sr; } - function Sl(e) { - return typeof e.then == "function" ? e : Promise.resolve(e); + var hn = Symbol(); + var Ii = /* @__PURE__ */ new WeakMap(); + var Me = class { + constructor(t) { + t === hn ? Ii.set(this, `Prisma.${this._getName()}`) : Ii.set(this, `new Prisma.${this._getNamespace()}.${this._getName()}()`); + } + _getName() { + return this.constructor.name; + } + toString() { + return Ii.get(this); + } + }; + var ar = class extends Me { + _getNamespace() { + return "NullTypes"; + } + }; + var lr = class extends ar { + }; + Oi(lr, "DbNull"); + var ur = class extends ar { + }; + Oi(ur, "JsonNull"); + var cr = class extends ar { + }; + Oi(cr, "AnyNull"); + var yn = { classes: { DbNull: lr, JsonNull: ur, AnyNull: cr }, instances: { DbNull: new lr(hn), JsonNull: new ur(hn), AnyNull: new cr(hn) } }; + function Oi(e, t) { + Object.defineProperty(e, "name", { value: t, configurable: true }); } - var Al = { isEnabled() { - return false; - }, getTraceParent() { - return "00-10-10-00"; - }, async createEngineSpan() { - }, getActiveContext() { - }, runInChildSpan(e, t) { - return t(); - } }; - var mo = class { - isEnabled() { - return this.getGlobalTracingHelper().isEnabled(); + var Ys = ": "; + var bn = class { + constructor(t, r) { + this.name = t; + this.value = r; + this.hasError = false; } - getTraceParent(t) { - return this.getGlobalTracingHelper().getTraceParent(t); + markAsError() { + this.hasError = true; } - createEngineSpan(t) { - return this.getGlobalTracingHelper().createEngineSpan(t); + getPrintWidth() { + return this.name.length + this.value.getPrintWidth() + Ys.length; } - getActiveContext() { - return this.getGlobalTracingHelper().getActiveContext(); + write(t) { + let r = new Pe(this.name); + this.hasError && r.underline().setColor(t.context.colors.red), t.write(r).write(Ys).write(this.value); } - runInChildSpan(t, r) { - return this.getGlobalTracingHelper().runInChildSpan(t, r); + }; + var ki = class { + constructor(t) { + this.errorMessages = []; + this.arguments = t; } - getGlobalTracingHelper() { - return globalThis.PRISMA_INSTRUMENTATION?.helper ?? Al; + write(t) { + t.write(this.arguments); + } + addErrorMessage(t) { + this.errorMessages.push(t); + } + renderAllMessages(t) { + return this.errorMessages.map((r) => r(t)).join(` +`); } }; - function Il(e) { - return e.includes("tracing") ? new mo() : Al; + function Ot(e) { + return new ki(Zs(e)); } - function Ol(e, t = () => { - }) { - let r, n = new Promise((i) => r = i); - return { then(i) { - return --e === 0 && r(t()), i?.(n); - } }; + function Zs(e) { + let t = new At(); + for (let [r, n] of Object.entries(e)) { + let i = new bn(r, Xs(n)); + t.addField(i); + } + return t; } - function kl(e) { - return typeof e == "string" ? e : e.reduce((t, r) => { - let n = typeof r == "string" ? r : r.level; - return n === "query" ? t : t && (r === "info" || t === "info") ? "info" : n; - }, void 0); + function Xs(e) { + if (typeof e == "string") return new W(JSON.stringify(e)); + if (typeof e == "number" || typeof e == "boolean") return new W(String(e)); + if (typeof e == "bigint") return new W(`${e}n`); + if (e === null) return new W("null"); + if (e === void 0) return new W("undefined"); + if (vt(e)) return new W(`new Prisma.Decimal("${e.toFixed()}")`); + if (e instanceof Uint8Array) return Buffer.isBuffer(e) ? new W(`Buffer.alloc(${e.byteLength})`) : new W(`new Uint8Array(${e.byteLength})`); + if (e instanceof Date) { + let t = ln(e) ? e.toISOString() : "Invalid Date"; + return new W(`new Date("${t}")`); + } + return e instanceof Me ? new W(`Prisma.${e._getName()}`) : It(e) ? new W(`prisma.${zs(e.modelName)}.$fields.${e.name}`) : Array.isArray(e) ? zp(e) : typeof e == "object" ? Zs(e) : new W(Object.prototype.toString.call(e)); } - var Ln = class { + function zp(e) { + let t = new St(); + for (let r of e) t.addItem(Xs(r)); + return t; + } + function En(e, t) { + let r = t === "pretty" ? Us : fn, n = e.renderAllMessages(r), i = new Rt(0, { colors: r }).write(e).toString(); + return { message: n, args: i }; + } + function wn({ args: e, errors: t, errorFormat: r, callsite: n, originalMethod: i, clientVersion: o, globalOmit: s }) { + let a = Ot(e); + for (let p of t) pn(p, a, s); + let { message: l, args: u } = En(a, r), c = Tt({ message: l, callsite: n, originalMethod: i, showColors: r === "pretty", callArguments: u }); + throw new J(c, { clientVersion: o }); + } + var ve = class { constructor() { - this._middlewares = []; - } - use(t) { - this._middlewares.push(t); + this._map = /* @__PURE__ */ new Map(); } get(t) { - return this._middlewares[t]; + return this._map.get(t)?.value; } - has(t) { - return !!this._middlewares[t]; + set(t, r) { + this._map.set(t, { value: r }); } - length() { - return this._middlewares.length; + getOrCreate(t, r) { + let n = this._map.get(t); + if (n) return n.value; + let i = r(); + return this.set(t, i), i; } }; - var Fl = k(bi()); - function Nn(e) { - return typeof e.batchRequestIdx == "number"; + function pr(e) { + let t; + return { get() { + return t || (t = { value: e() }), t.value; + } }; } - function Dl(e) { - if (e.action !== "findUnique" && e.action !== "findUniqueOrThrow") return; - let t = []; - return e.modelName && t.push(e.modelName), e.query.arguments && t.push(fo(e.query.arguments)), t.push(fo(e.query.selection)), t.join(""); + function Te(e) { + return e.replace(/^./, (t) => t.toLowerCase()); } - function fo(e) { - return `(${Object.keys(e).sort().map((r) => { - let n = e[r]; - return typeof n == "object" && n !== null ? `(${r} ${fo(n)})` : r; - }).join(" ")})`; + function ta(e, t, r) { + let n = Te(r); + return !t.result || !(t.result.$allModels || t.result[n]) ? e : Yp({ ...e, ...ea(t.name, e, t.result.$allModels), ...ea(t.name, e, t.result[n]) }); } - var wm = { aggregate: false, aggregateRaw: false, createMany: true, createManyAndReturn: true, createOne: true, deleteMany: true, deleteOne: true, executeRaw: true, findFirst: false, findFirstOrThrow: false, findMany: false, findRaw: false, findUnique: false, findUniqueOrThrow: false, groupBy: false, queryRaw: false, runCommandRaw: true, updateMany: true, updateOne: true, upsertOne: true }; - function go(e) { - return wm[e]; + function Yp(e) { + let t = new ve(), r = (n, i) => t.getOrCreate(n, () => i.has(n) ? [n] : (i.add(n), e[n] ? e[n].needs.flatMap((o) => r(o, i)) : [n])); + return yt(e, (n) => ({ ...n, needs: r(n.name, /* @__PURE__ */ new Set()) })); } - var Mn = class { - constructor(t) { - this.options = t; - this.tickActive = false; - this.batches = {}; + function ea(e, t, r) { + return r ? yt(r, ({ needs: n, compute: i }, o) => ({ name: o, needs: n ? Object.keys(n).filter((s) => n[s]) : [], compute: Zp(t, o, i) })) : {}; + } + function Zp(e, t, r) { + let n = e?.[t]?.compute; + return n ? (i) => r({ ...i, [t]: n(i) }) : r; + } + function ra(e, t) { + if (!t) return e; + let r = { ...e }; + for (let n of Object.values(t)) if (e[n.name]) for (let i of n.needs) r[i] = true; + return r; + } + function na(e, t) { + if (!t) return e; + let r = { ...e }; + for (let n of Object.values(t)) if (!e[n.name]) for (let i of n.needs) delete r[i]; + return r; + } + var xn = class { + constructor(t, r) { + this.extension = t; + this.previous = r; + this.computedFieldsCache = new ve(); + this.modelExtensionsCache = new ve(); + this.queryCallbacksCache = new ve(); + this.clientExtensions = pr(() => this.extension.client ? { ...this.previous?.getAllClientExtensions(), ...this.extension.client } : this.previous?.getAllClientExtensions()); + this.batchCallbacks = pr(() => { + let t2 = this.previous?.getAllBatchQueryCallbacks() ?? [], r2 = this.extension.query?.$__internalBatch; + return r2 ? t2.concat(r2) : t2; + }); } - request(t) { - let r = this.options.batchBy(t); - return r ? (this.batches[r] || (this.batches[r] = [], this.tickActive || (this.tickActive = true, process.nextTick(() => { - this.dispatchBatches(), this.tickActive = false; - }))), new Promise((n, i) => { - this.batches[r].push({ request: t, resolve: n, reject: i }); - })) : this.options.singleLoader(t); + getAllComputedFields(t) { + return this.computedFieldsCache.getOrCreate(t, () => ta(this.previous?.getAllComputedFields(t), this.extension, t)); } - dispatchBatches() { - for (let t in this.batches) { - let r = this.batches[t]; - delete this.batches[t], r.length === 1 ? this.options.singleLoader(r[0].request).then((n) => { - n instanceof Error ? r[0].reject(n) : r[0].resolve(n); - }).catch((n) => { - r[0].reject(n); - }) : (r.sort((n, i) => this.options.batchOrder(n.request, i.request)), this.options.batchLoader(r.map((n) => n.request)).then((n) => { - if (n instanceof Error) for (let i = 0; i < r.length; i++) r[i].reject(n); - else for (let i = 0; i < r.length; i++) { - let o = n[i]; - o instanceof Error ? r[i].reject(o) : r[i].resolve(o); - } - }).catch((n) => { - for (let i = 0; i < r.length; i++) r[i].reject(n); - })); - } + getAllClientExtensions() { + return this.clientExtensions.get(); } - get [Symbol.toStringTag]() { - return "DataLoader"; + getAllModelExtensions(t) { + return this.modelExtensionsCache.getOrCreate(t, () => { + let r = Te(t); + return !this.extension.model || !(this.extension.model[r] || this.extension.model.$allModels) ? this.previous?.getAllModelExtensions(t) : { ...this.previous?.getAllModelExtensions(t), ...this.extension.model.$allModels, ...this.extension.model[r] }; + }); } - }; - function pt(e, t) { - if (t === null) return t; - switch (e) { - case "bigint": - return BigInt(t); - case "bytes": - return Buffer.from(t, "base64"); - case "decimal": - return new xe(t); - case "datetime": - case "date": - return new Date(t); - case "time": - return /* @__PURE__ */ new Date(`1970-01-01T${t}Z`); - case "bigint-array": - return t.map((r) => pt("bigint", r)); - case "bytes-array": - return t.map((r) => pt("bytes", r)); - case "decimal-array": - return t.map((r) => pt("decimal", r)); - case "datetime-array": - return t.map((r) => pt("datetime", r)); - case "date-array": - return t.map((r) => pt("date", r)); - case "time-array": - return t.map((r) => pt("time", r)); - default: - return t; + getAllQueryCallbacks(t, r) { + return this.queryCallbacksCache.getOrCreate(`${t}:${r}`, () => { + let n = this.previous?.getAllQueryCallbacks(t, r) ?? [], i = [], o = this.extension.query; + return !o || !(o[t] || o.$allModels || o[r] || o.$allOperations) ? n : (o[t] !== void 0 && (o[t][r] !== void 0 && i.push(o[t][r]), o[t].$allOperations !== void 0 && i.push(o[t].$allOperations)), t !== "$none" && o.$allModels !== void 0 && (o.$allModels[r] !== void 0 && i.push(o.$allModels[r]), o.$allModels.$allOperations !== void 0 && i.push(o.$allModels.$allOperations)), o[r] !== void 0 && i.push(o[r]), o.$allOperations !== void 0 && i.push(o.$allOperations), n.concat(i)); + }); } - } - function _l(e) { - let t = [], r = xm(e); - for (let n = 0; n < e.rows.length; n++) { - let i = e.rows[n], o = { ...r }; - for (let s = 0; s < i.length; s++) o[e.columns[s]] = pt(e.types[s], i[s]); - t.push(o); + getAllBatchQueryCallbacks() { + return this.batchCallbacks.get(); } - return t; - } - function xm(e) { - let t = {}; - for (let r = 0; r < e.columns.length; r++) t[e.columns[r]] = null; - return t; - } - var Pm = L("prisma:client:request_handler"); - var $n = class { - constructor(t, r) { - this.logEmitter = r, this.client = t, this.dataloader = new Mn({ batchLoader: Ma(async ({ requests: n, customDataProxyFetch: i }) => { - let { transaction: o, otelParentCtx: s } = n[0], a = n.map((p) => p.protocolQuery), l = this.client._tracingHelper.getTraceParent(s), u = n.some((p) => go(p.protocolQuery.action)); - return (await this.client._engine.requestBatch(a, { traceparent: l, transaction: vm(o), containsWrite: u, customDataProxyFetch: i })).map((p, d) => { - if (p instanceof Error) return p; - try { - return this.mapQueryEngineResult(n[d], p); - } catch (f) { - return f; - } - }); - }), singleLoader: async (n) => { - let i = n.transaction?.kind === "itx" ? Ll(n.transaction) : void 0, o = await this.client._engine.request(n.protocolQuery, { traceparent: this.client._tracingHelper.getTraceParent(), interactiveTransaction: i, isWrite: go(n.protocolQuery.action), customDataProxyFetch: n.customDataProxyFetch }); - return this.mapQueryEngineResult(n, o); - }, batchBy: (n) => n.transaction?.id ? `transaction-${n.transaction.id}` : Dl(n.protocolQuery), batchOrder(n, i) { - return n.transaction?.kind === "batch" && i.transaction?.kind === "batch" ? n.transaction.index - i.transaction.index : 0; - } }); + }; + var kt = class e { + constructor(t) { + this.head = t; } - async request(t) { - try { - return await this.dataloader.request(t); - } catch (r) { - let { clientMethod: n, callsite: i, transaction: o, args: s, modelName: a } = t; - this.handleAndLogRequestError({ error: r, clientMethod: n, callsite: i, transaction: o, args: s, modelName: a, globalOmit: t.globalOmit }); - } + static empty() { + return new e(); } - mapQueryEngineResult({ dataPath: t, unpacker: r }, n) { - let i = n?.data, o = n?.elapsed, s = this.unpack(i, t, r); - return process.env.PRISMA_CLIENT_GET_TIME ? { data: s, elapsed: o } : s; + static single(t) { + return new e(new xn(t)); } - handleAndLogRequestError(t) { - try { - this.handleRequestError(t); - } catch (r) { - throw this.logEmitter && this.logEmitter.emit("error", { message: r.message, target: t.clientMethod, timestamp: /* @__PURE__ */ new Date() }), r; - } + isEmpty() { + return this.head === void 0; } - handleRequestError({ error: t, clientMethod: r, callsite: n, transaction: i, args: o, modelName: s, globalOmit: a }) { - if (Pm(t), Tm(t, i) || t instanceof Le) throw t; - if (t instanceof V && Rm(t)) { - let u = Nl(t.meta); - wn({ args: o, errors: [u], callsite: n, errorFormat: this.client._errorFormat, originalMethod: r, clientVersion: this.client._clientVersion, globalOmit: a }); - } - let l = t.message; - if (n && (l = Tt({ callsite: n, originalMethod: r, isPanic: t.isPanic, showColors: this.client._errorFormat === "pretty", message: l })), l = this.sanitizeMessage(l), t.code) { - let u = s ? { modelName: s, ...t.meta } : t.meta; - throw new V(l, { code: t.code, clientVersion: this.client._clientVersion, meta: u, batchRequestIdx: t.batchRequestIdx }); - } else { - if (t.isPanic) throw new le(l, this.client._clientVersion); - if (t instanceof B) throw new B(l, { clientVersion: this.client._clientVersion, batchRequestIdx: t.batchRequestIdx }); - if (t instanceof R) throw new R(l, this.client._clientVersion); - if (t instanceof le) throw new le(l, this.client._clientVersion); - } - throw t.clientVersion = this.client._clientVersion, t; + append(t) { + return new e(new xn(t, this.head)); } - sanitizeMessage(t) { - return this.client._errorFormat && this.client._errorFormat !== "pretty" ? (0, Fl.default)(t) : t; + getAllComputedFields(t) { + return this.head?.getAllComputedFields(t); } - unpack(t, r, n) { - if (!t || (t.data && (t = t.data), !t)) return t; - let i = Object.keys(t)[0], o = Object.values(t)[0], s = r.filter((u) => u !== "select" && u !== "include"), a = Gi(o, s), l = i === "queryRaw" ? _l(a) : wt(a); - return n ? n(l) : l; + getAllClientExtensions() { + return this.head?.getAllClientExtensions(); } - get [Symbol.toStringTag]() { - return "RequestHandler"; + getAllModelExtensions(t) { + return this.head?.getAllModelExtensions(t); } - }; - function vm(e) { - if (e) { - if (e.kind === "batch") return { kind: "batch", options: { isolationLevel: e.isolationLevel } }; - if (e.kind === "itx") return { kind: "itx", options: Ll(e) }; - Fe(e, "Unknown transaction kind"); + getAllQueryCallbacks(t, r) { + return this.head?.getAllQueryCallbacks(t, r) ?? []; } - } - function Ll(e) { - return { id: e.id, payload: e.payload }; - } - function Tm(e, t) { - return Nn(e) && t?.kind === "batch" && e.batchRequestIdx !== t.index; - } - function Rm(e) { - return e.code === "P2009" || e.code === "P2012"; - } - function Nl(e) { - if (e.kind === "Union") return { kind: "Union", errors: e.errors.map(Nl) }; - if (Array.isArray(e.selectionPath)) { - let [, ...t] = e.selectionPath; - return { ...e, selectionPath: t }; + getAllBatchQueryCallbacks() { + return this.head?.getAllBatchQueryCallbacks() ?? []; } - return e; - } - var Ml = "5.22.0"; - var $l = Ml; - var Ul = k(Ai()); - var F = class extends Error { + }; + var ia = Symbol(); + var dr = class { constructor(t) { - super(t + ` -Read more at https://pris.ly/d/client-constructor`), this.name = "PrismaClientConstructorValidationError"; + if (t !== ia) throw new Error("Skip instance can not be constructed directly"); } - get [Symbol.toStringTag]() { - return "PrismaClientConstructorValidationError"; + ifUndefined(t) { + return t === void 0 ? Pn : t; } }; - w(F, "PrismaClientConstructorValidationError"); - var ql = ["datasources", "datasourceUrl", "errorFormat", "adapter", "log", "transactionOptions", "omit", "__internal"]; - var jl = ["pretty", "colorless", "minimal"]; - var Vl = ["info", "query", "warn", "error"]; - var Sm = { datasources: (e, { datasourceNames: t }) => { - if (e) { - if (typeof e != "object" || Array.isArray(e)) throw new F(`Invalid value ${JSON.stringify(e)} for "datasources" provided to PrismaClient constructor`); - for (let [r, n] of Object.entries(e)) { - if (!t.includes(r)) { - let i = Vt(r, t) || ` Available datasources: ${t.join(", ")}`; - throw new F(`Unknown datasource ${r} provided to PrismaClient constructor.${i}`); - } - if (typeof n != "object" || Array.isArray(n)) throw new F(`Invalid value ${JSON.stringify(e)} for datasource "${r}" provided to PrismaClient constructor. -It should have this form: { url: "CONNECTION_STRING" }`); - if (n && typeof n == "object") for (let [i, o] of Object.entries(n)) { - if (i !== "url") throw new F(`Invalid value ${JSON.stringify(e)} for datasource "${r}" provided to PrismaClient constructor. -It should have this form: { url: "CONNECTION_STRING" }`); - if (typeof o != "string") throw new F(`Invalid value ${JSON.stringify(o)} for datasource "${r}" provided to PrismaClient constructor. -It should have this form: { url: "CONNECTION_STRING" }`); - } + var Pn = new dr(ia); + function Re(e) { + return e instanceof dr; + } + var Xp = { findUnique: "findUnique", findUniqueOrThrow: "findUniqueOrThrow", findFirst: "findFirst", findFirstOrThrow: "findFirstOrThrow", findMany: "findMany", count: "aggregate", create: "createOne", createMany: "createMany", createManyAndReturn: "createManyAndReturn", update: "updateOne", updateMany: "updateMany", upsert: "upsertOne", delete: "deleteOne", deleteMany: "deleteMany", executeRaw: "executeRaw", queryRaw: "queryRaw", aggregate: "aggregate", groupBy: "groupBy", runCommandRaw: "runCommandRaw", findRaw: "findRaw", aggregateRaw: "aggregateRaw" }; + var oa = "explicitly `undefined` values are not allowed"; + function vn({ modelName: e, action: t, args: r, runtimeDataModel: n, extensions: i = kt.empty(), callsite: o, clientMethod: s, errorFormat: a, clientVersion: l, previewFeatures: u, globalOmit: c }) { + let p = new Di({ runtimeDataModel: n, modelName: e, action: t, rootArgs: r, callsite: o, extensions: i, selectionPath: [], argumentPath: [], originalMethod: s, errorFormat: a, clientVersion: l, previewFeatures: u, globalOmit: c }); + return { modelName: e, action: Xp[t], query: mr(r, p) }; + } + function mr({ select: e, include: t, ...r } = {}, n) { + let i; + return n.isPreviewFeatureOn("omitApi") && (i = r.omit, delete r.omit), { arguments: aa(r, n), selection: ed(e, t, i, n) }; + } + function ed(e, t, r, n) { + return e ? (t ? n.throwValidationError({ kind: "MutuallyExclusiveFields", firstField: "include", secondField: "select", selectionPath: n.getSelectionPath() }) : r && n.isPreviewFeatureOn("omitApi") && n.throwValidationError({ kind: "MutuallyExclusiveFields", firstField: "omit", secondField: "select", selectionPath: n.getSelectionPath() }), id(e, n)) : td(n, t, r); + } + function td(e, t, r) { + let n = {}; + return e.modelOrType && !e.isRawAction() && (n.$composites = true, n.$scalars = true), t && rd(n, t, e), e.isPreviewFeatureOn("omitApi") && nd(n, r, e), n; + } + function rd(e, t, r) { + for (let [n, i] of Object.entries(t)) { + if (Re(i)) continue; + let o = r.nestSelection(n); + if (_i(i, o), i === false || i === void 0) { + e[n] = false; + continue; } - } - }, adapter: (e, t) => { - if (e === null) return; - if (e === void 0) throw new F('"adapter" property must not be undefined, use null to conditionally disable driver adapters.'); - if (!Fn(t).includes("driverAdapters")) throw new F('"adapter" property can only be provided to PrismaClient constructor when "driverAdapters" preview feature is enabled.'); - if (Yt() === "binary") throw new F('Cannot use a driver adapter with the "binary" Query Engine. Please use the "library" Query Engine.'); - }, datasourceUrl: (e) => { - if (typeof e < "u" && typeof e != "string") throw new F(`Invalid value ${JSON.stringify(e)} for "datasourceUrl" provided to PrismaClient constructor. -Expected string or undefined.`); - }, errorFormat: (e) => { - if (e) { - if (typeof e != "string") throw new F(`Invalid value ${JSON.stringify(e)} for "errorFormat" provided to PrismaClient constructor.`); - if (!jl.includes(e)) { - let t = Vt(e, jl); - throw new F(`Invalid errorFormat ${e} provided to PrismaClient constructor.${t}`); + let s = r.findField(n); + if (s && s.kind !== "object" && r.throwValidationError({ kind: "IncludeOnScalar", selectionPath: r.getSelectionPath().concat(n), outputType: r.getOutputTypeDescription() }), s) { + e[n] = mr(i === true ? {} : i, o); + continue; } - } - }, log: (e) => { - if (!e) return; - if (!Array.isArray(e)) throw new F(`Invalid value ${JSON.stringify(e)} for "log" provided to PrismaClient constructor.`); - function t(r) { - if (typeof r == "string" && !Vl.includes(r)) { - let n = Vt(r, Vl); - throw new F(`Invalid log level "${r}" provided to PrismaClient constructor.${n}`); + if (i === true) { + e[n] = true; + continue; } + e[n] = mr(i, o); } - for (let r of e) { - t(r); - let n = { level: t, emit: (i) => { - let o = ["stdout", "event"]; - if (!o.includes(i)) { - let s = Vt(i, o); - throw new F(`Invalid value ${JSON.stringify(i)} for "emit" in logLevel provided to PrismaClient constructor.${s}`); - } - } }; - if (r && typeof r == "object") for (let [i, o] of Object.entries(r)) if (n[i]) n[i](o); - else throw new F(`Invalid property ${i} for "log" provided to PrismaClient constructor`); + } + function nd(e, t, r) { + let n = r.getComputedFields(), i = { ...r.getGlobalOmit(), ...t }, o = na(i, n); + for (let [s, a] of Object.entries(o)) { + if (Re(a)) continue; + _i(a, r.nestSelection(s)); + let l = r.findField(s); + n?.[s] && !l || (e[s] = !a); } - }, transactionOptions: (e) => { - if (!e) return; - let t = e.maxWait; - if (t != null && t <= 0) throw new F(`Invalid value ${t} for maxWait in "transactionOptions" provided to PrismaClient constructor. maxWait needs to be greater than 0`); - let r = e.timeout; - if (r != null && r <= 0) throw new F(`Invalid value ${r} for timeout in "transactionOptions" provided to PrismaClient constructor. timeout needs to be greater than 0`); - }, omit: (e, t) => { - if (typeof e != "object") throw new F('"omit" option is expected to be an object.'); - if (e === null) throw new F('"omit" option can not be `null`'); - let r = []; - for (let [n, i] of Object.entries(e)) { - let o = Im(n, t.runtimeDataModel); - if (!o) { - r.push({ kind: "UnknownModel", modelKey: n }); - continue; - } - for (let [s, a] of Object.entries(i)) { - let l = o.fields.find((u) => u.name === s); - if (!l) { - r.push({ kind: "UnknownField", modelKey: n, fieldName: s }); + } + function id(e, t) { + let r = {}, n = t.getComputedFields(), i = ra(e, n); + for (let [o, s] of Object.entries(i)) { + if (Re(s)) continue; + let a = t.nestSelection(o); + _i(s, a); + let l = t.findField(o); + if (!(n?.[o] && !l)) { + if (s === false || s === void 0 || Re(s)) { + r[o] = false; continue; } - if (l.relationName) { - r.push({ kind: "RelationInOmit", modelKey: n, fieldName: s }); + if (s === true) { + l?.kind === "object" ? r[o] = mr({}, a) : r[o] = true; continue; } - typeof a != "boolean" && r.push({ kind: "InvalidFieldValue", modelKey: n, fieldName: s }); + r[o] = mr(s, a); } } - if (r.length > 0) throw new F(Om(e, r)); - }, __internal: (e) => { - if (!e) return; - let t = ["debug", "engine", "configOverride"]; - if (typeof e != "object") throw new F(`Invalid value ${JSON.stringify(e)} for "__internal" to PrismaClient constructor`); - for (let [r] of Object.entries(e)) if (!t.includes(r)) { - let n = Vt(r, t); - throw new F(`Invalid property ${JSON.stringify(r)} for "__internal" provided to PrismaClient constructor.${n}`); + return r; + } + function sa(e, t) { + if (e === null) return null; + if (typeof e == "string" || typeof e == "number" || typeof e == "boolean") return e; + if (typeof e == "bigint") return { $type: "BigInt", value: String(e) }; + if (Pt(e)) { + if (ln(e)) return { $type: "DateTime", value: e.toISOString() }; + t.throwValidationError({ kind: "InvalidArgumentValue", selectionPath: t.getSelectionPath(), argumentPath: t.getArgumentPath(), argument: { name: t.getArgumentName(), typeNames: ["Date"] }, underlyingError: "Provided Date object is invalid" }); } - } }; - function Gl(e, t) { - for (let [r, n] of Object.entries(e)) { - if (!ql.includes(r)) { - let i = Vt(r, ql); - throw new F(`Unknown property ${r} provided to PrismaClient constructor.${i}`); - } - Sm[r](n, t); + if (It(e)) return { $type: "FieldRef", value: { _ref: e.name, _container: e.modelName } }; + if (Array.isArray(e)) return od(e, t); + if (ArrayBuffer.isView(e)) return { $type: "Bytes", value: Buffer.from(e).toString("base64") }; + if (sd(e)) return e.values; + if (vt(e)) return { $type: "Decimal", value: e.toFixed() }; + if (e instanceof Me) { + if (e !== yn.instances[e._getName()]) throw new Error("Invalid ObjectEnumValue"); + return { $type: "Enum", value: e._getName() }; } - if (e.datasourceUrl && e.datasources) throw new F('Can not use "datasourceUrl" and "datasources" options at the same time. Pick one of them'); - } - function Vt(e, t) { - if (t.length === 0 || typeof e != "string") return ""; - let r = Am(e, t); - return r ? ` Did you mean "${r}"?` : ""; + if (ad(e)) return e.toJSON(); + if (typeof e == "object") return aa(e, t); + t.throwValidationError({ kind: "InvalidArgumentValue", selectionPath: t.getSelectionPath(), argumentPath: t.getArgumentPath(), argument: { name: t.getArgumentName(), typeNames: [] }, underlyingError: `We could not serialize ${Object.prototype.toString.call(e)} value. Serialize the object to JSON or implement a ".toJSON()" method on it` }); } - function Am(e, t) { - if (t.length === 0) return null; - let r = t.map((i) => ({ value: i, distance: (0, Ul.default)(e, i) })); - r.sort((i, o) => i.distance < o.distance ? -1 : 1); - let n = r[0]; - return n.distance < 3 ? n.value : null; + function aa(e, t) { + if (e.$type) return { $type: "Raw", value: e }; + let r = {}; + for (let n in e) { + let i = e[n], o = t.nestArgument(n); + Re(i) || (i !== void 0 ? r[n] = sa(i, o) : t.isPreviewFeatureOn("strictUndefinedChecks") && t.throwValidationError({ kind: "InvalidArgumentValue", argumentPath: o.getArgumentPath(), selectionPath: t.getSelectionPath(), argument: { name: t.getArgumentName(), typeNames: [] }, underlyingError: oa })); + } + return r; } - function Im(e, t) { - return Bl(t.models, e) ?? Bl(t.types, e); + function od(e, t) { + let r = []; + for (let n = 0; n < e.length; n++) { + let i = t.nestArgument(String(n)), o = e[n]; + if (o === void 0 || Re(o)) { + let s = o === void 0 ? "undefined" : "Prisma.skip"; + t.throwValidationError({ kind: "InvalidArgumentValue", selectionPath: i.getSelectionPath(), argumentPath: i.getArgumentPath(), argument: { name: `${t.getArgumentName()}[${n}]`, typeNames: [] }, underlyingError: `Can not use \`${s}\` value within array. Use \`null\` or filter out \`${s}\` values` }); + } + r.push(sa(o, i)); + } + return r; } - function Bl(e, t) { - let r = Object.keys(e).find((n) => xt(n) === t); - if (r) return e[r]; + function sd(e) { + return typeof e == "object" && e !== null && e.__prismaRawParameters__ === true; } - function Om(e, t) { - let r = Ot(e); - for (let o of t) switch (o.kind) { - case "UnknownModel": - r.arguments.getField(o.modelKey)?.markAsError(), r.addErrorMessage(() => `Unknown model name: ${o.modelKey}.`); - break; - case "UnknownField": - r.arguments.getDeepField([o.modelKey, o.fieldName])?.markAsError(), r.addErrorMessage(() => `Model "${o.modelKey}" does not have a field named "${o.fieldName}".`); - break; - case "RelationInOmit": - r.arguments.getDeepField([o.modelKey, o.fieldName])?.markAsError(), r.addErrorMessage(() => 'Relations are already excluded by default and can not be specified in "omit".'); - break; - case "InvalidFieldValue": - r.arguments.getDeepFieldValue([o.modelKey, o.fieldName])?.markAsError(), r.addErrorMessage(() => "Omit field option value must be a boolean."); - break; - } - let { message: n, args: i } = En(r, "colorless"); - return `Error validating "omit" option: - -${i} - -${n}`; + function ad(e) { + return typeof e == "object" && e !== null && typeof e.toJSON == "function"; } - function Ql(e) { - return e.length === 0 ? Promise.resolve([]) : new Promise((t, r) => { - let n = new Array(e.length), i = null, o = false, s = 0, a = () => { - o || (s++, s === e.length && (o = true, i ? r(i) : t(n))); - }, l = (u) => { - o || (o = true, r(u)); - }; - for (let u = 0; u < e.length; u++) e[u].then((c) => { - n[u] = c, a(); - }, (c) => { - if (!Nn(c)) { - l(c); - return; - } - c.batchRequestIdx === u ? l(c) : (i || (i = c), a()); - }); - }); + function _i(e, t) { + e === void 0 && t.isPreviewFeatureOn("strictUndefinedChecks") && t.throwValidationError({ kind: "InvalidSelectionValue", selectionPath: t.getSelectionPath(), underlyingError: oa }); } - var tt = L("prisma:client"); - typeof globalThis == "object" && (globalThis.NODE_CLIENT = true); - var km = { requestArgsToMiddlewareArgs: (e) => e, middlewareArgsToRequestArgs: (e) => e }; - var Dm = Symbol.for("prisma.client.transaction.id"); - var _m = { id: 0, nextId() { - return ++this.id; - } }; - function Yl(e) { - class t { - constructor(n) { - this._originalClient = this; - this._middlewares = new Ln(); - this._createPrismaPromise = po(); - this.$extends = Ia; - e = n?.__internal?.configOverride?.(e) ?? e, Ba(e), n && Gl(n, e); - let i = new Kl.EventEmitter().on("error", () => { - }); - this._extensions = kt.empty(), this._previewFeatures = Fn(e), this._clientVersion = e.clientVersion ?? $l, this._activeProvider = e.activeProvider, this._globalOmit = n?.omit, this._tracingHelper = Il(this._previewFeatures); - let o = { rootEnvPath: e.relativeEnvPaths.rootEnvPath && Fr.default.resolve(e.dirname, e.relativeEnvPaths.rootEnvPath), schemaEnvPath: e.relativeEnvPaths.schemaEnvPath && Fr.default.resolve(e.dirname, e.relativeEnvPaths.schemaEnvPath) }, s; - if (n?.adapter) { - s = qi(n.adapter); - let l = e.activeProvider === "postgresql" ? "postgres" : e.activeProvider; - if (s.provider !== l) throw new R(`The Driver Adapter \`${s.adapterName}\`, based on \`${s.provider}\`, is not compatible with the provider \`${l}\` specified in the Prisma schema.`, this._clientVersion); - if (n.datasources || n.datasourceUrl !== void 0) throw new R("Custom datasource configuration is not compatible with Prisma Driver Adapters. Please define the database connection string directly in the Driver Adapter configuration.", this._clientVersion); - } - let a = !s && zt(o, { conflictCheck: "none" }) || e.injectableEdgeEnv?.(); - try { - let l = n ?? {}, u = l.__internal ?? {}, c = u.debug === true; - c && L.enable("prisma:client"); - let p = Fr.default.resolve(e.dirname, e.relativePath); - zl.default.existsSync(p) || (p = e.dirname), tt("dirname", e.dirname), tt("relativePath", e.relativePath), tt("cwd", p); - let d = u.engine || {}; - if (l.errorFormat ? this._errorFormat = l.errorFormat : process.env.NODE_ENV === "production" ? this._errorFormat = "minimal" : process.env.NO_COLOR ? this._errorFormat = "colorless" : this._errorFormat = "colorless", this._runtimeDataModel = e.runtimeDataModel, this._engineConfig = { cwd: p, dirname: e.dirname, enableDebugLogs: c, allowTriggerPanic: d.allowTriggerPanic, datamodelPath: Fr.default.join(e.dirname, e.filename ?? "schema.prisma"), prismaPath: d.binaryPath ?? void 0, engineEndpoint: d.endpoint, generator: e.generator, showColors: this._errorFormat === "pretty", logLevel: l.log && kl(l.log), logQueries: l.log && !!(typeof l.log == "string" ? l.log === "query" : l.log.find((f) => typeof f == "string" ? f === "query" : f.level === "query")), env: a?.parsed ?? {}, flags: [], engineWasm: e.engineWasm, clientVersion: e.clientVersion, engineVersion: e.engineVersion, previewFeatures: this._previewFeatures, activeProvider: e.activeProvider, inlineSchema: e.inlineSchema, overrideDatasources: Ua(l, e.datasourceNames), inlineDatasources: e.inlineDatasources, inlineSchemaHash: e.inlineSchemaHash, tracingHelper: this._tracingHelper, transactionOptions: { maxWait: l.transactionOptions?.maxWait ?? 2e3, timeout: l.transactionOptions?.timeout ?? 5e3, isolationLevel: l.transactionOptions?.isolationLevel }, logEmitter: i, isBundled: e.isBundled, adapter: s }, this._accelerateEngineConfig = { ...this._engineConfig, accelerateUtils: { resolveDatasourceUrl: Nt, getBatchRequestPayload: Ft, prismaGraphQLToJSError: st, PrismaClientUnknownRequestError: B, PrismaClientInitializationError: R, PrismaClientKnownRequestError: V, debug: L("prisma:client:accelerateEngine"), engineVersion: Wl.version, clientVersion: e.clientVersion } }, tt("clientVersion", e.clientVersion), this._engine = hl(e, this._engineConfig), this._requestHandler = new $n(this, i), l.log) for (let f of l.log) { - let g = typeof f == "string" ? f : f.emit === "stdout" ? f.level : null; - g && this.$on(g, (h) => { - er.log(`${er.tags[g] ?? ""}`, h.message || h.query); - }); - } - this._metrics = new Dt(this._engine); - } catch (l) { - throw l.clientVersion = this._clientVersion, l; - } - return this._appliedParent = yr(this); - } - get [Symbol.toStringTag]() { - return "PrismaClient"; - } - $use(n) { - this._middlewares.use(n); - } - $on(n, i) { - n === "beforeExit" ? this._engine.onBeforeExit(i) : n && this._engineConfig.logEmitter.on(n, i); - } - $connect() { - try { - return this._engine.start(); - } catch (n) { - throw n.clientVersion = this._clientVersion, n; - } - } - async $disconnect() { - try { - await this._engine.stop(); - } catch (n) { - throw n.clientVersion = this._clientVersion, n; - } finally { - Ao(); - } - } - $executeRawInternal(n, i, o, s) { - let a = this._activeProvider; - return this._request({ action: "executeRaw", args: o, transaction: n, clientMethod: i, argsMapper: co({ clientMethod: i, activeProvider: a }), callsite: Ze(this._errorFormat), dataPath: [], middlewareArgsMapper: s }); - } - $executeRaw(n, ...i) { - return this._createPrismaPromise((o) => { - if (n.raw !== void 0 || n.sql !== void 0) { - let [s, a] = Jl(n, i); - return uo(this._activeProvider, s.text, s.values, Array.isArray(n) ? "prisma.$executeRaw``" : "prisma.$executeRaw(sql``)"), this.$executeRawInternal(o, "$executeRaw", s, a); - } - throw new J("`$executeRaw` is a tag function, please use it like the following:\n```\nconst result = await prisma.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};`\n```\n\nOr read our docs at https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#executeraw\n", { clientVersion: this._clientVersion }); - }); - } - $executeRawUnsafe(n, ...i) { - return this._createPrismaPromise((o) => (uo(this._activeProvider, n, i, "prisma.$executeRawUnsafe(, [...values])"), this.$executeRawInternal(o, "$executeRawUnsafe", [n, ...i]))); - } - $runCommandRaw(n) { - if (e.activeProvider !== "mongodb") throw new J(`The ${e.activeProvider} provider does not support $runCommandRaw. Use the mongodb provider.`, { clientVersion: this._clientVersion }); - return this._createPrismaPromise((i) => this._request({ args: n, clientMethod: "$runCommandRaw", dataPath: [], action: "runCommandRaw", argsMapper: yl, callsite: Ze(this._errorFormat), transaction: i })); - } - async $queryRawInternal(n, i, o, s) { - let a = this._activeProvider; - return this._request({ action: "queryRaw", args: o, transaction: n, clientMethod: i, argsMapper: co({ clientMethod: i, activeProvider: a }), callsite: Ze(this._errorFormat), dataPath: [], middlewareArgsMapper: s }); - } - $queryRaw(n, ...i) { - return this._createPrismaPromise((o) => { - if (n.raw !== void 0 || n.sql !== void 0) return this.$queryRawInternal(o, "$queryRaw", ...Jl(n, i)); - throw new J("`$queryRaw` is a tag function, please use it like the following:\n```\nconst result = await prisma.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};`\n```\n\nOr read our docs at https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#queryraw\n", { clientVersion: this._clientVersion }); - }); - } - $queryRawTyped(n) { - return this._createPrismaPromise((i) => { - if (!this._hasPreviewFlag("typedSql")) throw new J("`typedSql` preview feature must be enabled in order to access $queryRawTyped API", { clientVersion: this._clientVersion }); - return this.$queryRawInternal(i, "$queryRawTyped", n); - }); - } - $queryRawUnsafe(n, ...i) { - return this._createPrismaPromise((o) => this.$queryRawInternal(o, "$queryRawUnsafe", [n, ...i])); - } - _transactionWithArray({ promises: n, options: i }) { - let o = _m.nextId(), s = Ol(n.length), a = n.map((l, u) => { - if (l?.[Symbol.toStringTag] !== "PrismaPromise") throw new Error("All elements of the array need to be Prisma Client promises. Hint: Please make sure you are not awaiting the Prisma client calls you intended to pass in the $transaction function."); - let c = i?.isolationLevel ?? this._engineConfig.transactionOptions.isolationLevel, p = { kind: "batch", id: o, index: u, isolationLevel: c, lock: s }; - return l.requestTransaction?.(p) ?? l; - }); - return Ql(a); - } - async _transactionWithCallback({ callback: n, options: i }) { - let o = { traceparent: this._tracingHelper.getTraceParent() }, s = { maxWait: i?.maxWait ?? this._engineConfig.transactionOptions.maxWait, timeout: i?.timeout ?? this._engineConfig.transactionOptions.timeout, isolationLevel: i?.isolationLevel ?? this._engineConfig.transactionOptions.isolationLevel }, a = await this._engine.transaction("start", o, s), l; - try { - let u = { kind: "itx", ...a }; - l = await n(this._createItxClient(u)), await this._engine.transaction("commit", o, a); - } catch (u) { - throw await this._engine.transaction("rollback", o, a).catch(() => { - }), u; - } - return l; - } - _createItxClient(n) { - return yr(Se(Aa(this), [re("_appliedParent", () => this._appliedParent._createItxClient(n)), re("_createPrismaPromise", () => po(n)), re(Dm, () => n.id), _t(vl)])); - } - $transaction(n, i) { - let o; - typeof n == "function" ? this._engineConfig.adapter?.adapterName === "@prisma/adapter-d1" ? o = () => { - throw new Error("Cloudflare D1 does not support interactive transactions. We recommend you to refactor your queries with that limitation in mind, and use batch transactions with `prisma.$transactions([])` where applicable."); - } : o = () => this._transactionWithCallback({ callback: n, options: i }) : o = () => this._transactionWithArray({ promises: n, options: i }); - let s = { name: "transaction", attributes: { method: "$transaction" } }; - return this._tracingHelper.runInChildSpan(s, o); - } - _request(n) { - n.otelParentCtx = this._tracingHelper.getActiveContext(); - let i = n.middlewareArgsMapper ?? km, o = { args: i.requestArgsToMiddlewareArgs(n.args), dataPath: n.dataPath, runInTransaction: !!n.transaction, action: n.action, model: n.model }, s = { middleware: { name: "middleware", middleware: true, attributes: { method: "$use" }, active: false }, operation: { name: "operation", attributes: { method: o.action, model: o.model, name: o.model ? `${o.model}.${o.action}` : o.action } } }, a = -1, l = async (u) => { - let c = this._middlewares.get(++a); - if (c) return this._tracingHelper.runInChildSpan(s.middleware, (O) => c(u, (T) => (O?.end(), l(T)))); - let { runInTransaction: p, args: d, ...f } = u, g = { ...n, ...f }; - d && (g.args = i.middlewareArgsToRequestArgs(d)), n.transaction !== void 0 && p === false && delete g.transaction; - let h = await Na(this, g); - return g.model ? Da({ result: h, modelName: g.model, args: g.args, extensions: this._extensions, runtimeDataModel: this._runtimeDataModel, globalOmit: this._globalOmit }) : h; - }; - return this._tracingHelper.runInChildSpan(s.operation, () => new Hl.AsyncResource("prisma-client-request").runInAsyncScope(() => l(o))); - } - async _executeRequest({ args: n, clientMethod: i, dataPath: o, callsite: s, action: a, model: l, argsMapper: u, transaction: c, unpacker: p, otelParentCtx: d, customDataProxyFetch: f }) { - try { - n = u ? u(n) : n; - let g = { name: "serialize" }, h = this._tracingHelper.runInChildSpan(g, () => vn({ modelName: l, runtimeDataModel: this._runtimeDataModel, action: a, args: n, clientMethod: i, callsite: s, extensions: this._extensions, errorFormat: this._errorFormat, clientVersion: this._clientVersion, previewFeatures: this._previewFeatures, globalOmit: this._globalOmit })); - return L.enabled("prisma:client") && (tt("Prisma Client call:"), tt(`prisma.${i}(${ha(n)})`), tt("Generated request:"), tt(JSON.stringify(h, null, 2) + ` -`)), c?.kind === "batch" && await c.lock, this._requestHandler.request({ protocolQuery: h, modelName: l, action: a, clientMethod: i, dataPath: o, callsite: s, args: n, extensions: this._extensions, transaction: c, unpacker: p, otelParentCtx: d, otelChildCtx: this._tracingHelper.getActiveContext(), globalOmit: this._globalOmit, customDataProxyFetch: f }); - } catch (g) { - throw g.clientVersion = this._clientVersion, g; - } - } - get $metrics() { - if (!this._hasPreviewFlag("metrics")) throw new J("`metrics` preview feature must be enabled in order to access metrics API", { clientVersion: this._clientVersion }); - return this._metrics; - } - _hasPreviewFlag(n) { - return !!this._engineConfig.previewFeatures?.includes(n); - } - $applyPendingMigrations() { - return this._engine.applyPendingMigrations(); + var Di = class e { + constructor(t) { + this.params = t; + this.params.modelName && (this.modelOrType = this.params.runtimeDataModel.models[this.params.modelName] ?? this.params.runtimeDataModel.types[this.params.modelName]); + } + throwValidationError(t) { + wn({ errors: [t], originalMethod: this.params.originalMethod, args: this.params.rootArgs ?? {}, callsite: this.params.callsite, errorFormat: this.params.errorFormat, clientVersion: this.params.clientVersion, globalOmit: this.params.globalOmit }); + } + getSelectionPath() { + return this.params.selectionPath; + } + getArgumentPath() { + return this.params.argumentPath; + } + getArgumentName() { + return this.params.argumentPath[this.params.argumentPath.length - 1]; + } + getOutputTypeDescription() { + if (!(!this.params.modelName || !this.modelOrType)) return { name: this.params.modelName, fields: this.modelOrType.fields.map((t) => ({ name: t.name, typeName: "boolean", isRelation: t.kind === "object" })) }; + } + isRawAction() { + return ["executeRaw", "queryRaw", "runCommandRaw", "findRaw", "aggregateRaw"].includes(this.params.action); + } + isPreviewFeatureOn(t) { + return this.params.previewFeatures.includes(t); + } + getComputedFields() { + if (this.params.modelName) return this.params.extensions.getAllComputedFields(this.params.modelName); + } + findField(t) { + return this.modelOrType?.fields.find((r) => r.name === t); + } + nestSelection(t) { + let r = this.findField(t), n = r?.kind === "object" ? r.type : void 0; + return new e({ ...this.params, modelName: n, selectionPath: this.params.selectionPath.concat(t) }); + } + getGlobalOmit() { + return this.params.modelName && this.shouldApplyGlobalOmit() ? this.params.globalOmit?.[xt(this.params.modelName)] ?? {} : {}; + } + shouldApplyGlobalOmit() { + switch (this.params.action) { + case "findFirst": + case "findFirstOrThrow": + case "findUniqueOrThrow": + case "findMany": + case "upsert": + case "findUnique": + case "createManyAndReturn": + case "create": + case "update": + case "delete": + return true; + case "executeRaw": + case "aggregateRaw": + case "runCommandRaw": + case "findRaw": + case "createMany": + case "deleteMany": + case "groupBy": + case "updateMany": + case "count": + case "aggregate": + case "queryRaw": + return false; + default: + Fe(this.params.action, "Unknown action"); } } + nestArgument(t) { + return new e({ ...this.params, argumentPath: this.params.argumentPath.concat(t) }); + } + }; + var Dt = class { + constructor(t) { + this._engine = t; + } + prometheus(t) { + return this._engine.metrics({ format: "prometheus", ...t }); + } + json(t) { + return this._engine.metrics({ format: "json", ...t }); + } + }; + function la(e) { + return { models: Fi(e.models), enums: Fi(e.enums), types: Fi(e.types) }; + } + function Fi(e) { + let t = {}; + for (let { name: r, ...n } of e) t[r] = n; return t; } - function Jl(e, t) { - return Fm(e) ? [new oe(e, t), Rl] : [e, Cl]; + function ua(e, t) { + let r = pr(() => ld(t)); + Object.defineProperty(e, "dmmf", { get: () => r.get() }); + } + function ld(e) { + return { datamodel: { models: Li(e.models), enums: Li(e.enums), types: Li(e.types) } }; } - function Fm(e) { - return Array.isArray(e) && Array.isArray(e.raw); + function Li(e) { + return Object.entries(e).map(([t, r]) => ({ name: t, ...r })); } - var Lm = /* @__PURE__ */ new Set(["toJSON", "$$typeof", "asymmetricMatch", Symbol.iterator, Symbol.toStringTag, Symbol.isConcatSpreadable, Symbol.toPrimitive]); - function Zl(e) { - return new Proxy(e, { get(t, r) { - if (r in t) return t[r]; - if (!Lm.has(r)) throw new TypeError(`Invalid enum value: ${String(r)}`); - } }); + var Ni = /* @__PURE__ */ new WeakMap(); + var Tn = "$$PrismaTypedSql"; + var Mi = class { + constructor(t, r) { + Ni.set(this, { sql: t, values: r }), Object.defineProperty(this, Tn, { value: Tn }); + } + get sql() { + return Ni.get(this).sql; + } + get values() { + return Ni.get(this).values; + } + }; + function ca(e) { + return (...t) => new Mi(e, t); } - function Xl(e) { - zt(e, { conflictCheck: "warn" }); + function pa(e) { + return e != null && e[Tn] === Tn; } - } -}); - -// node_modules/.prisma/client/index.js -var require_client = __commonJS({ - "node_modules/.prisma/client/index.js"(exports2) { - Object.defineProperty(exports2, "__esModule", { value: true }); - var { - PrismaClientKnownRequestError: PrismaClientKnownRequestError2, - PrismaClientUnknownRequestError: PrismaClientUnknownRequestError2, - PrismaClientRustPanicError: PrismaClientRustPanicError2, - PrismaClientInitializationError: PrismaClientInitializationError2, - PrismaClientValidationError: PrismaClientValidationError2, - NotFoundError: NotFoundError3, - getPrismaClient: getPrismaClient2, - sqltag: sqltag2, - empty: empty2, - join: join2, - raw: raw2, - skip: skip2, - Decimal: Decimal2, - Debug: Debug2, - objectEnumValues: objectEnumValues2, - makeStrictEnum: makeStrictEnum2, - Extensions: Extensions2, - warnOnce: warnOnce2, - defineDmmfProperty: defineDmmfProperty2, - Public: Public2, - getRuntime: getRuntime2 - } = require_library(); - var Prisma = {}; - exports2.Prisma = Prisma; - exports2.$Enums = {}; - Prisma.prismaVersion = { - client: "5.22.0", - engine: "605197351a3c8bdd595af2d2a9bc3025bca48ea2" - }; - Prisma.PrismaClientKnownRequestError = PrismaClientKnownRequestError2; - Prisma.PrismaClientUnknownRequestError = PrismaClientUnknownRequestError2; - Prisma.PrismaClientRustPanicError = PrismaClientRustPanicError2; - Prisma.PrismaClientInitializationError = PrismaClientInitializationError2; - Prisma.PrismaClientValidationError = PrismaClientValidationError2; - Prisma.NotFoundError = NotFoundError3; - Prisma.Decimal = Decimal2; - Prisma.sql = sqltag2; - Prisma.empty = empty2; - Prisma.join = join2; - Prisma.raw = raw2; - Prisma.validator = Public2.validator; - Prisma.getExtensionContext = Extensions2.getExtensionContext; - Prisma.defineExtension = Extensions2.defineExtension; - Prisma.DbNull = objectEnumValues2.instances.DbNull; - Prisma.JsonNull = objectEnumValues2.instances.JsonNull; - Prisma.AnyNull = objectEnumValues2.instances.AnyNull; - Prisma.NullTypes = { - DbNull: objectEnumValues2.classes.DbNull, - JsonNull: objectEnumValues2.classes.JsonNull, - AnyNull: objectEnumValues2.classes.AnyNull - }; - var path = __require("path"); - exports2.Prisma.TransactionIsolationLevel = makeStrictEnum2({ - Serializable: "Serializable" - }); - exports2.Prisma.BlockCheckpointScalarFieldEnum = { - id: "id", - network: "network", - blockNumber: "blockNumber", - timestamp: "timestamp" + function fr(e) { + return { ok: false, error: e, map() { + return fr(e); + }, flatMap() { + return fr(e); + } }; + } + var $i = class { + constructor() { + this.registeredErrors = []; + } + consumeError(t) { + return this.registeredErrors[t]; + } + registerNewError(t) { + let r = 0; + for (; this.registeredErrors[r] !== void 0; ) r++; + return this.registeredErrors[r] = { error: t }, r; + } }; - exports2.Prisma.SortOrder = { - asc: "asc", - desc: "desc" + var qi = (e) => { + let t = new $i(), r = Ce(t, e.transactionContext.bind(e)), n = { adapterName: e.adapterName, errorRegistry: t, queryRaw: Ce(t, e.queryRaw.bind(e)), executeRaw: Ce(t, e.executeRaw.bind(e)), provider: e.provider, transactionContext: async (...i) => (await r(...i)).map((s) => ud(t, s)) }; + return e.getConnectionInfo && (n.getConnectionInfo = pd(t, e.getConnectionInfo.bind(e))), n; }; - exports2.Prisma.ModelName = { - BlockCheckpoint: "BlockCheckpoint" + var ud = (e, t) => { + let r = Ce(e, t.startTransaction.bind(t)); + return { adapterName: t.adapterName, provider: t.provider, queryRaw: Ce(e, t.queryRaw.bind(t)), executeRaw: Ce(e, t.executeRaw.bind(t)), startTransaction: async (...n) => (await r(...n)).map((o) => cd(e, o)) }; }; - var config3 = { - "generator": { - "name": "client", - "provider": { - "fromEnvVar": null, - "value": "prisma-client-js" - }, - "output": { - "value": "/Users/oleg/Documents/Code/concero/v2-operators/node_modules/@prisma/client", - "fromEnvVar": null - }, - "config": { - "engineType": "library" - }, - "binaryTargets": [ - { - "fromEnvVar": null, - "value": "darwin-arm64", - "native": true - } - ], - "previewFeatures": [], - "sourceFilePath": "/Users/oleg/Documents/Code/concero/v2-operators/prisma/schema.prisma" - }, - "relativeEnvPaths": { - "rootEnvPath": null, - "schemaEnvPath": "../../../.env" - }, - "relativePath": "../../../prisma", - "clientVersion": "5.22.0", - "engineVersion": "605197351a3c8bdd595af2d2a9bc3025bca48ea2", - "datasourceNames": [ - "db" - ], - "activeProvider": "sqlite", - "postinstall": false, - "inlineDatasources": { - "db": { - "url": { - "fromEnvVar": null, - "value": "file:./block-checkpoints.db" - } + var cd = (e, t) => ({ adapterName: t.adapterName, provider: t.provider, options: t.options, queryRaw: Ce(e, t.queryRaw.bind(t)), executeRaw: Ce(e, t.executeRaw.bind(t)), commit: Ce(e, t.commit.bind(t)), rollback: Ce(e, t.rollback.bind(t)) }); + function Ce(e, t) { + return async (...r) => { + try { + return await t(...r); + } catch (n) { + let i = e.registerNewError(n); + return fr({ kind: "GenericJs", id: i }); } - }, - "inlineSchema": 'generator client {\n provider = "prisma-client-js"\n}\n\ndatasource db {\n provider = "sqlite"\n url = "file:./block-checkpoints.db"\n}\n\nmodel BlockCheckpoint {\n id Int @id @default(autoincrement())\n network String @unique\n blockNumber BigInt\n timestamp DateTime @default(now())\n}\n', - "inlineSchemaHash": "bd1c73e8e712d1b9b3e8c8468e4ed2988c6ff6026cedd767f8cb6f8ca4afe408", - "copyEngine": true - }; - var fs2 = __require("fs"); - config3.dirname = __dirname; - if (!fs2.existsSync(path.join(__dirname, "schema.prisma"))) { - const alternativePaths = [ - "node_modules/.prisma/client", - ".prisma/client" - ]; - const alternativePath = alternativePaths.find((altPath) => { - return fs2.existsSync(path.join(process.cwd(), altPath, "schema.prisma")); - }) ?? alternativePaths[0]; - config3.dirname = path.join(process.cwd(), alternativePath); - config3.isBundled = true; - } - config3.runtimeDataModel = JSON.parse('{"models":{"BlockCheckpoint":{"dbName":null,"fields":[{"name":"id","kind":"scalar","isList":false,"isRequired":true,"isUnique":false,"isId":true,"isReadOnly":false,"hasDefaultValue":true,"type":"Int","default":{"name":"autoincrement","args":[]},"isGenerated":false,"isUpdatedAt":false},{"name":"network","kind":"scalar","isList":false,"isRequired":true,"isUnique":true,"isId":false,"isReadOnly":false,"hasDefaultValue":false,"type":"String","isGenerated":false,"isUpdatedAt":false},{"name":"blockNumber","kind":"scalar","isList":false,"isRequired":true,"isUnique":false,"isId":false,"isReadOnly":false,"hasDefaultValue":false,"type":"BigInt","isGenerated":false,"isUpdatedAt":false},{"name":"timestamp","kind":"scalar","isList":false,"isRequired":true,"isUnique":false,"isId":false,"isReadOnly":false,"hasDefaultValue":true,"type":"DateTime","default":{"name":"now","args":[]},"isGenerated":false,"isUpdatedAt":false}],"primaryKey":null,"uniqueFields":[],"uniqueIndexes":[],"isGenerated":false}},"enums":{},"types":{}}'); - defineDmmfProperty2(exports2.Prisma, config3.runtimeDataModel); - config3.engineWasm = void 0; - var { warnEnvConflicts: warnEnvConflicts2 } = require_library(); - warnEnvConflicts2({ - rootEnvPath: config3.relativeEnvPaths.rootEnvPath && path.resolve(config3.dirname, config3.relativeEnvPaths.rootEnvPath), - schemaEnvPath: config3.relativeEnvPaths.schemaEnvPath && path.resolve(config3.dirname, config3.relativeEnvPaths.schemaEnvPath) - }); - var PrismaClient2 = getPrismaClient2(config3); - exports2.PrismaClient = PrismaClient2; - Object.assign(exports2, Prisma); - path.join(__dirname, "libquery_engine-darwin-arm64.dylib.node"); - path.join(process.cwd(), "node_modules/.prisma/client/libquery_engine-darwin-arm64.dylib.node"); - path.join(__dirname, "schema.prisma"); - path.join(process.cwd(), "node_modules/.prisma/client/schema.prisma"); - } -}); - -// node_modules/.prisma/client/default.js -var require_default = __commonJS({ - "node_modules/.prisma/client/default.js"(exports2, module2) { - module2.exports = { ...require_client() }; - } -}); - -// node_modules/@prisma/client/default.js -var require_default2 = __commonJS({ - "node_modules/@prisma/client/default.js"(exports2, module2) { - module2.exports = { - ...require_default() - }; - } -}); - -// src/common/utils/configureDotEnv.ts -var dotenv = __toESM(require_main(), 1); -var ENV_FILES = [".env", ".env.wallets", ".env.deployments.testnet", ".env.deployments.mainnet"]; -function configureDotEnv(basePath = "./") { - const normalizedBasePath = basePath.endsWith("/") ? basePath : `${basePath}/`; - ENV_FILES.forEach((file) => { - dotenv.config({ path: `${normalizedBasePath}${file}` }); - }); -} -configureDotEnv(); - -// node_modules/axios/lib/helpers/bind.js -function bind(fn2, thisArg) { - return function wrap() { - return fn2.apply(thisArg, arguments); - }; -} - -// node_modules/axios/lib/utils.js -var { toString } = Object.prototype; -var { getPrototypeOf } = Object; -var { iterator, toStringTag } = Symbol; -var kindOf = /* @__PURE__ */ ((cache) => (thing) => { - const str = toString.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); -})(/* @__PURE__ */ Object.create(null)); -var kindOfTest = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf(thing) === type; -}; -var typeOfTest = (type) => (thing) => typeof thing === type; -var { isArray } = Array; -var isUndefined = typeOfTest("undefined"); -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); -} -var isArrayBuffer = kindOfTest("ArrayBuffer"); -function isArrayBufferView(val) { - let result; - if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { - result = ArrayBuffer.isView(val); - } else { - result = val && val.buffer && isArrayBuffer(val.buffer); - } - return result; -} -var isString = typeOfTest("string"); -var isFunction = typeOfTest("function"); -var isNumber = typeOfTest("number"); -var isObject = (thing) => thing !== null && typeof thing === "object"; -var isBoolean = (thing) => thing === true || thing === false; -var isPlainObject = (val) => { - if (kindOf(val) !== "object") { - return false; - } - const prototype3 = getPrototypeOf(val); - return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(toStringTag in val) && !(iterator in val); -}; -var isDate = kindOfTest("Date"); -var isFile = kindOfTest("File"); -var isBlob = kindOfTest("Blob"); -var isFileList = kindOfTest("FileList"); -var isStream = (val) => isObject(val) && isFunction(val.pipe); -var isFormData = (thing) => { - let kind; - return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance - kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]")); -}; -var isURLSearchParams = kindOfTest("URLSearchParams"); -var [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest); -var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); -function forEach(obj, fn2, { allOwnKeys = false } = {}) { - if (obj === null || typeof obj === "undefined") { - return; - } - let i; - let l; - if (typeof obj !== "object") { - obj = [obj]; - } - if (isArray(obj)) { - for (i = 0, l = obj.length; i < l; i++) { - fn2.call(null, obj[i], i, obj); - } - } else { - const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys.length; - let key; - for (i = 0; i < len; i++) { - key = keys[i]; - fn2.call(null, obj[key], key, obj); + }; } - } -} -function findKey(obj, key) { - key = key.toLowerCase(); - const keys = Object.keys(obj); - let i = keys.length; - let _key; - while (i-- > 0) { - _key = keys[i]; - if (key === _key.toLowerCase()) { - return _key; + function pd(e, t) { + return (...r) => { + try { + return t(...r); + } catch (n) { + let i = e.registerNewError(n); + return fr({ kind: "GenericJs", id: i }); + } + }; } - } - return null; -} -var _global = (() => { - if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; -})(); -var isContextDefined = (context) => !isUndefined(context) && context !== _global; -function merge() { - const { caseless } = isContextDefined(this) && this || {}; - const result = {}; - const assignValue = (val, key) => { - const targetKey = caseless && findKey(result, key) || key; - if (isPlainObject(result[targetKey]) && isPlainObject(val)) { - result[targetKey] = merge(result[targetKey], val); - } else if (isPlainObject(val)) { - result[targetKey] = merge({}, val); - } else if (isArray(val)) { - result[targetKey] = val.slice(); - } else { - result[targetKey] = val; + var Wl = k(oi()); + var Hl = __require("async_hooks"); + var Kl = __require("events"); + var zl = k(__require("fs")); + var Fr = k(__require("path")); + var oe = class e { + constructor(t, r) { + if (t.length - 1 !== r.length) throw t.length === 0 ? new TypeError("Expected at least 1 string") : new TypeError(`Expected ${t.length} strings to have ${t.length - 1} values`); + let n = r.reduce((s, a) => s + (a instanceof e ? a.values.length : 1), 0); + this.values = new Array(n), this.strings = new Array(n + 1), this.strings[0] = t[0]; + let i = 0, o = 0; + for (; i < r.length; ) { + let s = r[i++], a = t[i]; + if (s instanceof e) { + this.strings[o] += s.strings[0]; + let l = 0; + for (; l < s.values.length; ) this.values[o++] = s.values[l++], this.strings[o] = s.strings[l]; + this.strings[o] += a; + } else this.values[o++] = s, this.strings[o] = a; + } + } + get sql() { + let t = this.strings.length, r = 1, n = this.strings[0]; + for (; r < t; ) n += `?${this.strings[r++]}`; + return n; + } + get statement() { + let t = this.strings.length, r = 1, n = this.strings[0]; + for (; r < t; ) n += `:${r}${this.strings[r++]}`; + return n; + } + get text() { + let t = this.strings.length, r = 1, n = this.strings[0]; + for (; r < t; ) n += `$${r}${this.strings[r++]}`; + return n; + } + inspect() { + return { sql: this.sql, statement: this.statement, text: this.text, values: this.values }; + } + }; + function da(e, t = ",", r = "", n = "") { + if (e.length === 0) throw new TypeError("Expected `join([])` to be called with an array of multiple elements, but got an empty array"); + return new oe([r, ...Array(e.length - 1).fill(t), n], e); } - }; - for (let i = 0, l = arguments.length; i < l; i++) { - arguments[i] && forEach(arguments[i], assignValue); - } - return result; -} -var extend = (a, b2, thisArg, { allOwnKeys } = {}) => { - forEach(b2, (val, key) => { - if (thisArg && isFunction(val)) { - a[key] = bind(val, thisArg); - } else { - a[key] = val; + function ji(e) { + return new oe([e], []); } - }, { allOwnKeys }); - return a; -}; -var stripBOM = (content) => { - if (content.charCodeAt(0) === 65279) { - content = content.slice(1); - } - return content; -}; -var inherits = (constructor, superConstructor, props, descriptors2) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors2); - constructor.prototype.constructor = constructor; - Object.defineProperty(constructor, "super", { - value: superConstructor.prototype - }); - props && Object.assign(constructor.prototype, props); -}; -var toFlatObject = (sourceObj, destObj, filter2, propFilter) => { - let props; - let i; - let prop; - const merged = {}; - destObj = destObj || {}; - if (sourceObj == null) return destObj; - do { - props = Object.getOwnPropertyNames(sourceObj); - i = props.length; - while (i-- > 0) { - prop = props[i]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } + var ma = ji(""); + function Vi(e, ...t) { + return new oe(e, t); } - sourceObj = filter2 !== false && getPrototypeOf(sourceObj); - } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype); - return destObj; -}; -var endsWith = (str, searchString, position) => { - str = String(str); - if (position === void 0 || position > str.length) { - position = str.length; - } - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; -}; -var toArray = (thing) => { - if (!thing) return null; - if (isArray(thing)) return thing; - let i = thing.length; - if (!isNumber(i)) return null; - const arr = new Array(i); - while (i-- > 0) { - arr[i] = thing[i]; - } - return arr; -}; -var isTypedArray = /* @__PURE__ */ ((TypedArray) => { - return (thing) => { - return TypedArray && thing instanceof TypedArray; - }; -})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); -var forEachEntry = (obj, fn2) => { - const generator = obj && obj[iterator]; - const _iterator = generator.call(obj); - let result; - while ((result = _iterator.next()) && !result.done) { - const pair = result.value; - fn2.call(obj, pair[0], pair[1]); - } -}; -var matchAll = (regExp, str) => { - let matches; - const arr = []; - while ((matches = regExp.exec(str)) !== null) { - arr.push(matches); - } - return arr; -}; -var isHTMLForm = kindOfTest("HTMLFormElement"); -var toCamelCase = (str) => { - return str.toLowerCase().replace( - /[-_\s]([a-z\d])(\w*)/g, - function replacer(m2, p1, p2) { - return p1.toUpperCase() + p2; + function gr(e) { + return { getKeys() { + return Object.keys(e); + }, getPropertyValue(t) { + return e[t]; + } }; } - ); -}; -var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype); -var isRegExp = kindOfTest("RegExp"); -var reduceDescriptors = (obj, reducer) => { - const descriptors2 = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; - forEach(descriptors2, (descriptor, name) => { - let ret; - if ((ret = reducer(descriptor, name, obj)) !== false) { - reducedDescriptors[name] = ret || descriptor; + function re(e, t) { + return { getKeys() { + return [e]; + }, getPropertyValue() { + return t(); + } }; } - }); - Object.defineProperties(obj, reducedDescriptors); -}; -var freezeMethods = (obj) => { - reduceDescriptors(obj, (descriptor, name) => { - if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) { - return false; + function ot(e) { + let t = new ve(); + return { getKeys() { + return e.getKeys(); + }, getPropertyValue(r) { + return t.getOrCreate(r, () => e.getPropertyValue(r)); + }, getPropertyDescriptor(r) { + return e.getPropertyDescriptor?.(r); + } }; } - const value = obj[name]; - if (!isFunction(value)) return; - descriptor.enumerable = false; - if ("writable" in descriptor) { - descriptor.writable = false; - return; + var Rn = { enumerable: true, configurable: true, writable: true }; + function Cn(e) { + let t = new Set(e); + return { getOwnPropertyDescriptor: () => Rn, has: (r, n) => t.has(n), set: (r, n, i) => t.add(n) && Reflect.set(r, n, i), ownKeys: () => [...t] }; } - if (!descriptor.set) { - descriptor.set = () => { - throw Error("Can not rewrite read-only method '" + name + "'"); - }; + var fa = Symbol.for("nodejs.util.inspect.custom"); + function Se(e, t) { + let r = dd(t), n = /* @__PURE__ */ new Set(), i = new Proxy(e, { get(o, s) { + if (n.has(s)) return o[s]; + let a = r.get(s); + return a ? a.getPropertyValue(s) : o[s]; + }, has(o, s) { + if (n.has(s)) return true; + let a = r.get(s); + return a ? a.has?.(s) ?? true : Reflect.has(o, s); + }, ownKeys(o) { + let s = ga(Reflect.ownKeys(o), r), a = ga(Array.from(r.keys()), r); + return [.../* @__PURE__ */ new Set([...s, ...a, ...n])]; + }, set(o, s, a) { + return r.get(s)?.getPropertyDescriptor?.(s)?.writable === false ? false : (n.add(s), Reflect.set(o, s, a)); + }, getOwnPropertyDescriptor(o, s) { + let a = Reflect.getOwnPropertyDescriptor(o, s); + if (a && !a.configurable) return a; + let l = r.get(s); + return l ? l.getPropertyDescriptor ? { ...Rn, ...l?.getPropertyDescriptor(s) } : Rn : a; + }, defineProperty(o, s, a) { + return n.add(s), Reflect.defineProperty(o, s, a); + } }); + return i[fa] = function() { + let o = { ...this }; + return delete o[fa], o; + }, i; } - }); -}; -var toObjectSet = (arrayOrString, delimiter) => { - const obj = {}; - const define2 = (arr) => { - arr.forEach((value) => { - obj[value] = true; - }); - }; - isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); - return obj; -}; -var noop = () => { -}; -var toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; -}; -function isSpecCompliantForm(thing) { - return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]); -} -var toJSONObject = (obj) => { - const stack = new Array(10); - const visit = (source, i) => { - if (isObject(source)) { - if (stack.indexOf(source) >= 0) { - return; - } - if (!("toJSON" in source)) { - stack[i] = source; - const target = isArray(source) ? [] : {}; - forEach(source, (value, key) => { - const reducedValue = visit(value, i + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); - stack[i] = void 0; - return target; + function dd(e) { + let t = /* @__PURE__ */ new Map(); + for (let r of e) { + let n = r.getKeys(); + for (let i of n) t.set(i, r); } + return t; } - return source; - }; - return visit(obj, 0); -}; -var isAsyncFn = kindOfTest("AsyncFunction"); -var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); -var _setImmediate = ((setImmediateSupported, postMessageSupported) => { - if (setImmediateSupported) { - return setImmediate; - } - return postMessageSupported ? ((token, callbacks) => { - _global.addEventListener("message", ({ source, data }) => { - if (source === _global && data === token) { - callbacks.length && callbacks.shift()(); - } - }, false); - return (cb) => { - callbacks.push(cb); - _global.postMessage(token, "*"); - }; - })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); -})( - typeof setImmediate === "function", - isFunction(_global.postMessage) -); -var asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate; -var isIterable = (thing) => thing != null && isFunction(thing[iterator]); -var utils_default = { - isArray, - isArrayBuffer, - isBuffer, - isFormData, - isArrayBufferView, - isString, - isNumber, - isBoolean, - isObject, - isPlainObject, - isReadableStream, - isRequest, - isResponse, - isHeaders, - isUndefined, - isDate, - isFile, - isBlob, - isRegExp, - isFunction, - isStream, - isURLSearchParams, - isTypedArray, - isFileList, - forEach, - merge, - extend, - trim, - stripBOM, - inherits, - toFlatObject, - kindOf, - kindOfTest, - endsWith, - toArray, - forEachEntry, - matchAll, - isHTMLForm, - hasOwnProperty, - hasOwnProp: hasOwnProperty, - // an alias to avoid ESLint no-prototype-builtins detection - reduceDescriptors, - freezeMethods, - toObjectSet, - toCamelCase, - noop, - toFiniteNumber, - findKey, - global: _global, - isContextDefined, - isSpecCompliantForm, - toJSONObject, - isAsyncFn, - isThenable, - setImmediate: _setImmediate, - asap, - isIterable -}; - -// node_modules/axios/lib/core/AxiosError.js -function AxiosError(message, code, config3, request, response) { - Error.call(this); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = new Error().stack; - } - this.message = message; - this.name = "AxiosError"; - code && (this.code = code); - config3 && (this.config = config3); - request && (this.request = request); - if (response) { - this.response = response; - this.status = response.status ? response.status : null; - } -} -utils_default.inherits(AxiosError, Error, { - toJSON: function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: utils_default.toJSONObject(this.config), - code: this.code, - status: this.status - }; - } -}); -var prototype = AxiosError.prototype; -var descriptors = {}; -[ - "ERR_BAD_OPTION_VALUE", - "ERR_BAD_OPTION", - "ECONNABORTED", - "ETIMEDOUT", - "ERR_NETWORK", - "ERR_FR_TOO_MANY_REDIRECTS", - "ERR_DEPRECATED", - "ERR_BAD_RESPONSE", - "ERR_BAD_REQUEST", - "ERR_CANCELED", - "ERR_NOT_SUPPORT", - "ERR_INVALID_URL" - // eslint-disable-next-line func-names -].forEach((code) => { - descriptors[code] = { value: code }; -}); -Object.defineProperties(AxiosError, descriptors); -Object.defineProperty(prototype, "isAxiosError", { value: true }); -AxiosError.from = (error, code, config3, request, response, customProps) => { - const axiosError = Object.create(prototype); - utils_default.toFlatObject(error, axiosError, function filter2(obj) { - return obj !== Error.prototype; - }, (prop) => { - return prop !== "isAxiosError"; - }); - AxiosError.call(axiosError, error.message, code, config3, request, response); - axiosError.cause = error; - axiosError.name = error.name; - customProps && Object.assign(axiosError, customProps); - return axiosError; -}; -var AxiosError_default = AxiosError; - -// node_modules/axios/lib/platform/node/classes/FormData.js -var import_form_data = __toESM(require_form_data(), 1); -var FormData_default = import_form_data.default; - -// node_modules/axios/lib/helpers/toFormData.js -function isVisitable(thing) { - return utils_default.isPlainObject(thing) || utils_default.isArray(thing); -} -function removeBrackets(key) { - return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key; -} -function renderKey(path, key, dots) { - if (!path) return key; - return path.concat(key).map(function each(token, i) { - token = removeBrackets(token); - return !dots && i ? "[" + token + "]" : token; - }).join(dots ? "." : ""); -} -function isFlatArray(arr) { - return utils_default.isArray(arr) && !arr.some(isVisitable); -} -var predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) { - return /^is[A-Z]/.test(prop); -}); -function toFormData(obj, formData, options) { - if (!utils_default.isObject(obj)) { - throw new TypeError("target must be an object"); - } - formData = formData || new (FormData_default || FormData)(); - options = utils_default.toFlatObject(options, { - metaTokens: true, - dots: false, - indexes: false - }, false, function defined(option, source) { - return !utils_default.isUndefined(source[option]); - }); - const metaTokens = options.metaTokens; - const visitor = options.visitor || defaultVisitor; - const dots = options.dots; - const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; - const useBlob = _Blob && utils_default.isSpecCompliantForm(formData); - if (!utils_default.isFunction(visitor)) { - throw new TypeError("visitor must be a function"); - } - function convertValue(value) { - if (value === null) return ""; - if (utils_default.isDate(value)) { - return value.toISOString(); + function ga(e, t) { + return e.filter((r) => t.get(r)?.has?.(r) ?? true); } - if (!useBlob && utils_default.isBlob(value)) { - throw new AxiosError_default("Blob is not supported. Use a Buffer instead."); + function _t(e) { + return { getKeys() { + return e; + }, has() { + return false; + }, getPropertyValue() { + } }; } - if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) { - return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); + function Ft(e, t) { + return { batch: e, transaction: t?.kind === "batch" ? { isolationLevel: t.options.isolationLevel } : void 0 }; } - return value; - } - function defaultVisitor(value, key, path) { - let arr = value; - if (value && !path && typeof value === "object") { - if (utils_default.endsWith(key, "{}")) { - key = metaTokens ? key : key.slice(0, -2); - value = JSON.stringify(value); - } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) { - key = removeBrackets(key); - arr.forEach(function each(el2, index2) { - !(utils_default.isUndefined(el2) || el2 === null) && formData.append( - // eslint-disable-next-line no-nested-ternary - indexes === true ? renderKey([key], index2, dots) : indexes === null ? key : key + "[]", - convertValue(el2) - ); - }); - return false; - } + function ha(e) { + if (e === void 0) return ""; + let t = Ot(e); + return new Rt(0, { colors: fn }).write(t).toString(); } - if (isVisitable(value)) { - return true; + var md = "P2037"; + function st({ error: e, user_facing_error: t }, r, n) { + return t.error_code ? new V(fd(t, n), { code: t.error_code, clientVersion: r, meta: t.meta, batchRequestIdx: t.batch_request_idx }) : new B(e, { clientVersion: r, batchRequestIdx: t.batch_request_idx }); } - formData.append(renderKey(path, key, dots), convertValue(value)); - return false; - } - const stack = []; - const exposedHelpers = Object.assign(predicates, { - defaultVisitor, - convertValue, - isVisitable - }); - function build(value, path) { - if (utils_default.isUndefined(value)) return; - if (stack.indexOf(value) !== -1) { - throw Error("Circular reference detected in " + path.join(".")); + function fd(e, t) { + let r = e.message; + return (t === "postgresql" || t === "postgres" || t === "mysql") && e.error_code === md && (r += ` +Prisma Accelerate has built-in connection pooling to prevent such errors: https://pris.ly/client/error-accelerate`), r; } - stack.push(value); - utils_default.forEach(value, function each(el2, key) { - const result = !(utils_default.isUndefined(el2) || el2 === null) && visitor.call( - formData, - el2, - utils_default.isString(key) ? key.trim() : key, - path, - exposedHelpers - ); - if (result === true) { - build(el2, path ? path.concat(key) : [key]); - } - }); - stack.pop(); - } - if (!utils_default.isObject(obj)) { - throw new TypeError("data must be an object"); - } - build(obj); - return formData; -} -var toFormData_default = toFormData; - -// node_modules/axios/lib/helpers/AxiosURLSearchParams.js -function encode(str) { - const charMap = { - "!": "%21", - "'": "%27", - "(": "%28", - ")": "%29", - "~": "%7E", - "%20": "+", - "%00": "\0" - }; - return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { - return charMap[match]; - }); -} -function AxiosURLSearchParams(params, options) { - this._pairs = []; - params && toFormData_default(params, this, options); -} -var prototype2 = AxiosURLSearchParams.prototype; -prototype2.append = function append(name, value) { - this._pairs.push([name, value]); -}; -prototype2.toString = function toString2(encoder5) { - const _encode = encoder5 ? function(value) { - return encoder5.call(this, value, encode); - } : encode; - return this._pairs.map(function each(pair) { - return _encode(pair[0]) + "=" + _encode(pair[1]); - }, "").join("&"); -}; -var AxiosURLSearchParams_default = AxiosURLSearchParams; - -// node_modules/axios/lib/helpers/buildURL.js -function encode2(val) { - return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); -} -function buildURL(url2, params, options) { - if (!params) { - return url2; - } - const _encode = options && options.encode || encode2; - if (utils_default.isFunction(options)) { - options = { - serialize: options - }; - } - const serializeFn = options && options.serialize; - let serializedParams; - if (serializeFn) { - serializedParams = serializeFn(params, options); - } else { - serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, options).toString(_encode); - } - if (serializedParams) { - const hashmarkIndex = url2.indexOf("#"); - if (hashmarkIndex !== -1) { - url2 = url2.slice(0, hashmarkIndex); + var hr = ""; + function ya(e) { + var t = e.split(` +`); + return t.reduce(function(r, n) { + var i = yd(n) || Ed(n) || Pd(n) || Cd(n) || Td(n); + return i && r.push(i), r; + }, []); } - url2 += (url2.indexOf("?") === -1 ? "?" : "&") + serializedParams; - } - return url2; -} - -// node_modules/axios/lib/core/InterceptorManager.js -var InterceptorManager = class { - constructor() { - this.handlers = []; - } - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled, - rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - } - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - * - * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise - */ - eject(id2) { - if (this.handlers[id2]) { - this.handlers[id2] = null; + var gd = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack||\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; + var hd = /\((\S*)(?::(\d+))(?::(\d+))\)/; + function yd(e) { + var t = gd.exec(e); + if (!t) return null; + var r = t[2] && t[2].indexOf("native") === 0, n = t[2] && t[2].indexOf("eval") === 0, i = hd.exec(t[2]); + return n && i != null && (t[2] = i[1], t[3] = i[2], t[4] = i[3]), { file: r ? null : t[2], methodName: t[1] || hr, arguments: r ? [t[2]] : [], lineNumber: t[3] ? +t[3] : null, column: t[4] ? +t[4] : null }; } - } - /** - * Clear all interceptors from the stack - * - * @returns {void} - */ - clear() { - if (this.handlers) { - this.handlers = []; + var bd = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i; + function Ed(e) { + var t = bd.exec(e); + return t ? { file: t[2], methodName: t[1] || hr, arguments: [], lineNumber: +t[3], column: t[4] ? +t[4] : null } : null; } - } - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - * - * @returns {void} - */ - forEach(fn2) { - utils_default.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn2(h); + var wd = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i; + var xd = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; + function Pd(e) { + var t = wd.exec(e); + if (!t) return null; + var r = t[3] && t[3].indexOf(" > eval") > -1, n = xd.exec(t[3]); + return r && n != null && (t[3] = n[1], t[4] = n[2], t[5] = null), { file: t[3], methodName: t[1] || hr, arguments: t[2] ? t[2].split(",") : [], lineNumber: t[4] ? +t[4] : null, column: t[5] ? +t[5] : null }; + } + var vd = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i; + function Td(e) { + var t = vd.exec(e); + return t ? { file: t[3], methodName: t[1] || hr, arguments: [], lineNumber: +t[4], column: t[5] ? +t[5] : null } : null; + } + var Rd = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i; + function Cd(e) { + var t = Rd.exec(e); + return t ? { file: t[2], methodName: t[1] || hr, arguments: [], lineNumber: +t[3], column: t[4] ? +t[4] : null } : null; + } + var Bi = class { + getLocation() { + return null; } - }); - } -}; -var InterceptorManager_default = InterceptorManager; - -// node_modules/axios/lib/defaults/transitional.js -var transitional_default = { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false -}; - -// node_modules/axios/lib/platform/node/index.js -import crypto2 from "crypto"; - -// node_modules/axios/lib/platform/node/classes/URLSearchParams.js -import url from "url"; -var URLSearchParams_default = url.URLSearchParams; - -// node_modules/axios/lib/platform/node/index.js -var ALPHA = "abcdefghijklmnopqrstuvwxyz"; -var DIGIT = "0123456789"; -var ALPHABET = { - DIGIT, - ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT -}; -var generateString = (size5 = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { - let str = ""; - const { length } = alphabet; - const randomValues = new Uint32Array(size5); - crypto2.randomFillSync(randomValues); - for (let i = 0; i < size5; i++) { - str += alphabet[randomValues[i] % length]; - } - return str; -}; -var node_default = { - isNode: true, - classes: { - URLSearchParams: URLSearchParams_default, - FormData: FormData_default, - Blob: typeof Blob !== "undefined" && Blob || null - }, - ALPHABET, - generateString, - protocols: ["http", "https", "file", "data"] -}; - -// node_modules/axios/lib/platform/common/utils.js -var utils_exports = {}; -__export(utils_exports, { - hasBrowserEnv: () => hasBrowserEnv, - hasStandardBrowserEnv: () => hasStandardBrowserEnv, - hasStandardBrowserWebWorkerEnv: () => hasStandardBrowserWebWorkerEnv, - navigator: () => _navigator, - origin: () => origin -}); -var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; -var _navigator = typeof navigator === "object" && navigator || void 0; -var hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0); -var hasStandardBrowserWebWorkerEnv = (() => { - return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef - self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; -})(); -var origin = hasBrowserEnv && window.location.href || "http://localhost"; - -// node_modules/axios/lib/platform/index.js -var platform_default = { - ...utils_exports, - ...node_default -}; - -// node_modules/axios/lib/helpers/toURLEncodedForm.js -function toURLEncodedForm(data, options) { - return toFormData_default(data, new platform_default.classes.URLSearchParams(), Object.assign({ - visitor: function(value, key, path, helpers) { - if (platform_default.isNode && utils_default.isBuffer(value)) { - this.append(key, value.toString("base64")); - return false; + }; + var Ui = class { + constructor() { + this._error = new Error(); } - return helpers.defaultVisitor.apply(this, arguments); - } - }, options)); -} - -// node_modules/axios/lib/helpers/formDataToJSON.js -function parsePropPath(name) { - return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match) => { - return match[0] === "[]" ? "" : match[1] || match[0]; - }); -} -function arrayToObject(arr) { - const obj = {}; - const keys = Object.keys(arr); - let i; - const len = keys.length; - let key; - for (i = 0; i < len; i++) { - key = keys[i]; - obj[key] = arr[key]; - } - return obj; -} -function formDataToJSON(formData) { - function buildPath(path, value, target, index2) { - let name = path[index2++]; - if (name === "__proto__") return true; - const isNumericKey = Number.isFinite(+name); - const isLast = index2 >= path.length; - name = !name && utils_default.isArray(target) ? target.length : name; - if (isLast) { - if (utils_default.hasOwnProp(target, name)) { - target[name] = [target[name], value]; - } else { - target[name] = value; + getLocation() { + let t = this._error.stack; + if (!t) return null; + let n = ya(t).find((i) => { + if (!i.file) return false; + let o = mi(i.file); + return o !== "" && !o.includes("@prisma") && !o.includes("/packages/client/src/runtime/") && !o.endsWith("/runtime/binary.js") && !o.endsWith("/runtime/library.js") && !o.endsWith("/runtime/edge.js") && !o.endsWith("/runtime/edge-esm.js") && !o.startsWith("internal/") && !i.methodName.includes("new ") && !i.methodName.includes("getCallSite") && !i.methodName.includes("Proxy.") && i.methodName.split(".").length < 4; + }); + return !n || !n.file ? null : { fileName: n.file, lineNumber: n.lineNumber, columnNumber: n.column }; } - return !isNumericKey; + }; + function Ze(e) { + return e === "minimal" ? typeof $EnabledCallSite == "function" && e !== "minimal" ? new $EnabledCallSite() : new Bi() : new Ui(); } - if (!target[name] || !utils_default.isObject(target[name])) { - target[name] = []; + var ba = { _avg: true, _count: true, _sum: true, _min: true, _max: true }; + function Lt(e = {}) { + let t = Ad(e); + return Object.entries(t).reduce((n, [i, o]) => (ba[i] !== void 0 ? n.select[i] = { select: o } : n[i] = o, n), { select: {} }); } - const result = buildPath(path, value, target[name], index2); - if (result && utils_default.isArray(target[name])) { - target[name] = arrayToObject(target[name]); + function Ad(e = {}) { + return typeof e._count == "boolean" ? { ...e, _count: { _all: e._count } } : e; } - return !isNumericKey; - } - if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) { - const obj = {}; - utils_default.forEachEntry(formData, (name, value) => { - buildPath(parsePropPath(name), value, obj, 0); - }); - return obj; - } - return null; -} -var formDataToJSON_default = formDataToJSON; - -// node_modules/axios/lib/defaults/index.js -function stringifySafely(rawValue, parser, encoder5) { - if (utils_default.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils_default.trim(rawValue); - } catch (e) { - if (e.name !== "SyntaxError") { - throw e; - } + function Sn(e = {}) { + return (t) => (typeof e._count == "boolean" && (t._count = t._count._all), t); } - } - return (encoder5 || JSON.stringify)(rawValue); -} -var defaults = { - transitional: transitional_default, - adapter: ["xhr", "http", "fetch"], - transformRequest: [function transformRequest(data, headers) { - const contentType = headers.getContentType() || ""; - const hasJSONContentType = contentType.indexOf("application/json") > -1; - const isObjectPayload = utils_default.isObject(data); - if (isObjectPayload && utils_default.isHTMLForm(data)) { - data = new FormData(data); + function Ea(e, t) { + let r = Sn(e); + return t({ action: "aggregate", unpacker: r, argsMapper: Lt })(e); } - const isFormData2 = utils_default.isFormData(data); - if (isFormData2) { - return hasJSONContentType ? JSON.stringify(formDataToJSON_default(data)) : data; + function Id(e = {}) { + let { select: t, ...r } = e; + return typeof t == "object" ? Lt({ ...r, _count: t }) : Lt({ ...r, _count: { _all: true } }); } - if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data) || utils_default.isReadableStream(data)) { - return data; + function Od(e = {}) { + return typeof e.select == "object" ? (t) => Sn(e)(t)._count : (t) => Sn(e)(t)._count._all; } - if (utils_default.isArrayBufferView(data)) { - return data.buffer; + function wa(e, t) { + return t({ action: "count", unpacker: Od(e), argsMapper: Id })(e); } - if (utils_default.isURLSearchParams(data)) { - headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); - return data.toString(); + function kd(e = {}) { + let t = Lt(e); + if (Array.isArray(t.by)) for (let r of t.by) typeof r == "string" && (t.select[r] = true); + else typeof t.by == "string" && (t.select[t.by] = true); + return t; } - let isFileList2; - if (isObjectPayload) { - if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { - return toURLEncodedForm(data, this.formSerializer).toString(); - } - if ((isFileList2 = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { - const _FormData = this.env && this.env.FormData; - return toFormData_default( - isFileList2 ? { "files[]": data } : data, - _FormData && new _FormData(), - this.formSerializer - ); - } + function Dd(e = {}) { + return (t) => (typeof e?._count == "boolean" && t.forEach((r) => { + r._count = r._count._all; + }), t); } - if (isObjectPayload || hasJSONContentType) { - headers.setContentType("application/json", false); - return stringifySafely(data); + function xa(e, t) { + return t({ action: "groupBy", unpacker: Dd(e), argsMapper: kd })(e); } - return data; - }], - transformResponse: [function transformResponse(data) { - const transitional2 = this.transitional || defaults.transitional; - const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing; - const JSONRequested = this.responseType === "json"; - if (utils_default.isResponse(data) || utils_default.isReadableStream(data)) { - return data; + function Pa(e, t, r) { + if (t === "aggregate") return (n) => Ea(n, r); + if (t === "count") return (n) => wa(n, r); + if (t === "groupBy") return (n) => xa(n, r); } - if (data && utils_default.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { - const silentJSONParsing = transitional2 && transitional2.silentJSONParsing; - const strictJSONParsing = !silentJSONParsing && JSONRequested; - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === "SyntaxError") { - throw AxiosError_default.from(e, AxiosError_default.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e; + function va(e, t) { + let r = t.fields.filter((i) => !i.relationName), n = wi(r, (i) => i.name); + return new Proxy({}, { get(i, o) { + if (o in i || typeof o == "symbol") return i[o]; + let s = n[o]; + if (s) return new sr(e, o, s.type, s.isList, s.kind === "enum"); + }, ...Cn(Object.keys(n)) }); + } + var Ta = (e) => Array.isArray(e) ? e : e.split("."); + var Gi = (e, t) => Ta(t).reduce((r, n) => r && r[n], e); + var Ra = (e, t, r) => Ta(t).reduceRight((n, i, o, s) => Object.assign({}, Gi(e, s.slice(0, o)), { [i]: n }), r); + function _d(e, t) { + return e === void 0 || t === void 0 ? [] : [...t, "select", e]; + } + function Fd(e, t, r) { + return t === void 0 ? e ?? {} : Ra(t, r, e || true); + } + function Qi(e, t, r, n, i, o) { + let a = e._runtimeDataModel.models[t].fields.reduce((l, u) => ({ ...l, [u.name]: u }), {}); + return (l) => { + let u = Ze(e._errorFormat), c = _d(n, i), p = Fd(l, o, c), d = r({ dataPath: c, callsite: u })(p), f = Ld(e, t); + return new Proxy(d, { get(g, h) { + if (!f.includes(h)) return g[h]; + let T = [a[h].type, r, h], S = [c, p]; + return Qi(e, ...T, ...S); + }, ...Cn([...f, ...Object.getOwnPropertyNames(d)]) }); + }; + } + function Ld(e, t) { + return e._runtimeDataModel.models[t].fields.filter((r) => r.kind === "object").map((r) => r.name); + } + function Ca(e, t, r, n) { + return e === Je.ModelAction.findFirstOrThrow || e === Je.ModelAction.findUniqueOrThrow ? Nd(t, r, n) : n; + } + function Nd(e, t, r) { + return async (n) => { + if ("rejectOnNotFound" in n.args) { + let o = Tt({ originalMethod: n.clientMethod, callsite: n.callsite, message: "'rejectOnNotFound' option is not supported" }); + throw new J(o, { clientVersion: t }); } - } + return await r(n).catch((o) => { + throw o instanceof V && o.code === "P2025" ? new Le(`No ${e} found`, t) : o; + }); + }; } - return data; - }], - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - xsrfCookieName: "XSRF-TOKEN", - xsrfHeaderName: "X-XSRF-TOKEN", - maxContentLength: -1, - maxBodyLength: -1, - env: { - FormData: platform_default.classes.FormData, - Blob: platform_default.classes.Blob - }, - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - headers: { - common: { - "Accept": "application/json, text/plain, */*", - "Content-Type": void 0 + var Md = ["findUnique", "findUniqueOrThrow", "findFirst", "findFirstOrThrow", "create", "update", "upsert", "delete"]; + var $d = ["aggregate", "count", "groupBy"]; + function Ji(e, t) { + let r = e._extensions.getAllModelExtensions(t) ?? {}, n = [qd(e, t), Vd(e, t), gr(r), re("name", () => t), re("$name", () => t), re("$parent", () => e._appliedParent)]; + return Se({}, n); } - } -}; -utils_default.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { - defaults.headers[method] = {}; -}); -var defaults_default = defaults; - -// node_modules/axios/lib/helpers/parseHeaders.js -var ignoreDuplicateOf = utils_default.toObjectSet([ - "age", - "authorization", - "content-length", - "content-type", - "etag", - "expires", - "from", - "host", - "if-modified-since", - "if-unmodified-since", - "last-modified", - "location", - "max-forwards", - "proxy-authorization", - "referer", - "retry-after", - "user-agent" -]); -var parseHeaders_default = (rawHeaders) => { - const parsed = {}; - let key; - let val; - let i; - rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { - i = line.indexOf(":"); - key = line.substring(0, i).trim().toLowerCase(); - val = line.substring(i + 1).trim(); - if (!key || parsed[key] && ignoreDuplicateOf[key]) { - return; + function qd(e, t) { + let r = Te(t), n = Object.keys(Je.ModelAction).concat("count"); + return { getKeys() { + return n; + }, getPropertyValue(i) { + let o = i, s = (l) => e._request(l); + s = Ca(o, t, e._clientVersion, s); + let a = (l) => (u) => { + let c = Ze(e._errorFormat); + return e._createPrismaPromise((p) => { + let d = { args: u, dataPath: [], action: o, model: t, clientMethod: `${r}.${i}`, jsModelName: r, transaction: p, callsite: c }; + return s({ ...d, ...l }); + }); + }; + return Md.includes(o) ? Qi(e, t, a) : jd(i) ? Pa(e, i, a) : a({}); + } }; } - if (key === "set-cookie") { - if (parsed[key]) { - parsed[key].push(val); - } else { - parsed[key] = [val]; - } - } else { - parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; + function jd(e) { + return $d.includes(e); } - }); - return parsed; -}; - -// node_modules/axios/lib/core/AxiosHeaders.js -var $internals = Symbol("internals"); -function normalizeHeader(header) { - return header && String(header).trim().toLowerCase(); -} -function normalizeValue(value) { - if (value === false || value == null) { - return value; - } - return utils_default.isArray(value) ? value.map(normalizeValue) : String(value); -} -function parseTokens(str) { - const tokens = /* @__PURE__ */ Object.create(null); - const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; - let match; - while (match = tokensRE.exec(str)) { - tokens[match[1]] = match[2]; - } - return tokens; -} -var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); -function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) { - if (utils_default.isFunction(filter2)) { - return filter2.call(this, value, header); - } - if (isHeaderNameFilter) { - value = header; - } - if (!utils_default.isString(value)) return; - if (utils_default.isString(filter2)) { - return value.indexOf(filter2) !== -1; - } - if (utils_default.isRegExp(filter2)) { - return filter2.test(value); - } -} -function formatHeader(header) { - return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str) => { - return char.toUpperCase() + str; - }); -} -function buildAccessors(obj, header) { - const accessorName = utils_default.toCamelCase(" " + header); - ["get", "set", "has"].forEach((methodName) => { - Object.defineProperty(obj, methodName + accessorName, { - value: function(arg1, arg2, arg3) { - return this[methodName].call(this, header, arg1, arg2, arg3); - }, - configurable: true - }); - }); -} -var AxiosHeaders = class { - constructor(headers) { - headers && this.set(headers); - } - set(header, valueOrRewrite, rewrite) { - const self2 = this; - function setHeader(_value, _header, _rewrite) { - const lHeader = normalizeHeader(_header); - if (!lHeader) { - throw new Error("header name must be a non-empty string"); - } - const key = utils_default.findKey(self2, lHeader); - if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { - self2[key || _header] = normalizeValue(_value); - } + function Vd(e, t) { + return ot(re("fields", () => { + let r = e._runtimeDataModel.models[t]; + return va(t, r); + })); } - const setHeaders = (headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); - if (utils_default.isPlainObject(header) || header instanceof this.constructor) { - setHeaders(header, valueOrRewrite); - } else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { - setHeaders(parseHeaders_default(header), valueOrRewrite); - } else if (utils_default.isObject(header) && utils_default.isIterable(header)) { - let obj = {}, dest, key; - for (const entry of header) { - if (!utils_default.isArray(entry)) { - throw TypeError("Object iterator must return a key-value pair"); - } - obj[key = entry[0]] = (dest = obj[key]) ? utils_default.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1]; + function Sa(e) { + return e.replace(/^./, (t) => t.toUpperCase()); + } + var Wi = Symbol(); + function yr(e) { + let t = [Bd(e), re(Wi, () => e), re("$parent", () => e._appliedParent)], r = e._extensions.getAllClientExtensions(); + return r && t.push(gr(r)), Se(e, t); + } + function Bd(e) { + let t = Object.keys(e._runtimeDataModel.models), r = t.map(Te), n = [...new Set(t.concat(r))]; + return ot({ getKeys() { + return n; + }, getPropertyValue(i) { + let o = Sa(i); + if (e._runtimeDataModel.models[o] !== void 0) return Ji(e, o); + if (e._runtimeDataModel.models[i] !== void 0) return Ji(e, i); + }, getPropertyDescriptor(i) { + if (!r.includes(i)) return { enumerable: false }; + } }); + } + function Aa(e) { + return e[Wi] ? e[Wi] : e; + } + function Ia(e) { + if (typeof e == "function") return e(this); + if (e.client?.__AccelerateEngine) { + let r = e.client.__AccelerateEngine; + this._originalClient._engine = new r(this._originalClient._accelerateEngineConfig); } - setHeaders(obj, valueOrRewrite); - } else { - header != null && setHeader(valueOrRewrite, header, rewrite); + let t = Object.create(this._originalClient, { _extensions: { value: this._extensions.append(e) }, _appliedParent: { value: this, configurable: true }, $use: { value: void 0 }, $on: { value: void 0 } }); + return yr(t); } - return this; - } - get(header, parser) { - header = normalizeHeader(header); - if (header) { - const key = utils_default.findKey(this, header); - if (key) { - const value = this[key]; - if (!parser) { - return value; - } - if (parser === true) { - return parseTokens(value); - } - if (utils_default.isFunction(parser)) { - return parser.call(this, value, key); - } - if (utils_default.isRegExp(parser)) { - return parser.exec(value); + function Oa({ result: e, modelName: t, select: r, omit: n, extensions: i }) { + let o = i.getAllComputedFields(t); + if (!o) return e; + let s = [], a = []; + for (let l of Object.values(o)) { + if (n) { + if (n[l.name]) continue; + let u = l.needs.filter((c) => n[c]); + u.length > 0 && a.push(_t(u)); + } else if (r) { + if (!r[l.name]) continue; + let u = l.needs.filter((c) => !r[c]); + u.length > 0 && a.push(_t(u)); } - throw new TypeError("parser must be boolean|regexp|function"); + Ud(e, l.needs) && s.push(Gd(l, Se(e, s))); } + return s.length > 0 || a.length > 0 ? Se(e, [...s, ...a]) : e; } - } - has(header, matcher) { - header = normalizeHeader(header); - if (header) { - const key = utils_default.findKey(this, header); - return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + function Ud(e, t) { + return t.every((r) => Ei(e, r)); } - return false; - } - delete(header, matcher) { - const self2 = this; - let deleted = false; - function deleteHeader(_header) { - _header = normalizeHeader(_header); - if (_header) { - const key = utils_default.findKey(self2, _header); - if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { - delete self2[key]; - deleted = true; - } + function Gd(e, t) { + return ot(re(e.name, () => e.compute(t))); + } + function An({ visitor: e, result: t, args: r, runtimeDataModel: n, modelName: i }) { + if (Array.isArray(t)) { + for (let s = 0; s < t.length; s++) t[s] = An({ result: t[s], args: r, modelName: i, runtimeDataModel: n, visitor: e }); + return t; } + let o = e(t, i, r) ?? t; + return r.include && ka({ includeOrSelect: r.include, result: o, parentModelName: i, runtimeDataModel: n, visitor: e }), r.select && ka({ includeOrSelect: r.select, result: o, parentModelName: i, runtimeDataModel: n, visitor: e }), o; } - if (utils_default.isArray(header)) { - header.forEach(deleteHeader); - } else { - deleteHeader(header); + function ka({ includeOrSelect: e, result: t, parentModelName: r, runtimeDataModel: n, visitor: i }) { + for (let [o, s] of Object.entries(e)) { + if (!s || t[o] == null || Re(s)) continue; + let l = n.models[r].fields.find((c) => c.name === o); + if (!l || l.kind !== "object" || !l.relationName) continue; + let u = typeof s == "object" ? s : {}; + t[o] = An({ visitor: i, result: t[o], args: u, modelName: l.type, runtimeDataModel: n }); + } } - return deleted; - } - clear(matcher) { - const keys = Object.keys(this); - let i = keys.length; - let deleted = false; - while (i--) { - const key = keys[i]; - if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { - delete this[key]; - deleted = true; + function Da({ result: e, modelName: t, args: r, extensions: n, runtimeDataModel: i, globalOmit: o }) { + return n.isEmpty() || e == null || typeof e != "object" || !i.models[t] ? e : An({ result: e, args: r ?? {}, modelName: t, runtimeDataModel: i, visitor: (a, l, u) => { + let c = Te(l); + return Oa({ result: a, modelName: c, select: u.select, omit: u.select ? void 0 : { ...o?.[c], ...u.omit }, extensions: n }); + } }); + } + function _a(e) { + if (e instanceof oe) return Qd(e); + if (Array.isArray(e)) { + let r = [e[0]]; + for (let n = 1; n < e.length; n++) r[n] = br(e[n]); + return r; } + let t = {}; + for (let r in e) t[r] = br(e[r]); + return t; } - return deleted; - } - normalize(format) { - const self2 = this; - const headers = {}; - utils_default.forEach(this, (value, header) => { - const key = utils_default.findKey(headers, header); - if (key) { - self2[key] = normalizeValue(value); - delete self2[header]; - return; + function Qd(e) { + return new oe(e.strings, e.values); + } + function br(e) { + if (typeof e != "object" || e == null || e instanceof Me || It(e)) return e; + if (vt(e)) return new xe(e.toFixed()); + if (Pt(e)) return /* @__PURE__ */ new Date(+e); + if (ArrayBuffer.isView(e)) return e.slice(0); + if (Array.isArray(e)) { + let t = e.length, r; + for (r = Array(t); t--; ) r[t] = br(e[t]); + return r; } - const normalized = format ? formatHeader(header) : String(header).trim(); - if (normalized !== header) { - delete self2[header]; + if (typeof e == "object") { + let t = {}; + for (let r in e) r === "__proto__" ? Object.defineProperty(t, r, { value: br(e[r]), configurable: true, enumerable: true, writable: true }) : t[r] = br(e[r]); + return t; } - self2[normalized] = normalizeValue(value); - headers[normalized] = true; - }); - return this; - } - concat(...targets) { - return this.constructor.concat(this, ...targets); - } - toJSON(asStrings) { - const obj = /* @__PURE__ */ Object.create(null); - utils_default.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value); - }); - return obj; - } - [Symbol.iterator]() { - return Object.entries(this.toJSON())[Symbol.iterator](); - } - toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); - } - getSetCookie() { - return this.get("set-cookie") || []; - } - get [Symbol.toStringTag]() { - return "AxiosHeaders"; - } - static from(thing) { - return thing instanceof this ? thing : new this(thing); - } - static concat(first, ...targets) { - const computed = new this(first); - targets.forEach((target) => computed.set(target)); - return computed; - } - static accessor(header) { - const internals = this[$internals] = this[$internals] = { - accessors: {} - }; - const accessors = internals.accessors; - const prototype3 = this.prototype; - function defineAccessor(_header) { - const lHeader = normalizeHeader(_header); - if (!accessors[lHeader]) { - buildAccessors(prototype3, _header); - accessors[lHeader] = true; + Fe(e, "Unknown value"); + } + function La(e, t, r, n = 0) { + return e._createPrismaPromise((i) => { + let o = t.customDataProxyFetch; + return "transaction" in t && i !== void 0 && (t.transaction?.kind === "batch" && t.transaction.lock.then(), t.transaction = i), n === r.length ? e._executeRequest(t) : r[n]({ model: t.model, operation: t.model ? t.action : t.clientMethod, args: _a(t.args ?? {}), __internalParams: t, query: (s, a = t) => { + let l = a.customDataProxyFetch; + return a.customDataProxyFetch = qa(o, l), a.args = s, La(e, a, r, n + 1); + } }); + }); + } + function Na(e, t) { + let { jsModelName: r, action: n, clientMethod: i } = t, o = r ? n : i; + if (e._extensions.isEmpty()) return e._executeRequest(t); + let s = e._extensions.getAllQueryCallbacks(r ?? "$none", o); + return La(e, t, s); + } + function Ma(e) { + return (t) => { + let r = { requests: t }, n = t[0].extensions.getAllBatchQueryCallbacks(); + return n.length ? $a(r, n, 0, e) : e(r); + }; + } + function $a(e, t, r, n) { + if (r === t.length) return n(e); + let i = e.customDataProxyFetch, o = e.requests[0].transaction; + return t[r]({ args: { queries: e.requests.map((s) => ({ model: s.modelName, operation: s.action, args: s.args })), transaction: o ? { isolationLevel: o.kind === "batch" ? o.isolationLevel : void 0 } : void 0 }, __internalParams: e, query(s, a = e) { + let l = a.customDataProxyFetch; + return a.customDataProxyFetch = qa(i, l), $a(a, t, r + 1, n); + } }); + } + var Fa = (e) => e; + function qa(e = Fa, t = Fa) { + return (r) => e(t(r)); + } + var ja = L("prisma:client"); + var Va = { Vercel: "vercel", "Netlify CI": "netlify" }; + function Ba({ postinstall: e, ciName: t, clientVersion: r }) { + if (ja("checkPlatformCaching:postinstall", e), ja("checkPlatformCaching:ciName", t), e === true && t && t in Va) { + let n = `Prisma has detected that this project was built on ${t}, which caches dependencies. This leads to an outdated Prisma Client because Prisma's auto-generation isn't triggered. To fix this, make sure to run the \`prisma generate\` command during the build process. + +Learn how: https://pris.ly/d/${Va[t]}-build`; + throw console.error(n), new R(n, r); } } - utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); - return this; - } -}; -AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); -utils_default.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { - let mapped = key[0].toUpperCase() + key.slice(1); - return { - get: () => value, - set(headerValue) { - this[mapped] = headerValue; + function Ua(e, t) { + return e ? e.datasources ? e.datasources : e.datasourceUrl ? { [t[0]]: { url: e.datasourceUrl } } : {} : {}; } - }; -}); -utils_default.freezeMethods(AxiosHeaders); -var AxiosHeaders_default = AxiosHeaders; + var Jd = "Cloudflare-Workers"; + var Wd = "node"; + function Ga() { + return typeof Netlify == "object" ? "netlify" : typeof EdgeRuntime == "string" ? "edge-light" : globalThis.navigator?.userAgent === Jd ? "workerd" : globalThis.Deno ? "deno" : globalThis.__lagon__ ? "lagon" : globalThis.process?.release?.name === Wd ? "node" : globalThis.Bun ? "bun" : globalThis.fastly ? "fastly" : "unknown"; + } + var Hd = { node: "Node.js", workerd: "Cloudflare Workers", deno: "Deno and Deno Deploy", netlify: "Netlify Edge Functions", "edge-light": "Edge Runtime (Vercel Edge Functions, Vercel Edge Middleware, Next.js (Pages Router) Edge API Routes, Next.js (App Router) Edge Route Handlers or Next.js Middleware)" }; + function In() { + let e = Ga(); + return { id: e, prettyName: Hd[e] || e, isEdge: ["workerd", "deno", "netlify", "edge-light"].includes(e) }; + } + var Ka = k(__require("fs")); + var Er = k(__require("path")); + function On(e) { + let { runtimeBinaryTarget: t } = e; + return `Add "${t}" to \`binaryTargets\` in the "schema.prisma" file and run \`prisma generate\` after saving it: -// node_modules/axios/lib/core/transformData.js -function transformData(fns, response) { - const config3 = this || defaults_default; - const context = response || config3; - const headers = AxiosHeaders_default.from(context.headers); - let data = context.data; - utils_default.forEach(fns, function transform(fn2) { - data = fn2.call(config3, data, headers.normalize(), response ? response.status : void 0); - }); - headers.normalize(); - return data; -} +${Kd(e)}`; + } + function Kd(e) { + let { generator: t, generatorBinaryTargets: r, runtimeBinaryTarget: n } = e, i = { fromEnvVar: null, value: n }, o = [...r, i]; + return hi({ ...t, binaryTargets: o }); + } + function Xe(e) { + let { runtimeBinaryTarget: t } = e; + return `Prisma Client could not locate the Query Engine for runtime "${t}".`; + } + function et(e) { + let { searchedLocations: t } = e; + return `The following locations have been searched: +${[...new Set(t)].map((i) => ` ${i}`).join(` +`)}`; + } + function Qa(e) { + let { runtimeBinaryTarget: t } = e; + return `${Xe(e)} -// node_modules/axios/lib/cancel/isCancel.js -function isCancel(value) { - return !!(value && value.__CANCEL__); -} +This happened because \`binaryTargets\` have been pinned, but the actual deployment also required "${t}". +${On(e)} -// node_modules/axios/lib/cancel/CanceledError.js -function CanceledError(message, config3, request) { - AxiosError_default.call(this, message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config3, request); - this.name = "CanceledError"; -} -utils_default.inherits(CanceledError, AxiosError_default, { - __CANCEL__: true -}); -var CanceledError_default = CanceledError; +${et(e)}`; + } + function kn(e) { + return `We would appreciate if you could take the time to share some information with us. +Please help us by answering a few questions: https://pris.ly/${e}`; + } + function Dn(e) { + let { errorStack: t } = e; + return t?.match(/\/\.next|\/next@|\/next\//) ? ` -// node_modules/axios/lib/core/settle.js -function settle(resolve, reject, response) { - const validateStatus2 = response.config.validateStatus; - if (!response.status || !validateStatus2 || validateStatus2(response.status)) { - resolve(response); - } else { - reject(new AxiosError_default( - "Request failed with status code " + response.status, - [AxiosError_default.ERR_BAD_REQUEST, AxiosError_default.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); - } -} +We detected that you are using Next.js, learn how to fix this: https://pris.ly/d/engine-not-found-nextjs.` : ""; + } + function Ja(e) { + let { queryEngineName: t } = e; + return `${Xe(e)}${Dn(e)} -// node_modules/axios/lib/helpers/isAbsoluteURL.js -function isAbsoluteURL(url2) { - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url2); -} +This is likely caused by a bundler that has not copied "${t}" next to the resulting bundle. +Ensure that "${t}" has been copied next to the bundle or in "${e.expectedLocation}". -// node_modules/axios/lib/helpers/combineURLs.js -function combineURLs(baseURL, relativeURL) { - return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; -} +${kn("engine-not-found-bundler-investigation")} -// node_modules/axios/lib/core/buildFullPath.js -function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) { - let isRelativeUrl = !isAbsoluteURL(requestedURL); - if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; -} +${et(e)}`; + } + function Wa(e) { + let { runtimeBinaryTarget: t, generatorBinaryTargets: r } = e, n = r.find((i) => i.native); + return `${Xe(e)} -// node_modules/axios/lib/adapters/http.js -var import_proxy_from_env = __toESM(require_proxy_from_env(), 1); -var import_follow_redirects = __toESM(require_follow_redirects(), 1); -import http from "http"; -import https from "https"; -import util2 from "util"; -import zlib from "zlib"; +This happened because Prisma Client was generated for "${n?.value ?? "unknown"}", but the actual deployment required "${t}". +${On(e)} -// node_modules/axios/lib/env/data.js -var VERSION = "1.9.0"; +${et(e)}`; + } + function Ha(e) { + let { queryEngineName: t } = e; + return `${Xe(e)}${Dn(e)} -// node_modules/axios/lib/helpers/parseProtocol.js -function parseProtocol(url2) { - const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url2); - return match && match[1] || ""; -} +This is likely caused by tooling that has not copied "${t}" to the deployment folder. +Ensure that you ran \`prisma generate\` and that "${t}" has been copied to "${e.expectedLocation}". -// node_modules/axios/lib/helpers/fromDataURI.js -var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; -function fromDataURI(uri, asBlob, options) { - const _Blob = options && options.Blob || platform_default.classes.Blob; - const protocol = parseProtocol(uri); - if (asBlob === void 0 && _Blob) { - asBlob = true; - } - if (protocol === "data") { - uri = protocol.length ? uri.slice(protocol.length + 1) : uri; - const match = DATA_URL_PATTERN.exec(uri); - if (!match) { - throw new AxiosError_default("Invalid URL", AxiosError_default.ERR_INVALID_URL); +${kn("engine-not-found-tooling-investigation")} + +${et(e)}`; } - const mime = match[1]; - const isBase64 = match[2]; - const body = match[3]; - const buffer2 = Buffer.from(decodeURIComponent(body), isBase64 ? "base64" : "utf8"); - if (asBlob) { - if (!_Blob) { - throw new AxiosError_default("Blob is not supported", AxiosError_default.ERR_NOT_SUPPORT); + var zd = L("prisma:client:engines:resolveEnginePath"); + var Yd = () => new RegExp("runtime[\\\\/]library\\.m?js$"); + async function za(e, t) { + let r = { binary: process.env.PRISMA_QUERY_ENGINE_BINARY, library: process.env.PRISMA_QUERY_ENGINE_LIBRARY }[e] ?? t.prismaPath; + if (r !== void 0) return r; + let { enginePath: n, searchedLocations: i } = await Zd(e, t); + if (zd("enginePath", n), n !== void 0 && e === "binary" && li(n), n !== void 0) return t.prismaPath = n; + let o = await nt(), s = t.generator?.binaryTargets ?? [], a = s.some((d) => d.native), l = !s.some((d) => d.value === o), u = __filename.match(Yd()) === null, c = { searchedLocations: i, generatorBinaryTargets: s, generator: t.generator, runtimeBinaryTarget: o, queryEngineName: Ya(e, o), expectedLocation: Er.default.relative(process.cwd(), t.dirname), errorStack: new Error().stack }, p; + throw a && l ? p = Wa(c) : l ? p = Qa(c) : u ? p = Ja(c) : p = Ha(c), new R(p, t.clientVersion); + } + async function Zd(engineType, config) { + let binaryTarget = await nt(), searchedLocations = [], dirname = eval("__dirname"), searchLocations = [config.dirname, Er.default.resolve(dirname, ".."), config.generator?.output?.value ?? dirname, Er.default.resolve(dirname, "../../../.prisma/client"), "/tmp/prisma-engines", config.cwd]; + __filename.includes("resolveEnginePath") && searchLocations.push(Yo()); + for (let e of searchLocations) { + let t = Ya(engineType, binaryTarget), r = Er.default.join(e, t); + if (searchedLocations.push(e), Ka.default.existsSync(r)) return { enginePath: r, searchedLocations }; } - return new _Blob([buffer2], { type: mime }); + return { enginePath: void 0, searchedLocations }; } - return buffer2; - } - throw new AxiosError_default("Unsupported protocol " + protocol, AxiosError_default.ERR_NOT_SUPPORT); -} + function Ya(e, t) { + return e === "library" ? qr(t, "fs") : `query-engine-${t}${t === "windows" ? ".exe" : ""}`; + } + var Hi = k(bi()); + function Za(e) { + return e ? e.replace(/".*"/g, '"X"').replace(/[\s:\[]([+-]?([0-9]*[.])?[0-9]+)/g, (t) => `${t[0]}5`) : ""; + } + function Xa(e) { + return e.split(` +`).map((t) => t.replace(/^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)\s*/, "").replace(/\+\d+\s*ms$/, "")).join(` +`); + } + var el = k(hs()); + function tl({ title: e, user: t = "prisma", repo: r = "prisma", template: n = "bug_report.yml", body: i }) { + return (0, el.default)({ user: t, repo: r, template: n, title: e, body: i }); + } + function rl({ version: e, binaryTarget: t, title: r, description: n, engineVersion: i, database: o, query: s }) { + let a = So(6e3 - (s?.length ?? 0)), l = Xa((0, Hi.default)(a)), u = n ? `# Description +\`\`\` +${n} +\`\`\`` : "", c = (0, Hi.default)(`Hi Prisma Team! My Prisma Client just crashed. This is the report: +## Versions + +| Name | Version | +|-----------------|--------------------| +| Node | ${process.version?.padEnd(19)}| +| OS | ${t?.padEnd(19)}| +| Prisma Client | ${e?.padEnd(19)}| +| Query Engine | ${i?.padEnd(19)}| +| Database | ${o?.padEnd(19)}| + +${u} + +## Logs +\`\`\` +${l} +\`\`\` + +## Client Snippet +\`\`\`ts +// PLEASE FILL YOUR CODE SNIPPET HERE +\`\`\` + +## Schema +\`\`\`prisma +// PLEASE ADD YOUR SCHEMA HERE IF POSSIBLE +\`\`\` -// node_modules/axios/lib/adapters/http.js -import stream3 from "stream"; +## Prisma Engine Query +\`\`\` +${s ? Za(s) : ""} +\`\`\` +`), p = tl({ title: r, body: c }); + return `${r} -// node_modules/axios/lib/helpers/AxiosTransformStream.js -import stream from "stream"; -var kInternals = Symbol("internals"); -var AxiosTransformStream = class extends stream.Transform { - constructor(options) { - options = utils_default.toFlatObject(options, { - maxRate: 0, - chunkSize: 64 * 1024, - minChunkSize: 100, - timeWindow: 500, - ticksRate: 2, - samplesCount: 15 - }, null, (prop, source) => { - return !utils_default.isUndefined(source[prop]); - }); - super({ - readableHighWaterMark: options.chunkSize - }); - const internals = this[kInternals] = { - timeWindow: options.timeWindow, - chunkSize: options.chunkSize, - maxRate: options.maxRate, - minChunkSize: options.minChunkSize, - bytesSeen: 0, - isCaptured: false, - notifiedBytesLoaded: 0, - ts: Date.now(), - bytes: 0, - onReadCallback: null +This is a non-recoverable error which probably happens when the Prisma Query Engine has a panic. + +${X(p)} + +If you want the Prisma team to look into it, please open the link above \u{1F64F} +To increase the chance of success, please post your schema and a snippet of +how you used Prisma Client in the issue. +`; + } + function Nt({ inlineDatasources: e, overrideDatasources: t, env: r, clientVersion: n }) { + let i, o = Object.keys(e)[0], s = e[o]?.url, a = t[o]?.url; + if (o === void 0 ? i = void 0 : a ? i = a : s?.value ? i = s.value : s?.fromEnvVar && (i = r[s.fromEnvVar]), s?.fromEnvVar !== void 0 && i === void 0) throw new R(`error: Environment variable not found: ${s.fromEnvVar}.`, n); + if (i === void 0) throw new R("error: Missing URL environment variable, value, or override.", n); + return i; + } + var _n = class extends Error { + constructor(t, r) { + super(t), this.clientVersion = r.clientVersion, this.cause = r.cause; + } + get [Symbol.toStringTag]() { + return this.name; + } }; - this.on("newListener", (event) => { - if (event === "progress") { - if (!internals.isCaptured) { - internals.isCaptured = true; - } + var se = class extends _n { + constructor(t, r) { + super(t, r), this.isRetryable = r.isRetryable ?? true; } - }); - } - _read(size5) { - const internals = this[kInternals]; - if (internals.onReadCallback) { - internals.onReadCallback(); + }; + function A(e, t) { + return { ...e, isRetryable: t }; } - return super._read(size5); - } - _transform(chunk, encoding, callback) { - const internals = this[kInternals]; - const maxRate = internals.maxRate; - const readableHighWaterMark = this.readableHighWaterMark; - const timeWindow = internals.timeWindow; - const divider = 1e3 / timeWindow; - const bytesThreshold = maxRate / divider; - const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; - const pushChunk = (_chunk, _callback) => { - const bytes = Buffer.byteLength(_chunk); - internals.bytesSeen += bytes; - internals.bytes += bytes; - internals.isCaptured && this.emit("progress", internals.bytesSeen); - if (this.push(_chunk)) { - process.nextTick(_callback); - } else { - internals.onReadCallback = () => { - internals.onReadCallback = null; - process.nextTick(_callback); - }; + var Mt = class extends se { + constructor(r) { + super("This request must be retried", A(r, true)); + this.name = "ForcedRetryError"; + this.code = "P5001"; } }; - const transformChunk = (_chunk, _callback) => { - const chunkSize = Buffer.byteLength(_chunk); - let chunkRemainder = null; - let maxChunkSize = readableHighWaterMark; - let bytesLeft; - let passed = 0; - if (maxRate) { - const now = Date.now(); - if (!internals.ts || (passed = now - internals.ts) >= timeWindow) { - internals.ts = now; - bytesLeft = bytesThreshold - internals.bytes; - internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; - passed = 0; - } - bytesLeft = bytesThreshold - internals.bytes; + w(Mt, "ForcedRetryError"); + var at = class extends se { + constructor(r, n) { + super(r, A(n, false)); + this.name = "InvalidDatasourceError"; + this.code = "P6001"; } - if (maxRate) { - if (bytesLeft <= 0) { - return setTimeout(() => { - _callback(null, _chunk); - }, timeWindow - passed); - } - if (bytesLeft < maxChunkSize) { - maxChunkSize = bytesLeft; + }; + w(at, "InvalidDatasourceError"); + var lt = class extends se { + constructor(r, n) { + super(r, A(n, false)); + this.name = "NotImplementedYetError"; + this.code = "P5004"; + } + }; + w(lt, "NotImplementedYetError"); + var q = class extends se { + constructor(t, r) { + super(t, r), this.response = r.response; + let n = this.response.headers.get("prisma-request-id"); + if (n) { + let i = `(The request id was: ${n})`; + this.message = this.message + " " + i; } } - if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) { - chunkRemainder = _chunk.subarray(maxChunkSize); - _chunk = _chunk.subarray(0, maxChunkSize); + }; + var ut = class extends q { + constructor(r) { + super("Schema needs to be uploaded", A(r, true)); + this.name = "SchemaMissingError"; + this.code = "P5005"; } - pushChunk(_chunk, chunkRemainder ? () => { - process.nextTick(_callback, null, chunkRemainder); - } : _callback); }; - transformChunk(chunk, function transformNextChunk(err, _chunk) { - if (err) { - return callback(err); + w(ut, "SchemaMissingError"); + var Ki = "This request could not be understood by the server"; + var wr = class extends q { + constructor(r, n, i) { + super(n || Ki, A(r, false)); + this.name = "BadRequestError"; + this.code = "P5000"; + i && (this.code = i); } - if (_chunk) { - transformChunk(_chunk, transformNextChunk); - } else { - callback(null); + }; + w(wr, "BadRequestError"); + var xr = class extends q { + constructor(r, n) { + super("Engine not started: healthcheck timeout", A(r, true)); + this.name = "HealthcheckTimeoutError"; + this.code = "P5013"; + this.logs = n; + } + }; + w(xr, "HealthcheckTimeoutError"); + var Pr = class extends q { + constructor(r, n, i) { + super(n, A(r, true)); + this.name = "EngineStartupError"; + this.code = "P5014"; + this.logs = i; + } + }; + w(Pr, "EngineStartupError"); + var vr = class extends q { + constructor(r) { + super("Engine version is not supported", A(r, false)); + this.name = "EngineVersionNotSupportedError"; + this.code = "P5012"; + } + }; + w(vr, "EngineVersionNotSupportedError"); + var zi = "Request timed out"; + var Tr = class extends q { + constructor(r, n = zi) { + super(n, A(r, false)); + this.name = "GatewayTimeoutError"; + this.code = "P5009"; + } + }; + w(Tr, "GatewayTimeoutError"); + var Xd = "Interactive transaction error"; + var Rr = class extends q { + constructor(r, n = Xd) { + super(n, A(r, false)); + this.name = "InteractiveTransactionError"; + this.code = "P5015"; + } + }; + w(Rr, "InteractiveTransactionError"); + var em = "Request parameters are invalid"; + var Cr = class extends q { + constructor(r, n = em) { + super(n, A(r, false)); + this.name = "InvalidRequestError"; + this.code = "P5011"; + } + }; + w(Cr, "InvalidRequestError"); + var Yi = "Requested resource does not exist"; + var Sr = class extends q { + constructor(r, n = Yi) { + super(n, A(r, false)); + this.name = "NotFoundError"; + this.code = "P5003"; + } + }; + w(Sr, "NotFoundError"); + var Zi = "Unknown server error"; + var $t = class extends q { + constructor(r, n, i) { + super(n || Zi, A(r, true)); + this.name = "ServerError"; + this.code = "P5006"; + this.logs = i; + } + }; + w($t, "ServerError"); + var Xi = "Unauthorized, check your connection string"; + var Ar = class extends q { + constructor(r, n = Xi) { + super(n, A(r, false)); + this.name = "UnauthorizedError"; + this.code = "P5007"; + } + }; + w(Ar, "UnauthorizedError"); + var eo = "Usage exceeded, retry again later"; + var Ir = class extends q { + constructor(r, n = eo) { + super(n, A(r, true)); + this.name = "UsageExceededError"; + this.code = "P5008"; + } + }; + w(Ir, "UsageExceededError"); + async function tm(e) { + let t; + try { + t = await e.text(); + } catch { + return { type: "EmptyError" }; + } + try { + let r = JSON.parse(t); + if (typeof r == "string") switch (r) { + case "InternalDataProxyError": + return { type: "DataProxyError", body: r }; + default: + return { type: "UnknownTextError", body: r }; + } + if (typeof r == "object" && r !== null) { + if ("is_panic" in r && "message" in r && "error_code" in r) return { type: "QueryEngineError", body: r }; + if ("EngineNotStarted" in r || "InteractiveTransactionMisrouted" in r || "InvalidRequestError" in r) { + let n = Object.values(r)[0].reason; + return typeof n == "string" && !["SchemaMissing", "EngineVersionNotSupported"].includes(n) ? { type: "UnknownJsonError", body: r } : { type: "DataProxyError", body: r }; + } + } + return { type: "UnknownJsonError", body: r }; + } catch { + return t === "" ? { type: "EmptyError" } : { type: "UnknownTextError", body: t }; } - }); - } -}; -var AxiosTransformStream_default = AxiosTransformStream; - -// node_modules/axios/lib/adapters/http.js -import { EventEmitter } from "events"; - -// node_modules/axios/lib/helpers/formDataToStream.js -import util from "util"; -import { Readable } from "stream"; - -// node_modules/axios/lib/helpers/readBlob.js -var { asyncIterator } = Symbol; -var readBlob = async function* (blob) { - if (blob.stream) { - yield* blob.stream(); - } else if (blob.arrayBuffer) { - yield await blob.arrayBuffer(); - } else if (blob[asyncIterator]) { - yield* blob[asyncIterator](); - } else { - yield blob; - } -}; -var readBlob_default = readBlob; - -// node_modules/axios/lib/helpers/formDataToStream.js -var BOUNDARY_ALPHABET = platform_default.ALPHABET.ALPHA_DIGIT + "-_"; -var textEncoder = typeof TextEncoder === "function" ? new TextEncoder() : new util.TextEncoder(); -var CRLF = "\r\n"; -var CRLF_BYTES = textEncoder.encode(CRLF); -var CRLF_BYTES_COUNT = 2; -var FormDataPart = class { - constructor(name, value) { - const { escapeName } = this.constructor; - const isStringValue = utils_default.isString(value); - let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF}`; - if (isStringValue) { - value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); - } else { - headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; } - this.headers = textEncoder.encode(headers + CRLF); - this.contentLength = isStringValue ? value.byteLength : value.size; - this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; - this.name = name; - this.value = value; - } - async *encode() { - yield this.headers; - const { value } = this; - if (utils_default.isTypedArray(value)) { - yield value; - } else { - yield* readBlob_default(value); + async function Or(e, t) { + if (e.ok) return; + let r = { clientVersion: t, response: e }, n = await tm(e); + if (n.type === "QueryEngineError") throw new V(n.body.message, { code: n.body.error_code, clientVersion: t }); + if (n.type === "DataProxyError") { + if (n.body === "InternalDataProxyError") throw new $t(r, "Internal Data Proxy error"); + if ("EngineNotStarted" in n.body) { + if (n.body.EngineNotStarted.reason === "SchemaMissing") return new ut(r); + if (n.body.EngineNotStarted.reason === "EngineVersionNotSupported") throw new vr(r); + if ("EngineStartupError" in n.body.EngineNotStarted.reason) { + let { msg: i, logs: o } = n.body.EngineNotStarted.reason.EngineStartupError; + throw new Pr(r, i, o); + } + if ("KnownEngineStartupError" in n.body.EngineNotStarted.reason) { + let { msg: i, error_code: o } = n.body.EngineNotStarted.reason.KnownEngineStartupError; + throw new R(i, t, o); + } + if ("HealthcheckTimeout" in n.body.EngineNotStarted.reason) { + let { logs: i } = n.body.EngineNotStarted.reason.HealthcheckTimeout; + throw new xr(r, i); + } + } + if ("InteractiveTransactionMisrouted" in n.body) { + let i = { IDParseError: "Could not parse interactive transaction ID", NoQueryEngineFoundError: "Could not find Query Engine for the specified host and transaction ID", TransactionStartError: "Could not start interactive transaction" }; + throw new Rr(r, i[n.body.InteractiveTransactionMisrouted.reason]); + } + if ("InvalidRequestError" in n.body) throw new Cr(r, n.body.InvalidRequestError.reason); + } + if (e.status === 401 || e.status === 403) throw new Ar(r, qt(Xi, n)); + if (e.status === 404) return new Sr(r, qt(Yi, n)); + if (e.status === 429) throw new Ir(r, qt(eo, n)); + if (e.status === 504) throw new Tr(r, qt(zi, n)); + if (e.status >= 500) throw new $t(r, qt(Zi, n)); + if (e.status >= 400) throw new wr(r, qt(Ki, n)); } - yield CRLF_BYTES; - } - static escapeName(name) { - return String(name).replace(/[\r\n"]/g, (match) => ({ - "\r": "%0D", - "\n": "%0A", - '"': "%22" - })[match]); - } -}; -var formDataToStream = (form, headersHandler, options) => { - const { - tag = "form-data-boundary", - size: size5 = 25, - boundary = tag + "-" + platform_default.generateString(size5, BOUNDARY_ALPHABET) - } = options || {}; - if (!utils_default.isFormData(form)) { - throw TypeError("FormData instance required"); - } - if (boundary.length < 1 || boundary.length > 70) { - throw Error("boundary must be 10-70 characters long"); - } - const boundaryBytes = textEncoder.encode("--" + boundary + CRLF); - const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF); - let contentLength = footerBytes.byteLength; - const parts = Array.from(form.entries()).map(([name, value]) => { - const part = new FormDataPart(name, value); - contentLength += part.size; - return part; - }); - contentLength += boundaryBytes.byteLength * parts.length; - contentLength = utils_default.toFiniteNumber(contentLength); - const computedHeaders = { - "Content-Type": `multipart/form-data; boundary=${boundary}` - }; - if (Number.isFinite(contentLength)) { - computedHeaders["Content-Length"] = contentLength; - } - headersHandler && headersHandler(computedHeaders); - return Readable.from(async function* () { - for (const part of parts) { - yield boundaryBytes; - yield* part.encode(); + function qt(e, t) { + return t.type === "EmptyError" ? e : `${e}: ${JSON.stringify(t)}`; } - yield footerBytes; - }()); -}; -var formDataToStream_default = formDataToStream; - -// node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js -import stream2 from "stream"; -var ZlibHeaderTransformStream = class extends stream2.Transform { - __transform(chunk, encoding, callback) { - this.push(chunk); - callback(); - } - _transform(chunk, encoding, callback) { - if (chunk.length !== 0) { - this._transform = this.__transform; - if (chunk[0] !== 120) { - const header = Buffer.alloc(2); - header[0] = 120; - header[1] = 156; - this.push(header, encoding); - } + function nl(e) { + let t = Math.pow(2, e) * 50, r = Math.ceil(Math.random() * t) - Math.ceil(t / 2), n = t + r; + return new Promise((i) => setTimeout(() => i(n), n)); } - this.__transform(chunk, encoding, callback); - } -}; -var ZlibHeaderTransformStream_default = ZlibHeaderTransformStream; - -// node_modules/axios/lib/helpers/callbackify.js -var callbackify = (fn2, reducer) => { - return utils_default.isAsyncFn(fn2) ? function(...args) { - const cb = args.pop(); - fn2.apply(this, args).then((value) => { - try { - reducer ? cb(null, ...reducer(value)) : cb(null, value); - } catch (err) { - cb(err); + var $e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + function il(e) { + let t = new TextEncoder().encode(e), r = "", n = t.byteLength, i = n % 3, o = n - i, s, a, l, u, c; + for (let p = 0; p < o; p = p + 3) c = t[p] << 16 | t[p + 1] << 8 | t[p + 2], s = (c & 16515072) >> 18, a = (c & 258048) >> 12, l = (c & 4032) >> 6, u = c & 63, r += $e[s] + $e[a] + $e[l] + $e[u]; + return i == 1 ? (c = t[o], s = (c & 252) >> 2, a = (c & 3) << 4, r += $e[s] + $e[a] + "==") : i == 2 && (c = t[o] << 8 | t[o + 1], s = (c & 64512) >> 10, a = (c & 1008) >> 4, l = (c & 15) << 2, r += $e[s] + $e[a] + $e[l] + "="), r; + } + function ol(e) { + if (!!e.generator?.previewFeatures.some((r) => r.toLowerCase().includes("metrics"))) throw new R("The `metrics` preview feature is not yet available with Accelerate.\nPlease remove `metrics` from the `previewFeatures` in your schema.\n\nMore information about Accelerate: https://pris.ly/d/accelerate", e.clientVersion); + } + function rm(e) { + return e[0] * 1e3 + e[1] / 1e6; + } + function sl(e) { + return new Date(rm(e)); + } + var al = { "@prisma/debug": "workspace:*", "@prisma/engines-version": "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2", "@prisma/fetch-engine": "workspace:*", "@prisma/get-platform": "workspace:*" }; + var kr = class extends se { + constructor(r, n) { + super(`Cannot fetch data from service: +${r}`, A(n, true)); + this.name = "RequestError"; + this.code = "P5010"; + } + }; + w(kr, "RequestError"); + async function ct(e, t, r = (n) => n) { + let n = t.clientVersion; + try { + return typeof fetch == "function" ? await r(fetch)(e, t) : await r(to)(e, t); + } catch (i) { + let o = i.message ?? "Unknown error"; + throw new kr(o, { clientVersion: n }); } - }, cb); - } : fn2; -}; -var callbackify_default = callbackify; - -// node_modules/axios/lib/helpers/speedometer.js -function speedometer(samplesCount, min) { - samplesCount = samplesCount || 10; - const bytes = new Array(samplesCount); - const timestamps = new Array(samplesCount); - let head = 0; - let tail = 0; - let firstSampleTS; - min = min !== void 0 ? min : 1e3; - return function push(chunkLength) { - const now = Date.now(); - const startedAt = timestamps[tail]; - if (!firstSampleTS) { - firstSampleTS = now; } - bytes[head] = chunkLength; - timestamps[head] = now; - let i = tail; - let bytesCount = 0; - while (i !== head) { - bytesCount += bytes[i++]; - i = i % samplesCount; + function im(e) { + return { ...e.headers, "Content-Type": "application/json" }; } - head = (head + 1) % samplesCount; - if (head === tail) { - tail = (tail + 1) % samplesCount; + function om(e) { + return { method: e.method, headers: im(e) }; } - if (now - firstSampleTS < min) { - return; + function sm(e, t) { + return { text: () => Promise.resolve(Buffer.concat(e).toString()), json: () => Promise.resolve().then(() => JSON.parse(Buffer.concat(e).toString())), ok: t.statusCode >= 200 && t.statusCode <= 299, status: t.statusCode, url: t.url, headers: new ro(t.headers) }; } - const passed = startedAt && now - startedAt; - return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; - }; -} -var speedometer_default = speedometer; - -// node_modules/axios/lib/helpers/throttle.js -function throttle(fn2, freq) { - let timestamp = 0; - let threshold = 1e3 / freq; - let lastArgs; - let timer; - const invoke = (args, now = Date.now()) => { - timestamp = now; - lastArgs = null; - if (timer) { - clearTimeout(timer); - timer = null; + async function to(e, t = {}) { + let r = am("https"), n = om(t), i = [], { origin: o } = new URL(e); + return new Promise((s, a) => { + let l = r.request(e, n, (u) => { + let { statusCode: c, headers: { location: p } } = u; + c >= 301 && c <= 399 && p && (p.startsWith("http") === false ? s(to(`${o}${p}`, t)) : s(to(p, t))), u.on("data", (d) => i.push(d)), u.on("end", () => s(sm(i, u))), u.on("error", a); + }); + l.on("error", a), l.end(t.body ?? ""); + }); } - fn2.apply(null, args); - }; - const throttled = (...args) => { - const now = Date.now(); - const passed = now - timestamp; - if (passed >= threshold) { - invoke(args, now); - } else { - lastArgs = args; - if (!timer) { - timer = setTimeout(() => { - timer = null; - invoke(lastArgs); - }, threshold - passed); + var am = typeof __require < "u" ? __require : () => { + }; + var ro = class { + constructor(t = {}) { + this.headers = /* @__PURE__ */ new Map(); + for (let [r, n] of Object.entries(t)) if (typeof n == "string") this.headers.set(r, n); + else if (Array.isArray(n)) for (let i of n) this.headers.set(r, i); + } + append(t, r) { + this.headers.set(t, r); + } + delete(t) { + this.headers.delete(t); + } + get(t) { + return this.headers.get(t) ?? null; + } + has(t) { + return this.headers.has(t); + } + set(t, r) { + this.headers.set(t, r); + } + forEach(t, r) { + for (let [n, i] of this.headers) t.call(r, i, n, this); } - } - }; - const flush = () => lastArgs && invoke(lastArgs); - return [throttled, flush]; -} -var throttle_default = throttle; - -// node_modules/axios/lib/helpers/progressEventReducer.js -var progressEventReducer = (listener, isDownloadStream, freq = 3) => { - let bytesNotified = 0; - const _speedometer = speedometer_default(50, 250); - return throttle_default((e) => { - const loaded = e.loaded; - const total = e.lengthComputable ? e.total : void 0; - const progressBytes = loaded - bytesNotified; - const rate = _speedometer(progressBytes); - const inRange2 = loaded <= total; - bytesNotified = loaded; - const data = { - loaded, - total, - progress: total ? loaded / total : void 0, - bytes: progressBytes, - rate: rate ? rate : void 0, - estimated: rate && total && inRange2 ? (total - loaded) / rate : void 0, - event: e, - lengthComputable: total != null, - [isDownloadStream ? "download" : "upload"]: true }; - listener(data); - }, freq); -}; -var progressEventDecorator = (total, throttled) => { - const lengthComputable = total != null; - return [(loaded) => throttled[0]({ - lengthComputable, - total, - loaded - }), throttled[1]]; -}; -var asyncDecorator = (fn2) => (...args) => utils_default.asap(() => fn2(...args)); - -// node_modules/axios/lib/adapters/http.js -var zlibOptions = { - flush: zlib.constants.Z_SYNC_FLUSH, - finishFlush: zlib.constants.Z_SYNC_FLUSH -}; -var brotliOptions = { - flush: zlib.constants.BROTLI_OPERATION_FLUSH, - finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH -}; -var isBrotliSupported = utils_default.isFunction(zlib.createBrotliDecompress); -var { http: httpFollow, https: httpsFollow } = import_follow_redirects.default; -var isHttps = /https:?/; -var supportedProtocols = platform_default.protocols.map((protocol) => { - return protocol + ":"; -}); -var flushOnFinish = (stream4, [throttled, flush]) => { - stream4.on("end", flush).on("error", flush); - return throttled; -}; -function dispatchBeforeRedirect(options, responseDetails) { - if (options.beforeRedirects.proxy) { - options.beforeRedirects.proxy(options); - } - if (options.beforeRedirects.config) { - options.beforeRedirects.config(options, responseDetails); - } -} -function setProxy(options, configProxy, location) { - let proxy = configProxy; - if (!proxy && proxy !== false) { - const proxyUrl = import_proxy_from_env.default.getProxyForUrl(location); - if (proxyUrl) { - proxy = new URL(proxyUrl); - } - } - if (proxy) { - if (proxy.username) { - proxy.auth = (proxy.username || "") + ":" + (proxy.password || ""); - } - if (proxy.auth) { - if (proxy.auth.username || proxy.auth.password) { - proxy.auth = (proxy.auth.username || "") + ":" + (proxy.auth.password || ""); + var lm = /^[1-9][0-9]*\.[0-9]+\.[0-9]+$/; + var ll = L("prisma:client:dataproxyEngine"); + async function um(e, t) { + let r = al["@prisma/engines-version"], n = t.clientVersion ?? "unknown"; + if (process.env.PRISMA_CLIENT_DATA_PROXY_CLIENT_VERSION) return process.env.PRISMA_CLIENT_DATA_PROXY_CLIENT_VERSION; + if (e.includes("accelerate") && n !== "0.0.0" && n !== "in-memory") return n; + let [i, o] = n?.split("-") ?? []; + if (o === void 0 && lm.test(i)) return i; + if (o !== void 0 || n === "0.0.0" || n === "in-memory") { + if (e.startsWith("localhost") || e.startsWith("127.0.0.1")) return "0.0.0"; + let [s] = r.split("-") ?? [], [a, l, u] = s.split("."), c = cm(`<=${a}.${l}.${u}`), p = await ct(c, { clientVersion: n }); + if (!p.ok) throw new Error(`Failed to fetch stable Prisma version, unpkg.com status ${p.status} ${p.statusText}, response body: ${await p.text() || ""}`); + let d = await p.text(); + ll("length of body fetched from unpkg.com", d.length); + let f; + try { + f = JSON.parse(d); + } catch (g) { + throw console.error("JSON.parse error: body fetched from unpkg.com: ", d), g; + } + return f.version; } - const base64 = Buffer.from(proxy.auth, "utf8").toString("base64"); - options.headers["Proxy-Authorization"] = "Basic " + base64; + throw new lt("Only `major.minor.patch` versions are supported by Accelerate.", { clientVersion: n }); } - options.headers.host = options.hostname + (options.port ? ":" + options.port : ""); - const proxyHost = proxy.hostname || proxy.host; - options.hostname = proxyHost; - options.host = proxyHost; - options.port = proxy.port; - options.path = location; - if (proxy.protocol) { - options.protocol = proxy.protocol.includes(":") ? proxy.protocol : `${proxy.protocol}:`; + async function ul(e, t) { + let r = await um(e, t); + return ll("version", r), r; } - } - options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { - setProxy(redirectOptions, configProxy, redirectOptions.href); - }; -} -var isHttpAdapterSupported = typeof process !== "undefined" && utils_default.kindOf(process) === "process"; -var wrapAsync = (asyncExecutor) => { - return new Promise((resolve, reject) => { - let onDone; - let isDone; - const done = (value, isRejected) => { - if (isDone) return; - isDone = true; - onDone && onDone(value, isRejected); - }; - const _resolve = (value) => { - done(value); - resolve(value); - }; - const _reject = (reason) => { - done(reason, true); - reject(reason); - }; - asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject); - }); -}; -var resolveFamily = ({ address, family }) => { - if (!utils_default.isString(address)) { - throw TypeError("address must be a string"); - } - return { - address, - family: family || (address.indexOf(".") < 0 ? 6 : 4) - }; -}; -var buildAddressEntry = (address, family) => resolveFamily(utils_default.isObject(address) ? address : { address, family }); -var http_default = isHttpAdapterSupported && function httpAdapter(config3) { - return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { - let { data, lookup, family } = config3; - const { responseType, responseEncoding } = config3; - const method = config3.method.toUpperCase(); - let isDone; - let rejected = false; - let req; - if (lookup) { - const _lookup = callbackify_default(lookup, (value) => utils_default.isArray(value) ? value : [value]); - lookup = (hostname, opt, cb) => { - _lookup(hostname, opt, (err, arg0, arg1) => { - if (err) { - return cb(err); - } - const addresses = utils_default.isArray(arg0) ? arg0.map((addr) => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; - opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); - }); - }; + function cm(e) { + return encodeURI(`https://unpkg.com/prisma@${e}/package.json`); } - const emitter = new EventEmitter(); - const onFinished = () => { - if (config3.cancelToken) { - config3.cancelToken.unsubscribe(abort); + var cl = 3; + var no = L("prisma:client:dataproxyEngine"); + var io = class { + constructor({ apiKey: t, tracingHelper: r, logLevel: n, logQueries: i, engineHash: o }) { + this.apiKey = t, this.tracingHelper = r, this.logLevel = n, this.logQueries = i, this.engineHash = o; } - if (config3.signal) { - config3.signal.removeEventListener("abort", abort); + build({ traceparent: t, interactiveTransaction: r } = {}) { + let n = { Authorization: `Bearer ${this.apiKey}`, "Prisma-Engine-Hash": this.engineHash }; + this.tracingHelper.isEnabled() && (n.traceparent = t ?? this.tracingHelper.getTraceParent()), r && (n["X-transaction-id"] = r.id); + let i = this.buildCaptureSettings(); + return i.length > 0 && (n["X-capture-telemetry"] = i.join(", ")), n; + } + buildCaptureSettings() { + let t = []; + return this.tracingHelper.isEnabled() && t.push("tracing"), this.logLevel && t.push(this.logLevel), this.logQueries && t.push("query"), t; } - emitter.removeAllListeners(); }; - onDone((value, isRejected) => { - isDone = true; - if (isRejected) { - rejected = true; - onFinished(); + var Dr = class { + constructor(t) { + this.name = "DataProxyEngine"; + ol(t), this.config = t, this.env = { ...t.env, ...typeof process < "u" ? process.env : {} }, this.inlineSchema = il(t.inlineSchema), this.inlineDatasources = t.inlineDatasources, this.inlineSchemaHash = t.inlineSchemaHash, this.clientVersion = t.clientVersion, this.engineHash = t.engineVersion, this.logEmitter = t.logEmitter, this.tracingHelper = t.tracingHelper; } - }); - function abort(reason) { - emitter.emit("abort", !reason || reason.type ? new CanceledError_default(null, config3, req) : reason); - } - emitter.once("abort", reject); - if (config3.cancelToken || config3.signal) { - config3.cancelToken && config3.cancelToken.subscribe(abort); - if (config3.signal) { - config3.signal.aborted ? abort() : config3.signal.addEventListener("abort", abort); + apiKey() { + return this.headerBuilder.apiKey; } - } - const fullPath = buildFullPath(config3.baseURL, config3.url, config3.allowAbsoluteUrls); - const parsed = new URL(fullPath, platform_default.hasBrowserEnv ? platform_default.origin : void 0); - const protocol = parsed.protocol || supportedProtocols[0]; - if (protocol === "data:") { - let convertedData; - if (method !== "GET") { - return settle(resolve, reject, { - status: 405, - statusText: "method not allowed", - headers: {}, - config: config3 - }); + version() { + return this.engineHash; } - try { - convertedData = fromDataURI(config3.url, responseType === "blob", { - Blob: config3.env && config3.env.Blob + async start() { + this.startPromise !== void 0 && await this.startPromise, this.startPromise = (async () => { + let [t, r] = this.extractHostAndApiKey(); + this.host = t, this.headerBuilder = new io({ apiKey: r, tracingHelper: this.tracingHelper, logLevel: this.config.logLevel, logQueries: this.config.logQueries, engineHash: this.engineHash }), this.remoteClientVersion = await ul(t, this.config), no("host", this.host); + })(), await this.startPromise; + } + async stop() { + } + propagateResponseExtensions(t) { + t?.logs?.length && t.logs.forEach((r) => { + switch (r.level) { + case "debug": + case "error": + case "trace": + case "warn": + case "info": + break; + case "query": { + let n = typeof r.attributes.query == "string" ? r.attributes.query : ""; + if (!this.tracingHelper.isEnabled()) { + let [i] = n.split("/* traceparent"); + n = i; + } + this.logEmitter.emit("query", { query: n, timestamp: sl(r.timestamp), duration: Number(r.attributes.duration_ms), params: r.attributes.params, target: r.attributes.target }); + } + } + }), t?.traces?.length && this.tracingHelper.createEngineSpan({ span: true, spans: t.traces }); + } + onBeforeExit() { + throw new Error('"beforeExit" hook is not applicable to the remote query engine'); + } + async url(t) { + return await this.start(), `https://${this.host}/${this.remoteClientVersion}/${this.inlineSchemaHash}/${t}`; + } + async uploadSchema() { + let t = { name: "schemaUpload", internal: true }; + return this.tracingHelper.runInChildSpan(t, async () => { + let r = await ct(await this.url("schema"), { method: "PUT", headers: this.headerBuilder.build(), body: this.inlineSchema, clientVersion: this.clientVersion }); + r.ok || no("schema response status", r.status); + let n = await Or(r, this.clientVersion); + if (n) throw this.logEmitter.emit("warn", { message: `Error while uploading schema: ${n.message}`, timestamp: /* @__PURE__ */ new Date(), target: "" }), n; + this.logEmitter.emit("info", { message: `Schema (re)uploaded (hash: ${this.inlineSchemaHash})`, timestamp: /* @__PURE__ */ new Date(), target: "" }); }); - } catch (err) { - throw AxiosError_default.from(err, AxiosError_default.ERR_BAD_REQUEST, config3); } - if (responseType === "text") { - convertedData = convertedData.toString(responseEncoding); - if (!responseEncoding || responseEncoding === "utf8") { - convertedData = utils_default.stripBOM(convertedData); - } - } else if (responseType === "stream") { - convertedData = stream3.Readable.from(convertedData); + request(t, { traceparent: r, interactiveTransaction: n, customDataProxyFetch: i }) { + return this.requestInternal({ body: t, traceparent: r, interactiveTransaction: n, customDataProxyFetch: i }); } - return settle(resolve, reject, { - data: convertedData, - status: 200, - statusText: "OK", - headers: new AxiosHeaders_default(), - config: config3 - }); - } - if (supportedProtocols.indexOf(protocol) === -1) { - return reject(new AxiosError_default( - "Unsupported protocol " + protocol, - AxiosError_default.ERR_BAD_REQUEST, - config3 - )); - } - const headers = AxiosHeaders_default.from(config3.headers).normalize(); - headers.set("User-Agent", "axios/" + VERSION, false); - const { onUploadProgress, onDownloadProgress } = config3; - const maxRate = config3.maxRate; - let maxUploadRate = void 0; - let maxDownloadRate = void 0; - if (utils_default.isSpecCompliantForm(data)) { - const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); - data = formDataToStream_default(data, (formHeaders) => { - headers.set(formHeaders); - }, { - tag: `axios-${VERSION}-boundary`, - boundary: userBoundary && userBoundary[1] || void 0 - }); - } else if (utils_default.isFormData(data) && utils_default.isFunction(data.getHeaders)) { - headers.set(data.getHeaders()); - if (!headers.hasContentLength()) { + async requestBatch(t, { traceparent: r, transaction: n, customDataProxyFetch: i }) { + let o = n?.kind === "itx" ? n.options : void 0, s = Ft(t, n), { batchResult: a, elapsed: l } = await this.requestInternal({ body: s, customDataProxyFetch: i, interactiveTransaction: o, traceparent: r }); + return a.map((u) => "errors" in u && u.errors.length > 0 ? st(u.errors[0], this.clientVersion, this.config.activeProvider) : { data: u, elapsed: l }); + } + requestInternal({ body: t, traceparent: r, customDataProxyFetch: n, interactiveTransaction: i }) { + return this.withRetry({ actionGerund: "querying", callback: async ({ logHttpCall: o }) => { + let s = i ? `${i.payload.endpoint}/graphql` : await this.url("graphql"); + o(s); + let a = await ct(s, { method: "POST", headers: this.headerBuilder.build({ traceparent: r, interactiveTransaction: i }), body: JSON.stringify(t), clientVersion: this.clientVersion }, n); + a.ok || no("graphql response status", a.status), await this.handleError(await Or(a, this.clientVersion)); + let l = await a.json(), u = l.extensions; + if (u && this.propagateResponseExtensions(u), l.errors) throw l.errors.length === 1 ? st(l.errors[0], this.config.clientVersion, this.config.activeProvider) : new B(l.errors, { clientVersion: this.config.clientVersion }); + return l; + } }); + } + async transaction(t, r, n) { + let i = { start: "starting", commit: "committing", rollback: "rolling back" }; + return this.withRetry({ actionGerund: `${i[t]} transaction`, callback: async ({ logHttpCall: o }) => { + if (t === "start") { + let s = JSON.stringify({ max_wait: n.maxWait, timeout: n.timeout, isolation_level: n.isolationLevel }), a = await this.url("transaction/start"); + o(a); + let l = await ct(a, { method: "POST", headers: this.headerBuilder.build({ traceparent: r.traceparent }), body: s, clientVersion: this.clientVersion }); + await this.handleError(await Or(l, this.clientVersion)); + let u = await l.json(), c = u.extensions; + c && this.propagateResponseExtensions(c); + let p = u.id, d = u["data-proxy"].endpoint; + return { id: p, payload: { endpoint: d } }; + } else { + let s = `${n.payload.endpoint}/${t}`; + o(s); + let a = await ct(s, { method: "POST", headers: this.headerBuilder.build({ traceparent: r.traceparent }), clientVersion: this.clientVersion }); + await this.handleError(await Or(a, this.clientVersion)); + let u = (await a.json()).extensions; + u && this.propagateResponseExtensions(u); + return; + } + } }); + } + extractHostAndApiKey() { + let t = { clientVersion: this.clientVersion }, r = Object.keys(this.inlineDatasources)[0], n = Nt({ inlineDatasources: this.inlineDatasources, overrideDatasources: this.config.overrideDatasources, clientVersion: this.clientVersion, env: this.env }), i; try { - const knownLength = await util2.promisify(data.getLength).call(data); - Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); - } catch (e) { + i = new URL(n); + } catch { + throw new at(`Error validating datasource \`${r}\`: the URL must start with the protocol \`prisma://\``, t); } + let { protocol: o, host: s, searchParams: a } = i; + if (o !== "prisma:" && o !== "prisma+postgres:") throw new at(`Error validating datasource \`${r}\`: the URL must start with the protocol \`prisma://\``, t); + let l = a.get("api_key"); + if (l === null || l.length < 1) throw new at(`Error validating datasource \`${r}\`: the URL must contain a valid API key`, t); + return [s, l]; } - } else if (utils_default.isBlob(data) || utils_default.isFile(data)) { - data.size && headers.setContentType(data.type || "application/octet-stream"); - headers.setContentLength(data.size || 0); - data = stream3.Readable.from(readBlob_default(data)); - } else if (data && !utils_default.isStream(data)) { - if (Buffer.isBuffer(data)) { - } else if (utils_default.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils_default.isString(data)) { - data = Buffer.from(data, "utf-8"); - } else { - return reject(new AxiosError_default( - "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream", - AxiosError_default.ERR_BAD_REQUEST, - config3 - )); + metrics() { + throw new lt("Metrics are not yet supported for Accelerate", { clientVersion: this.clientVersion }); } - headers.setContentLength(data.length, false); - if (config3.maxBodyLength > -1 && data.length > config3.maxBodyLength) { - return reject(new AxiosError_default( - "Request body larger than maxBodyLength limit", - AxiosError_default.ERR_BAD_REQUEST, - config3 - )); + async withRetry(t) { + for (let r = 0; ; r++) { + let n = (i) => { + this.logEmitter.emit("info", { message: `Calling ${i} (n=${r})`, timestamp: /* @__PURE__ */ new Date(), target: "" }); + }; + try { + return await t.callback({ logHttpCall: n }); + } catch (i) { + if (!(i instanceof se) || !i.isRetryable) throw i; + if (r >= cl) throw i instanceof Mt ? i.cause : i; + this.logEmitter.emit("warn", { message: `Attempt ${r + 1}/${cl} failed for ${t.actionGerund}: ${i.message ?? "(unknown)"}`, timestamp: /* @__PURE__ */ new Date(), target: "" }); + let o = await nl(r); + this.logEmitter.emit("warn", { message: `Retrying after ${o}ms`, timestamp: /* @__PURE__ */ new Date(), target: "" }); + } + } } - } - const contentLength = utils_default.toFiniteNumber(headers.getContentLength()); - if (utils_default.isArray(maxRate)) { - maxUploadRate = maxRate[0]; - maxDownloadRate = maxRate[1]; - } else { - maxUploadRate = maxDownloadRate = maxRate; - } - if (data && (onUploadProgress || maxUploadRate)) { - if (!utils_default.isStream(data)) { - data = stream3.Readable.from(data, { objectMode: false }); + async handleError(t) { + if (t instanceof ut) throw await this.uploadSchema(), new Mt({ clientVersion: this.clientVersion, cause: t }); + if (t) throw t; + } + applyPendingMigrations() { + throw new Error("Method not implemented."); } - data = stream3.pipeline([data, new AxiosTransformStream_default({ - maxRate: utils_default.toFiniteNumber(maxUploadRate) - })], utils_default.noop); - onUploadProgress && data.on("progress", flushOnFinish( - data, - progressEventDecorator( - contentLength, - progressEventReducer(asyncDecorator(onUploadProgress), false, 3) - ) - )); + }; + function pl(e) { + if (e?.kind === "itx") return e.options.id; } - let auth = void 0; - if (config3.auth) { - const username = config3.auth.username || ""; - const password = config3.auth.password || ""; - auth = username + ":" + password; + var so = k(__require("os")); + var dl = k(__require("path")); + var oo = Symbol("PrismaLibraryEngineCache"); + function pm() { + let e = globalThis; + return e[oo] === void 0 && (e[oo] = {}), e[oo]; } - if (!auth && parsed.username) { - const urlUsername = parsed.username; - const urlPassword = parsed.password; - auth = urlUsername + ":" + urlPassword; + function dm(e) { + let t = pm(); + if (t[e] !== void 0) return t[e]; + let r = dl.default.toNamespacedPath(e), n = { exports: {} }, i = 0; + return process.platform !== "win32" && (i = so.default.constants.dlopen.RTLD_LAZY | so.default.constants.dlopen.RTLD_DEEPBIND), process.dlopen(n, r, i), t[e] = n.exports, n.exports; } - auth && headers.delete("authorization"); - let path; - try { - path = buildURL( - parsed.pathname + parsed.search, - config3.params, - config3.paramsSerializer - ).replace(/^\?/, ""); - } catch (err) { - const customErr = new Error(err.message); - customErr.config = config3; - customErr.url = config3.url; - customErr.exists = true; - return reject(customErr); + var ml = { async loadLibrary(e) { + let t = await Yn(), r = await za("library", e); + try { + return e.tracingHelper.runInChildSpan({ name: "loadLibrary", internal: true }, () => dm(r)); + } catch (n) { + let i = ui({ e: n, platformInfo: t, id: r }); + throw new R(i, e.clientVersion); + } + } }; + var ao; + var fl = { async loadLibrary(e) { + let { clientVersion: t, adapter: r, engineWasm: n } = e; + if (r === void 0) throw new R(`The \`adapter\` option for \`PrismaClient\` is required in this context (${In().prettyName})`, t); + if (n === void 0) throw new R("WASM engine was unexpectedly `undefined`", t); + ao === void 0 && (ao = (async () => { + let o = n.getRuntime(), s = await n.getQueryEngineWasmModule(); + if (s == null) throw new R("The loaded wasm module was unexpectedly `undefined` or `null` once loaded", t); + let a = { "./query_engine_bg.js": o }, l = new WebAssembly.Instance(s, a); + return o.__wbg_set_wasm(l.exports), o.QueryEngine; + })()); + let i = await ao; + return { debugPanic() { + return Promise.reject("{}"); + }, dmmf() { + return Promise.resolve("{}"); + }, version() { + return { commit: "unknown", version: "unknown" }; + }, QueryEngine: i }; + } }; + var mm = "P2036"; + var Ae = L("prisma:client:libraryEngine"); + function fm(e) { + return e.item_type === "query" && "query" in e; } - headers.set( - "Accept-Encoding", - "gzip, compress, deflate" + (isBrotliSupported ? ", br" : ""), - false - ); - const options = { - path, - method, - headers: headers.toJSON(), - agents: { http: config3.httpAgent, https: config3.httpsAgent }, - auth, - protocol, - family, - beforeRedirect: dispatchBeforeRedirect, - beforeRedirects: {} - }; - !utils_default.isUndefined(lookup) && (options.lookup = lookup); - if (config3.socketPath) { - options.socketPath = config3.socketPath; - } else { - options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; - options.port = parsed.port; - setProxy(options, config3.proxy, protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options.path); + function gm(e) { + return "level" in e ? e.level === "error" && e.message === "PANIC" : false; } - let transport; - const isHttpsRequest = isHttps.test(options.protocol); - options.agent = isHttpsRequest ? config3.httpsAgent : config3.httpAgent; - if (config3.transport) { - transport = config3.transport; - } else if (config3.maxRedirects === 0) { - transport = isHttpsRequest ? https : http; - } else { - if (config3.maxRedirects) { - options.maxRedirects = config3.maxRedirects; + var gl = [...Jn, "native"]; + var _r = class { + constructor(t, r) { + this.name = "LibraryEngine"; + this.libraryLoader = r ?? ml, t.engineWasm !== void 0 && (this.libraryLoader = r ?? fl), this.config = t, this.libraryStarted = false, this.logQueries = t.logQueries ?? false, this.logLevel = t.logLevel ?? "error", this.logEmitter = t.logEmitter, this.datamodel = t.inlineSchema, t.enableDebugLogs && (this.logLevel = "debug"); + let n = Object.keys(t.overrideDatasources)[0], i = t.overrideDatasources[n]?.url; + n !== void 0 && i !== void 0 && (this.datasourceOverrides = { [n]: i }), this.libraryInstantiationPromise = this.instantiateLibrary(); } - if (config3.beforeRedirect) { - options.beforeRedirects.config = config3.beforeRedirect; + async applyPendingMigrations() { + throw new Error("Cannot call this method from this type of engine instance"); } - transport = isHttpsRequest ? httpsFollow : httpFollow; - } - if (config3.maxBodyLength > -1) { - options.maxBodyLength = config3.maxBodyLength; - } else { - options.maxBodyLength = Infinity; - } - if (config3.insecureHTTPParser) { - options.insecureHTTPParser = config3.insecureHTTPParser; - } - req = transport.request(options, function handleResponse(res) { - if (req.destroyed) return; - const streams = [res]; - const responseLength = +res.headers["content-length"]; - if (onDownloadProgress || maxDownloadRate) { - const transformStream = new AxiosTransformStream_default({ - maxRate: utils_default.toFiniteNumber(maxDownloadRate) - }); - onDownloadProgress && transformStream.on("progress", flushOnFinish( - transformStream, - progressEventDecorator( - responseLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) - ) - )); - streams.push(transformStream); + async transaction(t, r, n) { + await this.start(); + let i = JSON.stringify(r), o; + if (t === "start") { + let a = JSON.stringify({ max_wait: n.maxWait, timeout: n.timeout, isolation_level: n.isolationLevel }); + o = await this.engine?.startTransaction(a, i); + } else t === "commit" ? o = await this.engine?.commitTransaction(n.id, i) : t === "rollback" && (o = await this.engine?.rollbackTransaction(n.id, i)); + let s = this.parseEngineResponse(o); + if (hm(s)) { + let a = this.getExternalAdapterError(s); + throw a ? a.error : new V(s.message, { code: s.error_code, clientVersion: this.config.clientVersion, meta: s.meta }); + } + return s; } - let responseStream = res; - const lastRequest = res.req || req; - if (config3.decompress !== false && res.headers["content-encoding"]) { - if (method === "HEAD" || res.statusCode === 204) { - delete res.headers["content-encoding"]; + async instantiateLibrary() { + if (Ae("internalSetup"), this.libraryInstantiationPromise) return this.libraryInstantiationPromise; + Qn(), this.binaryTarget = await this.getCurrentBinaryTarget(), await this.loadEngine(), this.version(); + } + async getCurrentBinaryTarget() { + { + if (this.binaryTarget) return this.binaryTarget; + let t = await nt(); + if (!gl.includes(t)) throw new R(`Unknown ${ce("PRISMA_QUERY_ENGINE_LIBRARY")} ${ce(H(t))}. Possible binaryTargets: ${qe(gl.join(", "))} or a path to the query engine library. +You may have to run ${qe("prisma generate")} for your changes to take effect.`, this.config.clientVersion); + return t; } - switch ((res.headers["content-encoding"] || "").toLowerCase()) { - /*eslint default-case:0*/ - case "gzip": - case "x-gzip": - case "compress": - case "x-compress": - streams.push(zlib.createUnzip(zlibOptions)); - delete res.headers["content-encoding"]; - break; - case "deflate": - streams.push(new ZlibHeaderTransformStream_default()); - streams.push(zlib.createUnzip(zlibOptions)); - delete res.headers["content-encoding"]; - break; - case "br": - if (isBrotliSupported) { - streams.push(zlib.createBrotliDecompress(brotliOptions)); - delete res.headers["content-encoding"]; - } + } + parseEngineResponse(t) { + if (!t) throw new B("Response from the Engine was empty", { clientVersion: this.config.clientVersion }); + try { + return JSON.parse(t); + } catch { + throw new B("Unable to JSON.parse response from engine", { clientVersion: this.config.clientVersion }); } } - responseStream = streams.length > 1 ? stream3.pipeline(streams, utils_default.noop) : streams[0]; - const offListeners = stream3.finished(responseStream, () => { - offListeners(); - onFinished(); - }); - const response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: new AxiosHeaders_default(res.headers), - config: config3, - request: lastRequest - }; - if (responseType === "stream") { - response.data = responseStream; - settle(resolve, reject, response); - } else { - const responseBuffer = []; - let totalResponseBytes = 0; - responseStream.on("data", function handleStreamData(chunk) { - responseBuffer.push(chunk); - totalResponseBytes += chunk.length; - if (config3.maxContentLength > -1 && totalResponseBytes > config3.maxContentLength) { - rejected = true; - responseStream.destroy(); - reject(new AxiosError_default( - "maxContentLength size of " + config3.maxContentLength + " exceeded", - AxiosError_default.ERR_BAD_RESPONSE, - config3, - lastRequest - )); - } - }); - responseStream.on("aborted", function handlerStreamAborted() { - if (rejected) { - return; - } - const err = new AxiosError_default( - "stream has been aborted", - AxiosError_default.ERR_BAD_RESPONSE, - config3, - lastRequest - ); - responseStream.destroy(err); - reject(err); - }); - responseStream.on("error", function handleStreamError(err) { - if (req.destroyed) return; - reject(AxiosError_default.from(err, null, config3, lastRequest)); - }); - responseStream.on("end", function handleStreamEnd() { + async loadEngine() { + if (!this.engine) { + this.QueryEngineConstructor || (this.library = await this.libraryLoader.loadLibrary(this.config), this.QueryEngineConstructor = this.library.QueryEngine); try { - let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); - if (responseType !== "arraybuffer") { - responseData = responseData.toString(responseEncoding); - if (!responseEncoding || responseEncoding === "utf8") { - responseData = utils_default.stripBOM(responseData); - } - } - response.data = responseData; - } catch (err) { - return reject(AxiosError_default.from(err, null, config3, response.request, response)); + let t = new WeakRef(this), { adapter: r } = this.config; + r && Ae("Using driver adapter: %O", r), this.engine = new this.QueryEngineConstructor({ datamodel: this.datamodel, env: process.env, logQueries: this.config.logQueries ?? false, ignoreEnvVarErrors: true, datasourceOverrides: this.datasourceOverrides ?? {}, logLevel: this.logLevel, configDir: this.config.cwd, engineProtocol: "json" }, (n) => { + t.deref()?.logger(n); + }, r); + } catch (t) { + let r = t, n = this.parseInitError(r.message); + throw typeof n == "string" ? r : new R(n.message, this.config.clientVersion, n.error_code); } - settle(resolve, reject, response); - }); + } } - emitter.once("abort", (err) => { - if (!responseStream.destroyed) { - responseStream.emit("error", err); - responseStream.destroy(); + logger(t) { + let r = this.parseEngineResponse(t); + if (r) { + if ("span" in r) { + this.config.tracingHelper.createEngineSpan(r); + return; + } + r.level = r?.level.toLowerCase() ?? "unknown", fm(r) ? this.logEmitter.emit("query", { timestamp: /* @__PURE__ */ new Date(), query: r.query, params: r.params, duration: Number(r.duration_ms), target: r.module_path }) : gm(r) ? this.loggerRustPanic = new le(lo(this, `${r.message}: ${r.reason} in ${r.file}:${r.line}:${r.column}`), this.config.clientVersion) : this.logEmitter.emit(r.level, { timestamp: /* @__PURE__ */ new Date(), message: r.message, target: r.module_path }); } - }); - }); - emitter.once("abort", (err) => { - reject(err); - req.destroy(err); - }); - req.on("error", function handleRequestError(err) { - reject(AxiosError_default.from(err, null, config3, req)); - }); - req.on("socket", function handleRequestSocket(socket) { - socket.setKeepAlive(true, 1e3 * 60); - }); - if (config3.timeout) { - const timeout = parseInt(config3.timeout, 10); - if (Number.isNaN(timeout)) { - reject(new AxiosError_default( - "error trying to parse `config.timeout` to int", - AxiosError_default.ERR_BAD_OPTION_VALUE, - config3, - req - )); - return; } - req.setTimeout(timeout, function handleRequestTimeout() { - if (isDone) return; - let timeoutErrorMessage = config3.timeout ? "timeout of " + config3.timeout + "ms exceeded" : "timeout exceeded"; - const transitional2 = config3.transitional || transitional_default; - if (config3.timeoutErrorMessage) { - timeoutErrorMessage = config3.timeoutErrorMessage; + parseInitError(t) { + try { + return JSON.parse(t); + } catch { } - reject(new AxiosError_default( - timeoutErrorMessage, - transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, - config3, - req - )); - abort(); - }); - } - if (utils_default.isStream(data)) { - let ended = false; - let errored = false; - data.on("end", () => { - ended = true; - }); - data.once("error", (err) => { - errored = true; - req.destroy(err); - }); - data.on("close", () => { - if (!ended && !errored) { - abort(new CanceledError_default("Request stream has been aborted", config3, req)); + return t; + } + parseRequestError(t) { + try { + return JSON.parse(t); + } catch { } - }); - data.pipe(req); - } else { - req.end(data); - } - }); -}; - -// node_modules/axios/lib/helpers/isURLSameOrigin.js -var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url2) => { - url2 = new URL(url2, platform_default.origin); - return origin2.protocol === url2.protocol && origin2.host === url2.host && (isMSIE || origin2.port === url2.port); -})( - new URL(platform_default.origin), - platform_default.navigator && /(msie|trident)/i.test(platform_default.navigator.userAgent) -) : () => true; - -// node_modules/axios/lib/helpers/cookies.js -var cookies_default = platform_default.hasStandardBrowserEnv ? ( - // Standard browser envs support document.cookie - { - write(name, value, expires, path, domain, secure) { - const cookie = [name + "=" + encodeURIComponent(value)]; - utils_default.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); - utils_default.isString(path) && cookie.push("path=" + path); - utils_default.isString(domain) && cookie.push("domain=" + domain); - secure === true && cookie.push("secure"); - document.cookie = cookie.join("; "); - }, - read(name) { - const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)")); - return match ? decodeURIComponent(match[3]) : null; - }, - remove(name) { - this.write(name, "", Date.now() - 864e5); - } - } -) : ( - // Non-standard browser env (web workers, react-native) lack needed support. - { - write() { - }, - read() { - return null; - }, - remove() { - } - } -); - -// node_modules/axios/lib/core/mergeConfig.js -var headersToObject = (thing) => thing instanceof AxiosHeaders_default ? { ...thing } : thing; -function mergeConfig(config1, config22) { - config22 = config22 || {}; - const config3 = {}; - function getMergedValue(target, source, prop, caseless) { - if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) { - return utils_default.merge.call({ caseless }, target, source); - } else if (utils_default.isPlainObject(source)) { - return utils_default.merge({}, source); - } else if (utils_default.isArray(source)) { - return source.slice(); - } - return source; - } - function mergeDeepProperties(a, b2, prop, caseless) { - if (!utils_default.isUndefined(b2)) { - return getMergedValue(a, b2, prop, caseless); - } else if (!utils_default.isUndefined(a)) { - return getMergedValue(void 0, a, prop, caseless); - } - } - function valueFromConfig2(a, b2) { - if (!utils_default.isUndefined(b2)) { - return getMergedValue(void 0, b2); - } - } - function defaultToConfig2(a, b2) { - if (!utils_default.isUndefined(b2)) { - return getMergedValue(void 0, b2); - } else if (!utils_default.isUndefined(a)) { - return getMergedValue(void 0, a); - } - } - function mergeDirectKeys(a, b2, prop) { - if (prop in config22) { - return getMergedValue(a, b2); - } else if (prop in config1) { - return getMergedValue(void 0, a); - } - } - const mergeMap = { - url: valueFromConfig2, - method: valueFromConfig2, - data: valueFromConfig2, - baseURL: defaultToConfig2, - transformRequest: defaultToConfig2, - transformResponse: defaultToConfig2, - paramsSerializer: defaultToConfig2, - timeout: defaultToConfig2, - timeoutMessage: defaultToConfig2, - withCredentials: defaultToConfig2, - withXSRFToken: defaultToConfig2, - adapter: defaultToConfig2, - responseType: defaultToConfig2, - xsrfCookieName: defaultToConfig2, - xsrfHeaderName: defaultToConfig2, - onUploadProgress: defaultToConfig2, - onDownloadProgress: defaultToConfig2, - decompress: defaultToConfig2, - maxContentLength: defaultToConfig2, - maxBodyLength: defaultToConfig2, - beforeRedirect: defaultToConfig2, - transport: defaultToConfig2, - httpAgent: defaultToConfig2, - httpsAgent: defaultToConfig2, - cancelToken: defaultToConfig2, - socketPath: defaultToConfig2, - responseEncoding: defaultToConfig2, - validateStatus: mergeDirectKeys, - headers: (a, b2, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b2), prop, true) - }; - utils_default.forEach(Object.keys(Object.assign({}, config1, config22)), function computeConfigValue(prop) { - const merge2 = mergeMap[prop] || mergeDeepProperties; - const configValue = merge2(config1[prop], config22[prop], prop); - utils_default.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config3[prop] = configValue); - }); - return config3; -} - -// node_modules/axios/lib/helpers/resolveConfig.js -var resolveConfig_default = (config3) => { - const newConfig = mergeConfig({}, config3); - let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; - newConfig.headers = headers = AxiosHeaders_default.from(headers); - newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config3.params, config3.paramsSerializer); - if (auth) { - headers.set( - "Authorization", - "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : "")) - ); - } - let contentType; - if (utils_default.isFormData(data)) { - if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv) { - headers.setContentType(void 0); - } else if ((contentType = headers.getContentType()) !== false) { - const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; - headers.setContentType([type || "multipart/form-data", ...tokens].join("; ")); - } - } - if (platform_default.hasStandardBrowserEnv) { - withXSRFToken && utils_default.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); - if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin_default(newConfig.url)) { - const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies_default.read(xsrfCookieName); - if (xsrfValue) { - headers.set(xsrfHeaderName, xsrfValue); + return t; + } + onBeforeExit() { + throw new Error('"beforeExit" hook is not applicable to the library engine since Prisma 5.0.0, it is only relevant and implemented for the binary engine. Please add your event listener to the `process` object directly instead.'); } - } - } - return newConfig; -}; - -// node_modules/axios/lib/adapters/xhr.js -var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; -var xhr_default = isXHRAdapterSupported && function(config3) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - const _config = resolveConfig_default(config3); - let requestData = _config.data; - const requestHeaders = AxiosHeaders_default.from(_config.headers).normalize(); - let { responseType, onUploadProgress, onDownloadProgress } = _config; - let onCanceled; - let uploadThrottled, downloadThrottled; - let flushUpload, flushDownload; - function done() { - flushUpload && flushUpload(); - flushDownload && flushDownload(); - _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); - _config.signal && _config.signal.removeEventListener("abort", onCanceled); - } - let request = new XMLHttpRequest(); - request.open(_config.method.toUpperCase(), _config.url, true); - request.timeout = _config.timeout; - function onloadend() { - if (!request) { - return; + async start() { + if (await this.libraryInstantiationPromise, await this.libraryStoppingPromise, this.libraryStartingPromise) return Ae(`library already starting, this.libraryStarted: ${this.libraryStarted}`), this.libraryStartingPromise; + if (this.libraryStarted) return; + let t = async () => { + Ae("library starting"); + try { + let r = { traceparent: this.config.tracingHelper.getTraceParent() }; + await this.engine?.connect(JSON.stringify(r)), this.libraryStarted = true, Ae("library started"); + } catch (r) { + let n = this.parseInitError(r.message); + throw typeof n == "string" ? r : new R(n.message, this.config.clientVersion, n.error_code); + } finally { + this.libraryStartingPromise = void 0; + } + }; + return this.libraryStartingPromise = this.config.tracingHelper.runInChildSpan("connect", t), this.libraryStartingPromise; } - const responseHeaders = AxiosHeaders_default.from( - "getAllResponseHeaders" in request && request.getAllResponseHeaders() - ); - const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; - const response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config3, - request - }; - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); - request = null; - } - if ("onloadend" in request) { - request.onloadend = onloadend; - } else { - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; + async stop() { + if (await this.libraryStartingPromise, await this.executingQueryPromise, this.libraryStoppingPromise) return Ae("library is already stopping"), this.libraryStoppingPromise; + if (!this.libraryStarted) return; + let t = async () => { + await new Promise((n) => setTimeout(n, 5)), Ae("library stopping"); + let r = { traceparent: this.config.tracingHelper.getTraceParent() }; + await this.engine?.disconnect(JSON.stringify(r)), this.libraryStarted = false, this.libraryStoppingPromise = void 0, Ae("library stopped"); + }; + return this.libraryStoppingPromise = this.config.tracingHelper.runInChildSpan("disconnect", t), this.libraryStoppingPromise; + } + version() { + return this.versionInfo = this.library?.version(), this.versionInfo?.version ?? "unknown"; + } + debugPanic(t) { + return this.library?.debugPanic(t); + } + async request(t, { traceparent: r, interactiveTransaction: n }) { + Ae(`sending request, this.libraryStarted: ${this.libraryStarted}`); + let i = JSON.stringify({ traceparent: r }), o = JSON.stringify(t); + try { + await this.start(), this.executingQueryPromise = this.engine?.query(o, i, n?.id), this.lastQuery = o; + let s = this.parseEngineResponse(await this.executingQueryPromise); + if (s.errors) throw s.errors.length === 1 ? this.buildQueryError(s.errors[0]) : new B(JSON.stringify(s.errors), { clientVersion: this.config.clientVersion }); + if (this.loggerRustPanic) throw this.loggerRustPanic; + return { data: s, elapsed: 0 }; + } catch (s) { + if (s instanceof R) throw s; + if (s.code === "GenericFailure" && s.message?.startsWith("PANIC:")) throw new le(lo(this, s.message), this.config.clientVersion); + let a = this.parseRequestError(s.message); + throw typeof a == "string" ? s : new B(`${a.message} +${a.backtrace}`, { clientVersion: this.config.clientVersion }); } - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { - return; + } + async requestBatch(t, { transaction: r, traceparent: n }) { + Ae("requestBatch"); + let i = Ft(t, r); + await this.start(), this.lastQuery = JSON.stringify(i), this.executingQueryPromise = this.engine.query(this.lastQuery, JSON.stringify({ traceparent: n }), pl(r)); + let o = await this.executingQueryPromise, s = this.parseEngineResponse(o); + if (s.errors) throw s.errors.length === 1 ? this.buildQueryError(s.errors[0]) : new B(JSON.stringify(s.errors), { clientVersion: this.config.clientVersion }); + let { batchResult: a, errors: l } = s; + if (Array.isArray(a)) return a.map((u) => u.errors && u.errors.length > 0 ? this.loggerRustPanic ?? this.buildQueryError(u.errors[0]) : { data: u, elapsed: 0 }); + throw l && l.length === 1 ? new Error(l[0].error) : new Error(JSON.stringify(s)); + } + buildQueryError(t) { + if (t.user_facing_error.is_panic) return new le(lo(this, t.user_facing_error.message), this.config.clientVersion); + let r = this.getExternalAdapterError(t.user_facing_error); + return r ? r.error : st(t, this.config.clientVersion, this.config.activeProvider); + } + getExternalAdapterError(t) { + if (t.error_code === mm && this.config.adapter) { + let r = t.meta?.id; + Yr(typeof r == "number", "Malformed external JS error received from the engine"); + let n = this.config.adapter.errorRegistry.consumeError(r); + return Yr(n, "External error with reported id was not registered"), n; } - setTimeout(onloadend); - }; - } - request.onabort = function handleAbort() { - if (!request) { - return; } - reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config3, request)); - request = null; - }; - request.onerror = function handleError() { - reject(new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config3, request)); - request = null; - }; - request.ontimeout = function handleTimeout() { - let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded"; - const transitional2 = _config.transitional || transitional_default; - if (_config.timeoutErrorMessage) { - timeoutErrorMessage = _config.timeoutErrorMessage; + async metrics(t) { + await this.start(); + let r = await this.engine.metrics(JSON.stringify(t)); + return t.format === "prometheus" ? r : this.parseEngineResponse(r); } - reject(new AxiosError_default( - timeoutErrorMessage, - transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, - config3, - request - )); - request = null; }; - requestData === void 0 && requestHeaders.setContentType(null); - if ("setRequestHeader" in request) { - utils_default.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { - request.setRequestHeader(key, val); - }); - } - if (!utils_default.isUndefined(_config.withCredentials)) { - request.withCredentials = !!_config.withCredentials; + function hm(e) { + return typeof e == "object" && e !== null && e.error_code !== void 0; } - if (responseType && responseType !== "json") { - request.responseType = _config.responseType; + function lo(e, t) { + return rl({ binaryTarget: e.binaryTarget, title: t, version: e.config.clientVersion, engineVersion: e.versionInfo?.commit, database: e.config.activeProvider, query: e.lastQuery }); } - if (onDownloadProgress) { - [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true); - request.addEventListener("progress", downloadThrottled); + function hl({ copyEngine: e = true }, t) { + let r; + try { + r = Nt({ inlineDatasources: t.inlineDatasources, overrideDatasources: t.overrideDatasources, env: { ...t.env, ...process.env }, clientVersion: t.clientVersion }); + } catch { + } + let n = !!(r?.startsWith("prisma://") || r?.startsWith("prisma+postgres://")); + e && n && tr("recommend--no-engine", "In production, we recommend using `prisma generate --no-engine` (See: `prisma generate --help`)"); + let i = Yt(t.generator), o = n || !e, s = !!t.adapter, a = i === "library", l = i === "binary"; + if (o && s || s && false) { + let u; + throw e ? r?.startsWith("prisma://") ? u = ["Prisma Client was configured to use the `adapter` option but the URL was a `prisma://` URL.", "Please either use the `prisma://` URL or remove the `adapter` from the Prisma Client constructor."] : u = ["Prisma Client was configured to use both the `adapter` and Accelerate, please chose one."] : u = ["Prisma Client was configured to use the `adapter` option but `prisma generate` was run with `--no-engine`.", "Please run `prisma generate` without `--no-engine` to be able to use Prisma Client with the adapter."], new J(u.join(` +`), { clientVersion: t.clientVersion }); + } + if (o) return new Dr(t); + if (a) return new _r(t); + throw new J("Invalid client engine type, please use `library` or `binary`", { clientVersion: t.clientVersion }); } - if (onUploadProgress && request.upload) { - [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress); - request.upload.addEventListener("progress", uploadThrottled); - request.upload.addEventListener("loadend", flushUpload); + function Fn({ generator: e }) { + return e?.previewFeatures ?? []; } - if (_config.cancelToken || _config.signal) { - onCanceled = (cancel) => { - if (!request) { - return; - } - reject(!cancel || cancel.type ? new CanceledError_default(null, config3, request) : cancel); - request.abort(); - request = null; - }; - _config.cancelToken && _config.cancelToken.subscribe(onCanceled); - if (_config.signal) { - _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled); + var yl = (e) => ({ command: e }); + var bl = (e) => e.strings.reduce((t, r, n) => `${t}@P${n}${r}`); + function jt(e) { + try { + return El(e, "fast"); + } catch { + return El(e, "slow"); } } - const protocol = parseProtocol(_config.url); - if (protocol && platform_default.protocols.indexOf(protocol) === -1) { - reject(new AxiosError_default("Unsupported protocol " + protocol + ":", AxiosError_default.ERR_BAD_REQUEST, config3)); - return; + function El(e, t) { + return JSON.stringify(e.map((r) => xl(r, t))); } - request.send(requestData || null); - }); -}; + function xl(e, t) { + return Array.isArray(e) ? e.map((r) => xl(r, t)) : typeof e == "bigint" ? { prisma__type: "bigint", prisma__value: e.toString() } : Pt(e) ? { prisma__type: "date", prisma__value: e.toJSON() } : xe.isDecimal(e) ? { prisma__type: "decimal", prisma__value: e.toJSON() } : Buffer.isBuffer(e) ? { prisma__type: "bytes", prisma__value: e.toString("base64") } : ym(e) || ArrayBuffer.isView(e) ? { prisma__type: "bytes", prisma__value: Buffer.from(e).toString("base64") } : typeof e == "object" && t === "slow" ? Pl(e) : e; + } + function ym(e) { + return e instanceof ArrayBuffer || e instanceof SharedArrayBuffer ? true : typeof e == "object" && e !== null ? e[Symbol.toStringTag] === "ArrayBuffer" || e[Symbol.toStringTag] === "SharedArrayBuffer" : false; + } + function Pl(e) { + if (typeof e != "object" || e === null) return e; + if (typeof e.toJSON == "function") return e.toJSON(); + if (Array.isArray(e)) return e.map(wl); + let t = {}; + for (let r of Object.keys(e)) t[r] = wl(e[r]); + return t; + } + function wl(e) { + return typeof e == "bigint" ? e.toString() : Pl(e); + } + var bm = ["$connect", "$disconnect", "$on", "$transaction", "$use", "$extends"]; + var vl = bm; + var Em = /^(\s*alter\s)/i; + var Tl = L("prisma:client"); + function uo(e, t, r, n) { + if (!(e !== "postgresql" && e !== "cockroachdb") && r.length > 0 && Em.exec(t)) throw new Error(`Running ALTER using ${n} is not supported +Using the example below you can still execute your query with Prisma, but please note that it is vulnerable to SQL injection attacks and requires you to take care of input sanitization. -// node_modules/axios/lib/helpers/composeSignals.js -var composeSignals = (signals, timeout) => { - const { length } = signals = signals ? signals.filter(Boolean) : []; - if (timeout || length) { - let controller = new AbortController(); - let aborted; - const onabort = function(reason) { - if (!aborted) { - aborted = true; - unsubscribe(); - const err = reason instanceof Error ? reason : this.reason; - controller.abort(err instanceof AxiosError_default ? err : new CanceledError_default(err instanceof Error ? err.message : err)); - } - }; - let timer = timeout && setTimeout(() => { - timer = null; - onabort(new AxiosError_default(`timeout ${timeout} of ms exceeded`, AxiosError_default.ETIMEDOUT)); - }, timeout); - const unsubscribe = () => { - if (signals) { - timer && clearTimeout(timer); - timer = null; - signals.forEach((signal2) => { - signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort); - }); - signals = null; - } - }; - signals.forEach((signal2) => signal2.addEventListener("abort", onabort)); - const { signal } = controller; - signal.unsubscribe = () => utils_default.asap(unsubscribe); - return signal; - } -}; -var composeSignals_default = composeSignals; +Example: + await prisma.$executeRawUnsafe(\`ALTER USER prisma WITH PASSWORD '\${password}'\`) -// node_modules/axios/lib/helpers/trackStream.js -var streamChunk = function* (chunk, chunkSize) { - let len = chunk.byteLength; - if (!chunkSize || len < chunkSize) { - yield chunk; - return; - } - let pos = 0; - let end; - while (pos < len) { - end = pos + chunkSize; - yield chunk.slice(pos, end); - pos = end; - } -}; -var readBytes = async function* (iterable, chunkSize) { - for await (const chunk of readStream(iterable)) { - yield* streamChunk(chunk, chunkSize); - } -}; -var readStream = async function* (stream4) { - if (stream4[Symbol.asyncIterator]) { - yield* stream4; - return; - } - const reader = stream4.getReader(); - try { - for (; ; ) { - const { done, value } = await reader.read(); - if (done) { - break; - } - yield value; - } - } finally { - await reader.cancel(); - } -}; -var trackStream = (stream4, chunkSize, onProgress, onFinish) => { - const iterator2 = readBytes(stream4, chunkSize); - let bytes = 0; - let done; - let _onFinish = (e) => { - if (!done) { - done = true; - onFinish && onFinish(e); +More Information: https://pris.ly/d/execute-raw +`); } - }; - return new ReadableStream({ - async pull(controller) { - try { - const { done: done2, value } = await iterator2.next(); - if (done2) { - _onFinish(); - controller.close(); - return; + var co = ({ clientMethod: e, activeProvider: t }) => (r) => { + let n = "", i; + if (pa(r)) n = r.sql, i = { values: jt(r.values), __prismaRawParameters__: true }; + else if (Array.isArray(r)) { + let [o, ...s] = r; + n = o, i = { values: jt(s || []), __prismaRawParameters__: true }; + } else switch (t) { + case "sqlite": + case "mysql": { + n = r.sql, i = { values: jt(r.values), __prismaRawParameters__: true }; + break; } - let len = value.byteLength; - if (onProgress) { - let loadedBytes = bytes += len; - onProgress(loadedBytes); + case "cockroachdb": + case "postgresql": + case "postgres": { + n = r.text, i = { values: jt(r.values), __prismaRawParameters__: true }; + break; } - controller.enqueue(new Uint8Array(value)); - } catch (err) { - _onFinish(err); - throw err; + case "sqlserver": { + n = bl(r), i = { values: jt(r.values), __prismaRawParameters__: true }; + break; + } + default: + throw new Error(`The ${t} provider does not support ${e}`); } - }, - cancel(reason) { - _onFinish(reason); - return iterator2.return(); - } - }, { - highWaterMark: 2 - }); -}; - -// node_modules/axios/lib/adapters/fetch.js -var isFetchSupported = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function"; -var isReadableStreamSupported = isFetchSupported && typeof ReadableStream === "function"; -var encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder5) => (str) => encoder5.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Response(str).arrayBuffer())); -var test = (fn2, ...args) => { - try { - return !!fn2(...args); - } catch (e) { - return false; - } -}; -var supportsRequestStream = isReadableStreamSupported && test(() => { - let duplexAccessed = false; - const hasContentType = new Request(platform_default.origin, { - body: new ReadableStream(), - method: "POST", - get duplex() { - duplexAccessed = true; - return "half"; + return i?.values ? Tl(`prisma.${e}(${n}, ${i.values})`) : Tl(`prisma.${e}(${n})`), { query: n, parameters: i }; + }; + var Rl = { requestArgsToMiddlewareArgs(e) { + return [e.strings, ...e.values]; + }, middlewareArgsToRequestArgs(e) { + let [t, ...r] = e; + return new oe(t, r); + } }; + var Cl = { requestArgsToMiddlewareArgs(e) { + return [e]; + }, middlewareArgsToRequestArgs(e) { + return e[0]; + } }; + function po(e) { + return function(r) { + let n, i = (o = e) => { + try { + return o === void 0 || o?.kind === "itx" ? n ??= Sl(r(o)) : Sl(r(o)); + } catch (s) { + return Promise.reject(s); + } + }; + return { then(o, s) { + return i().then(o, s); + }, catch(o) { + return i().catch(o); + }, finally(o) { + return i().finally(o); + }, requestTransaction(o) { + let s = i(o); + return s.requestTransaction ? s.requestTransaction(o) : s; + }, [Symbol.toStringTag]: "PrismaPromise" }; + }; } - }).headers.has("Content-Type"); - return duplexAccessed && !hasContentType; -}); -var DEFAULT_CHUNK_SIZE = 64 * 1024; -var supportsResponseStream = isReadableStreamSupported && test(() => utils_default.isReadableStream(new Response("").body)); -var resolvers = { - stream: supportsResponseStream && ((res) => res.body) -}; -isFetchSupported && ((res) => { - ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => { - !resolvers[type] && (resolvers[type] = utils_default.isFunction(res[type]) ? (res2) => res2[type]() : (_, config3) => { - throw new AxiosError_default(`Response type '${type}' is not supported`, AxiosError_default.ERR_NOT_SUPPORT, config3); - }); - }); -})(new Response()); -var getBodyLength = async (body) => { - if (body == null) { - return 0; - } - if (utils_default.isBlob(body)) { - return body.size; - } - if (utils_default.isSpecCompliantForm(body)) { - const _request = new Request(platform_default.origin, { - method: "POST", - body - }); - return (await _request.arrayBuffer()).byteLength; - } - if (utils_default.isArrayBufferView(body) || utils_default.isArrayBuffer(body)) { - return body.byteLength; - } - if (utils_default.isURLSearchParams(body)) { - body = body + ""; - } - if (utils_default.isString(body)) { - return (await encodeText(body)).byteLength; - } -}; -var resolveBodyLength = async (headers, body) => { - const length = utils_default.toFiniteNumber(headers.getContentLength()); - return length == null ? getBodyLength(body) : length; -}; -var fetch_default = isFetchSupported && (async (config3) => { - let { - url: url2, - method, - data, - signal, - cancelToken, - timeout, - onDownloadProgress, - onUploadProgress, - responseType, - headers, - withCredentials = "same-origin", - fetchOptions - } = resolveConfig_default(config3); - responseType = responseType ? (responseType + "").toLowerCase() : "text"; - let composedSignal = composeSignals_default([signal, cancelToken && cancelToken.toAbortSignal()], timeout); - let request; - const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { - composedSignal.unsubscribe(); - }); - let requestContentLength; - try { - if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) { - let _request = new Request(url2, { - method: "POST", - body: data, - duplex: "half" - }); - let contentTypeHeader; - if (utils_default.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) { - headers.setContentType(contentTypeHeader); + function Sl(e) { + return typeof e.then == "function" ? e : Promise.resolve(e); + } + var Al = { isEnabled() { + return false; + }, getTraceParent() { + return "00-10-10-00"; + }, async createEngineSpan() { + }, getActiveContext() { + }, runInChildSpan(e, t) { + return t(); + } }; + var mo = class { + isEnabled() { + return this.getGlobalTracingHelper().isEnabled(); } - if (_request.body) { - const [onProgress, flush] = progressEventDecorator( - requestContentLength, - progressEventReducer(asyncDecorator(onUploadProgress)) - ); - data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + getTraceParent(t) { + return this.getGlobalTracingHelper().getTraceParent(t); + } + createEngineSpan(t) { + return this.getGlobalTracingHelper().createEngineSpan(t); + } + getActiveContext() { + return this.getGlobalTracingHelper().getActiveContext(); + } + runInChildSpan(t, r) { + return this.getGlobalTracingHelper().runInChildSpan(t, r); + } + getGlobalTracingHelper() { + return globalThis.PRISMA_INSTRUMENTATION?.helper ?? Al; } + }; + function Il(e) { + return e.includes("tracing") ? new mo() : Al; } - if (!utils_default.isString(withCredentials)) { - withCredentials = withCredentials ? "include" : "omit"; + function Ol(e, t = () => { + }) { + let r, n = new Promise((i) => r = i); + return { then(i) { + return --e === 0 && r(t()), i?.(n); + } }; } - const isCredentialsSupported = "credentials" in Request.prototype; - request = new Request(url2, { - ...fetchOptions, - signal: composedSignal, - method: method.toUpperCase(), - headers: headers.normalize().toJSON(), - body: data, - duplex: "half", - credentials: isCredentialsSupported ? withCredentials : void 0 - }); - let response = await fetch(request); - const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response"); - if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) { - const options = {}; - ["status", "statusText", "headers"].forEach((prop) => { - options[prop] = response[prop]; - }); - const responseContentLength = utils_default.toFiniteNumber(response.headers.get("content-length")); - const [onProgress, flush] = onDownloadProgress && progressEventDecorator( - responseContentLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true) - ) || []; - response = new Response( - trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { - flush && flush(); - unsubscribe && unsubscribe(); - }), - options - ); + function kl(e) { + return typeof e == "string" ? e : e.reduce((t, r) => { + let n = typeof r == "string" ? r : r.level; + return n === "query" ? t : t && (r === "info" || t === "info") ? "info" : n; + }, void 0); } - responseType = responseType || "text"; - let responseData = await resolvers[utils_default.findKey(resolvers, responseType) || "text"](response, config3); - !isStreamResponse && unsubscribe && unsubscribe(); - return await new Promise((resolve, reject) => { - settle(resolve, reject, { - data: responseData, - headers: AxiosHeaders_default.from(response.headers), - status: response.status, - statusText: response.statusText, - config: config3, - request - }); - }); - } catch (err) { - unsubscribe && unsubscribe(); - if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) { - throw Object.assign( - new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config3, request), - { - cause: err.cause || err - } - ); + var Ln = class { + constructor() { + this._middlewares = []; + } + use(t) { + this._middlewares.push(t); + } + get(t) { + return this._middlewares[t]; + } + has(t) { + return !!this._middlewares[t]; + } + length() { + return this._middlewares.length; + } + }; + var Fl = k(bi()); + function Nn(e) { + return typeof e.batchRequestIdx == "number"; } - throw AxiosError_default.from(err, err && err.code, config3, request); - } -}); - -// node_modules/axios/lib/adapters/adapters.js -var knownAdapters = { - http: http_default, - xhr: xhr_default, - fetch: fetch_default -}; -utils_default.forEach(knownAdapters, (fn2, value) => { - if (fn2) { - try { - Object.defineProperty(fn2, "name", { value }); - } catch (e) { + function Dl(e) { + if (e.action !== "findUnique" && e.action !== "findUniqueOrThrow") return; + let t = []; + return e.modelName && t.push(e.modelName), e.query.arguments && t.push(fo(e.query.arguments)), t.push(fo(e.query.selection)), t.join(""); } - Object.defineProperty(fn2, "adapterName", { value }); - } -}); -var renderReason = (reason) => `- ${reason}`; -var isResolvedHandle = (adapter) => utils_default.isFunction(adapter) || adapter === null || adapter === false; -var adapters_default = { - getAdapter: (adapters) => { - adapters = utils_default.isArray(adapters) ? adapters : [adapters]; - const { length } = adapters; - let nameOrAdapter; - let adapter; - const rejectedReasons = {}; - for (let i = 0; i < length; i++) { - nameOrAdapter = adapters[i]; - let id2; - adapter = nameOrAdapter; - if (!isResolvedHandle(nameOrAdapter)) { - adapter = knownAdapters[(id2 = String(nameOrAdapter)).toLowerCase()]; - if (adapter === void 0) { - throw new AxiosError_default(`Unknown adapter '${id2}'`); + function fo(e) { + return `(${Object.keys(e).sort().map((r) => { + let n = e[r]; + return typeof n == "object" && n !== null ? `(${r} ${fo(n)})` : r; + }).join(" ")})`; + } + var wm = { aggregate: false, aggregateRaw: false, createMany: true, createManyAndReturn: true, createOne: true, deleteMany: true, deleteOne: true, executeRaw: true, findFirst: false, findFirstOrThrow: false, findMany: false, findRaw: false, findUnique: false, findUniqueOrThrow: false, groupBy: false, queryRaw: false, runCommandRaw: true, updateMany: true, updateOne: true, upsertOne: true }; + function go(e) { + return wm[e]; + } + var Mn = class { + constructor(t) { + this.options = t; + this.tickActive = false; + this.batches = {}; + } + request(t) { + let r = this.options.batchBy(t); + return r ? (this.batches[r] || (this.batches[r] = [], this.tickActive || (this.tickActive = true, process.nextTick(() => { + this.dispatchBatches(), this.tickActive = false; + }))), new Promise((n, i) => { + this.batches[r].push({ request: t, resolve: n, reject: i }); + })) : this.options.singleLoader(t); + } + dispatchBatches() { + for (let t in this.batches) { + let r = this.batches[t]; + delete this.batches[t], r.length === 1 ? this.options.singleLoader(r[0].request).then((n) => { + n instanceof Error ? r[0].reject(n) : r[0].resolve(n); + }).catch((n) => { + r[0].reject(n); + }) : (r.sort((n, i) => this.options.batchOrder(n.request, i.request)), this.options.batchLoader(r.map((n) => n.request)).then((n) => { + if (n instanceof Error) for (let i = 0; i < r.length; i++) r[i].reject(n); + else for (let i = 0; i < r.length; i++) { + let o = n[i]; + o instanceof Error ? r[i].reject(o) : r[i].resolve(o); + } + }).catch((n) => { + for (let i = 0; i < r.length; i++) r[i].reject(n); + })); } } - if (adapter) { - break; + get [Symbol.toStringTag]() { + return "DataLoader"; + } + }; + function pt(e, t) { + if (t === null) return t; + switch (e) { + case "bigint": + return BigInt(t); + case "bytes": + return Buffer.from(t, "base64"); + case "decimal": + return new xe(t); + case "datetime": + case "date": + return new Date(t); + case "time": + return /* @__PURE__ */ new Date(`1970-01-01T${t}Z`); + case "bigint-array": + return t.map((r) => pt("bigint", r)); + case "bytes-array": + return t.map((r) => pt("bytes", r)); + case "decimal-array": + return t.map((r) => pt("decimal", r)); + case "datetime-array": + return t.map((r) => pt("datetime", r)); + case "date-array": + return t.map((r) => pt("date", r)); + case "time-array": + return t.map((r) => pt("time", r)); + default: + return t; } - rejectedReasons[id2 || "#" + i] = adapter; } - if (!adapter) { - const reasons = Object.entries(rejectedReasons).map( - ([id2, state]) => `adapter ${id2} ` + (state === false ? "is not supported by the environment" : "is not available in the build") - ); - let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"; - throw new AxiosError_default( - `There is no suitable adapter to dispatch the request ` + s, - "ERR_NOT_SUPPORT" - ); + function _l(e) { + let t = [], r = xm(e); + for (let n = 0; n < e.rows.length; n++) { + let i = e.rows[n], o = { ...r }; + for (let s = 0; s < i.length; s++) o[e.columns[s]] = pt(e.types[s], i[s]); + t.push(o); + } + return t; } - return adapter; - }, - adapters: knownAdapters -}; - -// node_modules/axios/lib/core/dispatchRequest.js -function throwIfCancellationRequested(config3) { - if (config3.cancelToken) { - config3.cancelToken.throwIfRequested(); - } - if (config3.signal && config3.signal.aborted) { - throw new CanceledError_default(null, config3); - } -} -function dispatchRequest(config3) { - throwIfCancellationRequested(config3); - config3.headers = AxiosHeaders_default.from(config3.headers); - config3.data = transformData.call( - config3, - config3.transformRequest - ); - if (["post", "put", "patch"].indexOf(config3.method) !== -1) { - config3.headers.setContentType("application/x-www-form-urlencoded", false); - } - const adapter = adapters_default.getAdapter(config3.adapter || defaults_default.adapter); - return adapter(config3).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config3); - response.data = transformData.call( - config3, - config3.transformResponse, - response - ); - response.headers = AxiosHeaders_default.from(response.headers); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config3); - if (reason && reason.response) { - reason.response.data = transformData.call( - config3, - config3.transformResponse, - reason.response - ); - reason.response.headers = AxiosHeaders_default.from(reason.response.headers); + function xm(e) { + let t = {}; + for (let r = 0; r < e.columns.length; r++) t[e.columns[r]] = null; + return t; + } + var Pm = L("prisma:client:request_handler"); + var $n = class { + constructor(t, r) { + this.logEmitter = r, this.client = t, this.dataloader = new Mn({ batchLoader: Ma(async ({ requests: n, customDataProxyFetch: i }) => { + let { transaction: o, otelParentCtx: s } = n[0], a = n.map((p) => p.protocolQuery), l = this.client._tracingHelper.getTraceParent(s), u = n.some((p) => go(p.protocolQuery.action)); + return (await this.client._engine.requestBatch(a, { traceparent: l, transaction: vm(o), containsWrite: u, customDataProxyFetch: i })).map((p, d) => { + if (p instanceof Error) return p; + try { + return this.mapQueryEngineResult(n[d], p); + } catch (f) { + return f; + } + }); + }), singleLoader: async (n) => { + let i = n.transaction?.kind === "itx" ? Ll(n.transaction) : void 0, o = await this.client._engine.request(n.protocolQuery, { traceparent: this.client._tracingHelper.getTraceParent(), interactiveTransaction: i, isWrite: go(n.protocolQuery.action), customDataProxyFetch: n.customDataProxyFetch }); + return this.mapQueryEngineResult(n, o); + }, batchBy: (n) => n.transaction?.id ? `transaction-${n.transaction.id}` : Dl(n.protocolQuery), batchOrder(n, i) { + return n.transaction?.kind === "batch" && i.transaction?.kind === "batch" ? n.transaction.index - i.transaction.index : 0; + } }); + } + async request(t) { + try { + return await this.dataloader.request(t); + } catch (r) { + let { clientMethod: n, callsite: i, transaction: o, args: s, modelName: a } = t; + this.handleAndLogRequestError({ error: r, clientMethod: n, callsite: i, transaction: o, args: s, modelName: a, globalOmit: t.globalOmit }); + } + } + mapQueryEngineResult({ dataPath: t, unpacker: r }, n) { + let i = n?.data, o = n?.elapsed, s = this.unpack(i, t, r); + return process.env.PRISMA_CLIENT_GET_TIME ? { data: s, elapsed: o } : s; + } + handleAndLogRequestError(t) { + try { + this.handleRequestError(t); + } catch (r) { + throw this.logEmitter && this.logEmitter.emit("error", { message: r.message, target: t.clientMethod, timestamp: /* @__PURE__ */ new Date() }), r; + } + } + handleRequestError({ error: t, clientMethod: r, callsite: n, transaction: i, args: o, modelName: s, globalOmit: a }) { + if (Pm(t), Tm(t, i) || t instanceof Le) throw t; + if (t instanceof V && Rm(t)) { + let u = Nl(t.meta); + wn({ args: o, errors: [u], callsite: n, errorFormat: this.client._errorFormat, originalMethod: r, clientVersion: this.client._clientVersion, globalOmit: a }); + } + let l = t.message; + if (n && (l = Tt({ callsite: n, originalMethod: r, isPanic: t.isPanic, showColors: this.client._errorFormat === "pretty", message: l })), l = this.sanitizeMessage(l), t.code) { + let u = s ? { modelName: s, ...t.meta } : t.meta; + throw new V(l, { code: t.code, clientVersion: this.client._clientVersion, meta: u, batchRequestIdx: t.batchRequestIdx }); + } else { + if (t.isPanic) throw new le(l, this.client._clientVersion); + if (t instanceof B) throw new B(l, { clientVersion: this.client._clientVersion, batchRequestIdx: t.batchRequestIdx }); + if (t instanceof R) throw new R(l, this.client._clientVersion); + if (t instanceof le) throw new le(l, this.client._clientVersion); + } + throw t.clientVersion = this.client._clientVersion, t; + } + sanitizeMessage(t) { + return this.client._errorFormat && this.client._errorFormat !== "pretty" ? (0, Fl.default)(t) : t; + } + unpack(t, r, n) { + if (!t || (t.data && (t = t.data), !t)) return t; + let i = Object.keys(t)[0], o = Object.values(t)[0], s = r.filter((u) => u !== "select" && u !== "include"), a = Gi(o, s), l = i === "queryRaw" ? _l(a) : wt(a); + return n ? n(l) : l; + } + get [Symbol.toStringTag]() { + return "RequestHandler"; + } + }; + function vm(e) { + if (e) { + if (e.kind === "batch") return { kind: "batch", options: { isolationLevel: e.isolationLevel } }; + if (e.kind === "itx") return { kind: "itx", options: Ll(e) }; + Fe(e, "Unknown transaction kind"); } } - return Promise.reject(reason); - }); -} - -// node_modules/axios/lib/helpers/validator.js -var validators = {}; -["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => { - validators[type] = function validator(thing) { - return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type; - }; -}); -var deprecatedWarnings = {}; -validators.transitional = function transitional(validator, version4, message) { - function formatMessage(opt, desc) { - return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); - } - return (value, opt, opts) => { - if (validator === false) { - throw new AxiosError_default( - formatMessage(opt, " has been removed" + (version4 ? " in " + version4 : "")), - AxiosError_default.ERR_DEPRECATED - ); + function Ll(e) { + return { id: e.id, payload: e.payload }; } - if (version4 && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - console.warn( - formatMessage( - opt, - " has been deprecated since v" + version4 + " and will be removed in the near future" - ) - ); + function Tm(e, t) { + return Nn(e) && t?.kind === "batch" && e.batchRequestIdx !== t.index; } - return validator ? validator(value, opt, opts) : true; - }; -}; -validators.spelling = function spelling(correctSpelling) { - return (value, opt) => { - console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); - return true; - }; -}; -function assertOptions(options, schema, allowUnknown) { - if (typeof options !== "object") { - throw new AxiosError_default("options must be an object", AxiosError_default.ERR_BAD_OPTION_VALUE); - } - const keys = Object.keys(options); - let i = keys.length; - while (i-- > 0) { - const opt = keys[i]; - const validator = schema[opt]; - if (validator) { - const value = options[opt]; - const result = value === void 0 || validator(value, opt, options); - if (result !== true) { - throw new AxiosError_default("option " + opt + " must be " + result, AxiosError_default.ERR_BAD_OPTION_VALUE); - } - continue; + function Rm(e) { + return e.code === "P2009" || e.code === "P2012"; } - if (allowUnknown !== true) { - throw new AxiosError_default("Unknown option " + opt, AxiosError_default.ERR_BAD_OPTION); + function Nl(e) { + if (e.kind === "Union") return { kind: "Union", errors: e.errors.map(Nl) }; + if (Array.isArray(e.selectionPath)) { + let [, ...t] = e.selectionPath; + return { ...e, selectionPath: t }; + } + return e; } - } -} -var validator_default = { - assertOptions, - validators -}; - -// node_modules/axios/lib/core/Axios.js -var validators2 = validator_default.validators; -var Axios = class { - constructor(instanceConfig) { - this.defaults = instanceConfig || {}; - this.interceptors = { - request: new InterceptorManager_default(), - response: new InterceptorManager_default() + var Ml = "5.22.0"; + var $l = Ml; + var Ul = k(Ai()); + var F = class extends Error { + constructor(t) { + super(t + ` +Read more at https://pris.ly/d/client-constructor`), this.name = "PrismaClientConstructorValidationError"; + } + get [Symbol.toStringTag]() { + return "PrismaClientConstructorValidationError"; + } }; - } - /** - * Dispatch a request - * - * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) - * @param {?Object} config - * - * @returns {Promise} The Promise to be fulfilled - */ - async request(configOrUrl, config3) { - try { - return await this._request(configOrUrl, config3); - } catch (err) { - if (err instanceof Error) { - let dummy = {}; - Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error(); - const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; - try { - if (!err.stack) { - err.stack = stack; - } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { - err.stack += "\n" + stack; + w(F, "PrismaClientConstructorValidationError"); + var ql = ["datasources", "datasourceUrl", "errorFormat", "adapter", "log", "transactionOptions", "omit", "__internal"]; + var jl = ["pretty", "colorless", "minimal"]; + var Vl = ["info", "query", "warn", "error"]; + var Sm = { datasources: (e, { datasourceNames: t }) => { + if (e) { + if (typeof e != "object" || Array.isArray(e)) throw new F(`Invalid value ${JSON.stringify(e)} for "datasources" provided to PrismaClient constructor`); + for (let [r, n] of Object.entries(e)) { + if (!t.includes(r)) { + let i = Vt(r, t) || ` Available datasources: ${t.join(", ")}`; + throw new F(`Unknown datasource ${r} provided to PrismaClient constructor.${i}`); + } + if (typeof n != "object" || Array.isArray(n)) throw new F(`Invalid value ${JSON.stringify(e)} for datasource "${r}" provided to PrismaClient constructor. +It should have this form: { url: "CONNECTION_STRING" }`); + if (n && typeof n == "object") for (let [i, o] of Object.entries(n)) { + if (i !== "url") throw new F(`Invalid value ${JSON.stringify(e)} for datasource "${r}" provided to PrismaClient constructor. +It should have this form: { url: "CONNECTION_STRING" }`); + if (typeof o != "string") throw new F(`Invalid value ${JSON.stringify(o)} for datasource "${r}" provided to PrismaClient constructor. +It should have this form: { url: "CONNECTION_STRING" }`); } - } catch (e) { } } - throw err; - } - } - _request(configOrUrl, config3) { - if (typeof configOrUrl === "string") { - config3 = config3 || {}; - config3.url = configOrUrl; - } else { - config3 = configOrUrl || {}; - } - config3 = mergeConfig(this.defaults, config3); - const { transitional: transitional2, paramsSerializer, headers } = config3; - if (transitional2 !== void 0) { - validator_default.assertOptions(transitional2, { - silentJSONParsing: validators2.transitional(validators2.boolean), - forcedJSONParsing: validators2.transitional(validators2.boolean), - clarifyTimeoutError: validators2.transitional(validators2.boolean) - }, false); - } - if (paramsSerializer != null) { - if (utils_default.isFunction(paramsSerializer)) { - config3.paramsSerializer = { - serialize: paramsSerializer - }; - } else { - validator_default.assertOptions(paramsSerializer, { - encode: validators2.function, - serialize: validators2.function - }, true); + }, adapter: (e, t) => { + if (e === null) return; + if (e === void 0) throw new F('"adapter" property must not be undefined, use null to conditionally disable driver adapters.'); + if (!Fn(t).includes("driverAdapters")) throw new F('"adapter" property can only be provided to PrismaClient constructor when "driverAdapters" preview feature is enabled.'); + if (Yt() === "binary") throw new F('Cannot use a driver adapter with the "binary" Query Engine. Please use the "library" Query Engine.'); + }, datasourceUrl: (e) => { + if (typeof e < "u" && typeof e != "string") throw new F(`Invalid value ${JSON.stringify(e)} for "datasourceUrl" provided to PrismaClient constructor. +Expected string or undefined.`); + }, errorFormat: (e) => { + if (e) { + if (typeof e != "string") throw new F(`Invalid value ${JSON.stringify(e)} for "errorFormat" provided to PrismaClient constructor.`); + if (!jl.includes(e)) { + let t = Vt(e, jl); + throw new F(`Invalid errorFormat ${e} provided to PrismaClient constructor.${t}`); + } } - } - if (config3.allowAbsoluteUrls !== void 0) { - } else if (this.defaults.allowAbsoluteUrls !== void 0) { - config3.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; - } else { - config3.allowAbsoluteUrls = true; - } - validator_default.assertOptions(config3, { - baseUrl: validators2.spelling("baseURL"), - withXsrfToken: validators2.spelling("withXSRFToken") - }, true); - config3.method = (config3.method || this.defaults.method || "get").toLowerCase(); - let contextHeaders = headers && utils_default.merge( - headers.common, - headers[config3.method] - ); - headers && utils_default.forEach( - ["delete", "get", "head", "post", "put", "patch", "common"], - (method) => { - delete headers[method]; + }, log: (e) => { + if (!e) return; + if (!Array.isArray(e)) throw new F(`Invalid value ${JSON.stringify(e)} for "log" provided to PrismaClient constructor.`); + function t(r) { + if (typeof r == "string" && !Vl.includes(r)) { + let n = Vt(r, Vl); + throw new F(`Invalid log level "${r}" provided to PrismaClient constructor.${n}`); + } } - ); - config3.headers = AxiosHeaders_default.concat(contextHeaders, headers); - const requestInterceptorChain = []; - let synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config3) === false) { - return; + for (let r of e) { + t(r); + let n = { level: t, emit: (i) => { + let o = ["stdout", "event"]; + if (!o.includes(i)) { + let s = Vt(i, o); + throw new F(`Invalid value ${JSON.stringify(i)} for "emit" in logLevel provided to PrismaClient constructor.${s}`); + } + } }; + if (r && typeof r == "object") for (let [i, o] of Object.entries(r)) if (n[i]) n[i](o); + else throw new F(`Invalid property ${i} for "log" provided to PrismaClient constructor`); } - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - const responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - let promise; - let i = 0; - let len; - if (!synchronousRequestInterceptors) { - const chain = [dispatchRequest.bind(this), void 0]; - chain.unshift.apply(chain, requestInterceptorChain); - chain.push.apply(chain, responseInterceptorChain); - len = chain.length; - promise = Promise.resolve(config3); - while (i < len) { - promise = promise.then(chain[i++], chain[i++]); + }, transactionOptions: (e) => { + if (!e) return; + let t = e.maxWait; + if (t != null && t <= 0) throw new F(`Invalid value ${t} for maxWait in "transactionOptions" provided to PrismaClient constructor. maxWait needs to be greater than 0`); + let r = e.timeout; + if (r != null && r <= 0) throw new F(`Invalid value ${r} for timeout in "transactionOptions" provided to PrismaClient constructor. timeout needs to be greater than 0`); + }, omit: (e, t) => { + if (typeof e != "object") throw new F('"omit" option is expected to be an object.'); + if (e === null) throw new F('"omit" option can not be `null`'); + let r = []; + for (let [n, i] of Object.entries(e)) { + let o = Im(n, t.runtimeDataModel); + if (!o) { + r.push({ kind: "UnknownModel", modelKey: n }); + continue; + } + for (let [s, a] of Object.entries(i)) { + let l = o.fields.find((u) => u.name === s); + if (!l) { + r.push({ kind: "UnknownField", modelKey: n, fieldName: s }); + continue; + } + if (l.relationName) { + r.push({ kind: "RelationInOmit", modelKey: n, fieldName: s }); + continue; + } + typeof a != "boolean" && r.push({ kind: "InvalidFieldValue", modelKey: n, fieldName: s }); + } } - return promise; - } - len = requestInterceptorChain.length; - let newConfig = config3; - i = 0; - while (i < len) { - const onFulfilled = requestInterceptorChain[i++]; - const onRejected = requestInterceptorChain[i++]; - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected.call(this, error); - break; + if (r.length > 0) throw new F(Om(e, r)); + }, __internal: (e) => { + if (!e) return; + let t = ["debug", "engine", "configOverride"]; + if (typeof e != "object") throw new F(`Invalid value ${JSON.stringify(e)} for "__internal" to PrismaClient constructor`); + for (let [r] of Object.entries(e)) if (!t.includes(r)) { + let n = Vt(r, t); + throw new F(`Invalid property ${JSON.stringify(r)} for "__internal" provided to PrismaClient constructor.${n}`); + } + } }; + function Gl(e, t) { + for (let [r, n] of Object.entries(e)) { + if (!ql.includes(r)) { + let i = Vt(r, ql); + throw new F(`Unknown property ${r} provided to PrismaClient constructor.${i}`); + } + Sm[r](n, t); } + if (e.datasourceUrl && e.datasources) throw new F('Can not use "datasourceUrl" and "datasources" options at the same time. Pick one of them'); } - try { - promise = dispatchRequest.call(this, newConfig); - } catch (error) { - return Promise.reject(error); + function Vt(e, t) { + if (t.length === 0 || typeof e != "string") return ""; + let r = Am(e, t); + return r ? ` Did you mean "${r}"?` : ""; } - i = 0; - len = responseInterceptorChain.length; - while (i < len) { - promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + function Am(e, t) { + if (t.length === 0) return null; + let r = t.map((i) => ({ value: i, distance: (0, Ul.default)(e, i) })); + r.sort((i, o) => i.distance < o.distance ? -1 : 1); + let n = r[0]; + return n.distance < 3 ? n.value : null; } - return promise; - } - getUri(config3) { - config3 = mergeConfig(this.defaults, config3); - const fullPath = buildFullPath(config3.baseURL, config3.url, config3.allowAbsoluteUrls); - return buildURL(fullPath, config3.params, config3.paramsSerializer); - } -}; -utils_default.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) { - Axios.prototype[method] = function(url2, config3) { - return this.request(mergeConfig(config3 || {}, { - method, - url: url2, - data: (config3 || {}).data - })); - }; -}); -utils_default.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { - function generateHTTPMethod(isForm) { - return function httpMethod(url2, data, config3) { - return this.request(mergeConfig(config3 || {}, { - method, - headers: isForm ? { - "Content-Type": "multipart/form-data" - } : {}, - url: url2, - data - })); - }; - } - Axios.prototype[method] = generateHTTPMethod(); - Axios.prototype[method + "Form"] = generateHTTPMethod(true); -}); -var Axios_default = Axios; - -// node_modules/axios/lib/cancel/CancelToken.js -var CancelToken = class _CancelToken { - constructor(executor) { - if (typeof executor !== "function") { - throw new TypeError("executor must be a function."); + function Im(e, t) { + return Bl(t.models, e) ?? Bl(t.types, e); } - let resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - const token = this; - this.promise.then((cancel) => { - if (!token._listeners) return; - let i = token._listeners.length; - while (i-- > 0) { - token._listeners[i](cancel); + function Bl(e, t) { + let r = Object.keys(e).find((n) => xt(n) === t); + if (r) return e[r]; + } + function Om(e, t) { + let r = Ot(e); + for (let o of t) switch (o.kind) { + case "UnknownModel": + r.arguments.getField(o.modelKey)?.markAsError(), r.addErrorMessage(() => `Unknown model name: ${o.modelKey}.`); + break; + case "UnknownField": + r.arguments.getDeepField([o.modelKey, o.fieldName])?.markAsError(), r.addErrorMessage(() => `Model "${o.modelKey}" does not have a field named "${o.fieldName}".`); + break; + case "RelationInOmit": + r.arguments.getDeepField([o.modelKey, o.fieldName])?.markAsError(), r.addErrorMessage(() => 'Relations are already excluded by default and can not be specified in "omit".'); + break; + case "InvalidFieldValue": + r.arguments.getDeepFieldValue([o.modelKey, o.fieldName])?.markAsError(), r.addErrorMessage(() => "Omit field option value must be a boolean."); + break; } - token._listeners = null; - }); - this.promise.then = (onfulfilled) => { - let _resolve; - const promise = new Promise((resolve) => { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - return promise; - }; - executor(function cancel(message, config3, request) { - if (token.reason) { - return; + let { message: n, args: i } = En(r, "colorless"); + return `Error validating "omit" option: + +${i} + +${n}`; + } + function Ql(e) { + return e.length === 0 ? Promise.resolve([]) : new Promise((t, r) => { + let n = new Array(e.length), i = null, o = false, s = 0, a = () => { + o || (s++, s === e.length && (o = true, i ? r(i) : t(n))); + }, l = (u) => { + o || (o = true, r(u)); + }; + for (let u = 0; u < e.length; u++) e[u].then((c) => { + n[u] = c, a(); + }, (c) => { + if (!Nn(c)) { + l(c); + return; + } + c.batchRequestIdx === u ? l(c) : (i || (i = c), a()); + }); + }); + } + var tt = L("prisma:client"); + typeof globalThis == "object" && (globalThis.NODE_CLIENT = true); + var km = { requestArgsToMiddlewareArgs: (e) => e, middlewareArgsToRequestArgs: (e) => e }; + var Dm = Symbol.for("prisma.client.transaction.id"); + var _m = { id: 0, nextId() { + return ++this.id; + } }; + function Yl(e) { + class t { + constructor(n) { + this._originalClient = this; + this._middlewares = new Ln(); + this._createPrismaPromise = po(); + this.$extends = Ia; + e = n?.__internal?.configOverride?.(e) ?? e, Ba(e), n && Gl(n, e); + let i = new Kl.EventEmitter().on("error", () => { + }); + this._extensions = kt.empty(), this._previewFeatures = Fn(e), this._clientVersion = e.clientVersion ?? $l, this._activeProvider = e.activeProvider, this._globalOmit = n?.omit, this._tracingHelper = Il(this._previewFeatures); + let o = { rootEnvPath: e.relativeEnvPaths.rootEnvPath && Fr.default.resolve(e.dirname, e.relativeEnvPaths.rootEnvPath), schemaEnvPath: e.relativeEnvPaths.schemaEnvPath && Fr.default.resolve(e.dirname, e.relativeEnvPaths.schemaEnvPath) }, s; + if (n?.adapter) { + s = qi(n.adapter); + let l = e.activeProvider === "postgresql" ? "postgres" : e.activeProvider; + if (s.provider !== l) throw new R(`The Driver Adapter \`${s.adapterName}\`, based on \`${s.provider}\`, is not compatible with the provider \`${l}\` specified in the Prisma schema.`, this._clientVersion); + if (n.datasources || n.datasourceUrl !== void 0) throw new R("Custom datasource configuration is not compatible with Prisma Driver Adapters. Please define the database connection string directly in the Driver Adapter configuration.", this._clientVersion); + } + let a = !s && zt(o, { conflictCheck: "none" }) || e.injectableEdgeEnv?.(); + try { + let l = n ?? {}, u = l.__internal ?? {}, c = u.debug === true; + c && L.enable("prisma:client"); + let p = Fr.default.resolve(e.dirname, e.relativePath); + zl.default.existsSync(p) || (p = e.dirname), tt("dirname", e.dirname), tt("relativePath", e.relativePath), tt("cwd", p); + let d = u.engine || {}; + if (l.errorFormat ? this._errorFormat = l.errorFormat : process.env.NODE_ENV === "production" ? this._errorFormat = "minimal" : process.env.NO_COLOR ? this._errorFormat = "colorless" : this._errorFormat = "colorless", this._runtimeDataModel = e.runtimeDataModel, this._engineConfig = { cwd: p, dirname: e.dirname, enableDebugLogs: c, allowTriggerPanic: d.allowTriggerPanic, datamodelPath: Fr.default.join(e.dirname, e.filename ?? "schema.prisma"), prismaPath: d.binaryPath ?? void 0, engineEndpoint: d.endpoint, generator: e.generator, showColors: this._errorFormat === "pretty", logLevel: l.log && kl(l.log), logQueries: l.log && !!(typeof l.log == "string" ? l.log === "query" : l.log.find((f) => typeof f == "string" ? f === "query" : f.level === "query")), env: a?.parsed ?? {}, flags: [], engineWasm: e.engineWasm, clientVersion: e.clientVersion, engineVersion: e.engineVersion, previewFeatures: this._previewFeatures, activeProvider: e.activeProvider, inlineSchema: e.inlineSchema, overrideDatasources: Ua(l, e.datasourceNames), inlineDatasources: e.inlineDatasources, inlineSchemaHash: e.inlineSchemaHash, tracingHelper: this._tracingHelper, transactionOptions: { maxWait: l.transactionOptions?.maxWait ?? 2e3, timeout: l.transactionOptions?.timeout ?? 5e3, isolationLevel: l.transactionOptions?.isolationLevel }, logEmitter: i, isBundled: e.isBundled, adapter: s }, this._accelerateEngineConfig = { ...this._engineConfig, accelerateUtils: { resolveDatasourceUrl: Nt, getBatchRequestPayload: Ft, prismaGraphQLToJSError: st, PrismaClientUnknownRequestError: B, PrismaClientInitializationError: R, PrismaClientKnownRequestError: V, debug: L("prisma:client:accelerateEngine"), engineVersion: Wl.version, clientVersion: e.clientVersion } }, tt("clientVersion", e.clientVersion), this._engine = hl(e, this._engineConfig), this._requestHandler = new $n(this, i), l.log) for (let f of l.log) { + let g = typeof f == "string" ? f : f.emit === "stdout" ? f.level : null; + g && this.$on(g, (h) => { + er.log(`${er.tags[g] ?? ""}`, h.message || h.query); + }); + } + this._metrics = new Dt(this._engine); + } catch (l) { + throw l.clientVersion = this._clientVersion, l; + } + return this._appliedParent = yr(this); + } + get [Symbol.toStringTag]() { + return "PrismaClient"; + } + $use(n) { + this._middlewares.use(n); + } + $on(n, i) { + n === "beforeExit" ? this._engine.onBeforeExit(i) : n && this._engineConfig.logEmitter.on(n, i); + } + $connect() { + try { + return this._engine.start(); + } catch (n) { + throw n.clientVersion = this._clientVersion, n; + } + } + async $disconnect() { + try { + await this._engine.stop(); + } catch (n) { + throw n.clientVersion = this._clientVersion, n; + } finally { + Ao(); + } + } + $executeRawInternal(n, i, o, s) { + let a = this._activeProvider; + return this._request({ action: "executeRaw", args: o, transaction: n, clientMethod: i, argsMapper: co({ clientMethod: i, activeProvider: a }), callsite: Ze(this._errorFormat), dataPath: [], middlewareArgsMapper: s }); + } + $executeRaw(n, ...i) { + return this._createPrismaPromise((o) => { + if (n.raw !== void 0 || n.sql !== void 0) { + let [s, a] = Jl(n, i); + return uo(this._activeProvider, s.text, s.values, Array.isArray(n) ? "prisma.$executeRaw``" : "prisma.$executeRaw(sql``)"), this.$executeRawInternal(o, "$executeRaw", s, a); + } + throw new J("`$executeRaw` is a tag function, please use it like the following:\n```\nconst result = await prisma.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};`\n```\n\nOr read our docs at https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#executeraw\n", { clientVersion: this._clientVersion }); + }); + } + $executeRawUnsafe(n, ...i) { + return this._createPrismaPromise((o) => (uo(this._activeProvider, n, i, "prisma.$executeRawUnsafe(, [...values])"), this.$executeRawInternal(o, "$executeRawUnsafe", [n, ...i]))); + } + $runCommandRaw(n) { + if (e.activeProvider !== "mongodb") throw new J(`The ${e.activeProvider} provider does not support $runCommandRaw. Use the mongodb provider.`, { clientVersion: this._clientVersion }); + return this._createPrismaPromise((i) => this._request({ args: n, clientMethod: "$runCommandRaw", dataPath: [], action: "runCommandRaw", argsMapper: yl, callsite: Ze(this._errorFormat), transaction: i })); + } + async $queryRawInternal(n, i, o, s) { + let a = this._activeProvider; + return this._request({ action: "queryRaw", args: o, transaction: n, clientMethod: i, argsMapper: co({ clientMethod: i, activeProvider: a }), callsite: Ze(this._errorFormat), dataPath: [], middlewareArgsMapper: s }); + } + $queryRaw(n, ...i) { + return this._createPrismaPromise((o) => { + if (n.raw !== void 0 || n.sql !== void 0) return this.$queryRawInternal(o, "$queryRaw", ...Jl(n, i)); + throw new J("`$queryRaw` is a tag function, please use it like the following:\n```\nconst result = await prisma.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};`\n```\n\nOr read our docs at https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#queryraw\n", { clientVersion: this._clientVersion }); + }); + } + $queryRawTyped(n) { + return this._createPrismaPromise((i) => { + if (!this._hasPreviewFlag("typedSql")) throw new J("`typedSql` preview feature must be enabled in order to access $queryRawTyped API", { clientVersion: this._clientVersion }); + return this.$queryRawInternal(i, "$queryRawTyped", n); + }); + } + $queryRawUnsafe(n, ...i) { + return this._createPrismaPromise((o) => this.$queryRawInternal(o, "$queryRawUnsafe", [n, ...i])); + } + _transactionWithArray({ promises: n, options: i }) { + let o = _m.nextId(), s = Ol(n.length), a = n.map((l, u) => { + if (l?.[Symbol.toStringTag] !== "PrismaPromise") throw new Error("All elements of the array need to be Prisma Client promises. Hint: Please make sure you are not awaiting the Prisma client calls you intended to pass in the $transaction function."); + let c = i?.isolationLevel ?? this._engineConfig.transactionOptions.isolationLevel, p = { kind: "batch", id: o, index: u, isolationLevel: c, lock: s }; + return l.requestTransaction?.(p) ?? l; + }); + return Ql(a); + } + async _transactionWithCallback({ callback: n, options: i }) { + let o = { traceparent: this._tracingHelper.getTraceParent() }, s = { maxWait: i?.maxWait ?? this._engineConfig.transactionOptions.maxWait, timeout: i?.timeout ?? this._engineConfig.transactionOptions.timeout, isolationLevel: i?.isolationLevel ?? this._engineConfig.transactionOptions.isolationLevel }, a = await this._engine.transaction("start", o, s), l; + try { + let u = { kind: "itx", ...a }; + l = await n(this._createItxClient(u)), await this._engine.transaction("commit", o, a); + } catch (u) { + throw await this._engine.transaction("rollback", o, a).catch(() => { + }), u; + } + return l; + } + _createItxClient(n) { + return yr(Se(Aa(this), [re("_appliedParent", () => this._appliedParent._createItxClient(n)), re("_createPrismaPromise", () => po(n)), re(Dm, () => n.id), _t(vl)])); + } + $transaction(n, i) { + let o; + typeof n == "function" ? this._engineConfig.adapter?.adapterName === "@prisma/adapter-d1" ? o = () => { + throw new Error("Cloudflare D1 does not support interactive transactions. We recommend you to refactor your queries with that limitation in mind, and use batch transactions with `prisma.$transactions([])` where applicable."); + } : o = () => this._transactionWithCallback({ callback: n, options: i }) : o = () => this._transactionWithArray({ promises: n, options: i }); + let s = { name: "transaction", attributes: { method: "$transaction" } }; + return this._tracingHelper.runInChildSpan(s, o); + } + _request(n) { + n.otelParentCtx = this._tracingHelper.getActiveContext(); + let i = n.middlewareArgsMapper ?? km, o = { args: i.requestArgsToMiddlewareArgs(n.args), dataPath: n.dataPath, runInTransaction: !!n.transaction, action: n.action, model: n.model }, s = { middleware: { name: "middleware", middleware: true, attributes: { method: "$use" }, active: false }, operation: { name: "operation", attributes: { method: o.action, model: o.model, name: o.model ? `${o.model}.${o.action}` : o.action } } }, a = -1, l = async (u) => { + let c = this._middlewares.get(++a); + if (c) return this._tracingHelper.runInChildSpan(s.middleware, (O) => c(u, (T) => (O?.end(), l(T)))); + let { runInTransaction: p, args: d, ...f } = u, g = { ...n, ...f }; + d && (g.args = i.middlewareArgsToRequestArgs(d)), n.transaction !== void 0 && p === false && delete g.transaction; + let h = await Na(this, g); + return g.model ? Da({ result: h, modelName: g.model, args: g.args, extensions: this._extensions, runtimeDataModel: this._runtimeDataModel, globalOmit: this._globalOmit }) : h; + }; + return this._tracingHelper.runInChildSpan(s.operation, () => new Hl.AsyncResource("prisma-client-request").runInAsyncScope(() => l(o))); + } + async _executeRequest({ args: n, clientMethod: i, dataPath: o, callsite: s, action: a, model: l, argsMapper: u, transaction: c, unpacker: p, otelParentCtx: d, customDataProxyFetch: f }) { + try { + n = u ? u(n) : n; + let g = { name: "serialize" }, h = this._tracingHelper.runInChildSpan(g, () => vn({ modelName: l, runtimeDataModel: this._runtimeDataModel, action: a, args: n, clientMethod: i, callsite: s, extensions: this._extensions, errorFormat: this._errorFormat, clientVersion: this._clientVersion, previewFeatures: this._previewFeatures, globalOmit: this._globalOmit })); + return L.enabled("prisma:client") && (tt("Prisma Client call:"), tt(`prisma.${i}(${ha(n)})`), tt("Generated request:"), tt(JSON.stringify(h, null, 2) + ` +`)), c?.kind === "batch" && await c.lock, this._requestHandler.request({ protocolQuery: h, modelName: l, action: a, clientMethod: i, dataPath: o, callsite: s, args: n, extensions: this._extensions, transaction: c, unpacker: p, otelParentCtx: d, otelChildCtx: this._tracingHelper.getActiveContext(), globalOmit: this._globalOmit, customDataProxyFetch: f }); + } catch (g) { + throw g.clientVersion = this._clientVersion, g; + } + } + get $metrics() { + if (!this._hasPreviewFlag("metrics")) throw new J("`metrics` preview feature must be enabled in order to access metrics API", { clientVersion: this._clientVersion }); + return this._metrics; + } + _hasPreviewFlag(n) { + return !!this._engineConfig.previewFeatures?.includes(n); + } + $applyPendingMigrations() { + return this._engine.applyPendingMigrations(); + } } - token.reason = new CanceledError_default(message, config3, request); - resolvePromise(token.reason); - }); - } - /** - * Throws a `CanceledError` if cancellation has been requested. - */ - throwIfRequested() { - if (this.reason) { - throw this.reason; + return t; } - } - /** - * Subscribe to the cancel signal - */ - subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; + function Jl(e, t) { + return Fm(e) ? [new oe(e, t), Rl] : [e, Cl]; } - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; + function Fm(e) { + return Array.isArray(e) && Array.isArray(e.raw); } - } - /** - * Unsubscribe from the cancel signal - */ - unsubscribe(listener) { - if (!this._listeners) { - return; + var Lm = /* @__PURE__ */ new Set(["toJSON", "$$typeof", "asymmetricMatch", Symbol.iterator, Symbol.toStringTag, Symbol.isConcatSpreadable, Symbol.toPrimitive]); + function Zl(e) { + return new Proxy(e, { get(t, r) { + if (r in t) return t[r]; + if (!Lm.has(r)) throw new TypeError(`Invalid enum value: ${String(r)}`); + } }); } - const index2 = this._listeners.indexOf(listener); - if (index2 !== -1) { - this._listeners.splice(index2, 1); + function Xl(e) { + zt(e, { conflictCheck: "warn" }); } } - toAbortSignal() { - const controller = new AbortController(); - const abort = (err) => { - controller.abort(err); +}); + +// node_modules/.prisma/client/index.js +var require_client = __commonJS({ + "node_modules/.prisma/client/index.js"(exports2) { + Object.defineProperty(exports2, "__esModule", { value: true }); + var { + PrismaClientKnownRequestError: PrismaClientKnownRequestError2, + PrismaClientUnknownRequestError: PrismaClientUnknownRequestError2, + PrismaClientRustPanicError: PrismaClientRustPanicError2, + PrismaClientInitializationError: PrismaClientInitializationError2, + PrismaClientValidationError: PrismaClientValidationError2, + NotFoundError: NotFoundError3, + getPrismaClient: getPrismaClient2, + sqltag: sqltag2, + empty: empty2, + join: join2, + raw: raw2, + skip: skip2, + Decimal: Decimal2, + Debug: Debug2, + objectEnumValues: objectEnumValues2, + makeStrictEnum: makeStrictEnum2, + Extensions: Extensions2, + warnOnce: warnOnce2, + defineDmmfProperty: defineDmmfProperty2, + Public: Public2, + getRuntime: getRuntime2 + } = require_library(); + var Prisma = {}; + exports2.Prisma = Prisma; + exports2.$Enums = {}; + Prisma.prismaVersion = { + client: "5.22.0", + engine: "605197351a3c8bdd595af2d2a9bc3025bca48ea2" }; - this.subscribe(abort); - controller.signal.unsubscribe = () => this.unsubscribe(abort); - return controller.signal; - } - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - static source() { - let cancel; - const token = new _CancelToken(function executor(c) { - cancel = c; + Prisma.PrismaClientKnownRequestError = PrismaClientKnownRequestError2; + Prisma.PrismaClientUnknownRequestError = PrismaClientUnknownRequestError2; + Prisma.PrismaClientRustPanicError = PrismaClientRustPanicError2; + Prisma.PrismaClientInitializationError = PrismaClientInitializationError2; + Prisma.PrismaClientValidationError = PrismaClientValidationError2; + Prisma.NotFoundError = NotFoundError3; + Prisma.Decimal = Decimal2; + Prisma.sql = sqltag2; + Prisma.empty = empty2; + Prisma.join = join2; + Prisma.raw = raw2; + Prisma.validator = Public2.validator; + Prisma.getExtensionContext = Extensions2.getExtensionContext; + Prisma.defineExtension = Extensions2.defineExtension; + Prisma.DbNull = objectEnumValues2.instances.DbNull; + Prisma.JsonNull = objectEnumValues2.instances.JsonNull; + Prisma.AnyNull = objectEnumValues2.instances.AnyNull; + Prisma.NullTypes = { + DbNull: objectEnumValues2.classes.DbNull, + JsonNull: objectEnumValues2.classes.JsonNull, + AnyNull: objectEnumValues2.classes.AnyNull + }; + var path = __require("path"); + exports2.Prisma.TransactionIsolationLevel = makeStrictEnum2({ + Serializable: "Serializable" }); - return { - token, - cancel + exports2.Prisma.BlockCheckpointScalarFieldEnum = { + id: "id", + network: "network", + blockNumber: "blockNumber", + timestamp: "timestamp" + }; + exports2.Prisma.SortOrder = { + asc: "asc", + desc: "desc" + }; + exports2.Prisma.ModelName = { + BlockCheckpoint: "BlockCheckpoint" + }; + var config3 = { + "generator": { + "name": "client", + "provider": { + "fromEnvVar": null, + "value": "prisma-client-js" + }, + "output": { + "value": "/Users/oleg/Documents/Code/concero/v2-operators/node_modules/@prisma/client", + "fromEnvVar": null + }, + "config": { + "engineType": "library" + }, + "binaryTargets": [ + { + "fromEnvVar": null, + "value": "darwin-arm64", + "native": true + } + ], + "previewFeatures": [], + "sourceFilePath": "/Users/oleg/Documents/Code/concero/v2-operators/prisma/schema.prisma" + }, + "relativeEnvPaths": { + "rootEnvPath": null, + "schemaEnvPath": "../../../.env" + }, + "relativePath": "../../../prisma", + "clientVersion": "5.22.0", + "engineVersion": "605197351a3c8bdd595af2d2a9bc3025bca48ea2", + "datasourceNames": [ + "db" + ], + "activeProvider": "sqlite", + "postinstall": false, + "inlineDatasources": { + "db": { + "url": { + "fromEnvVar": null, + "value": "file:./block-checkpoints.db" + } + } + }, + "inlineSchema": 'generator client {\n provider = "prisma-client-js"\n}\n\ndatasource db {\n provider = "sqlite"\n url = "file:./block-checkpoints.db"\n}\n\nmodel BlockCheckpoint {\n id Int @id @default(autoincrement())\n network String @unique\n blockNumber BigInt\n timestamp DateTime @default(now())\n}\n', + "inlineSchemaHash": "bd1c73e8e712d1b9b3e8c8468e4ed2988c6ff6026cedd767f8cb6f8ca4afe408", + "copyEngine": true }; + var fs2 = __require("fs"); + config3.dirname = __dirname; + if (!fs2.existsSync(path.join(__dirname, "schema.prisma"))) { + const alternativePaths = [ + "node_modules/.prisma/client", + ".prisma/client" + ]; + const alternativePath = alternativePaths.find((altPath) => { + return fs2.existsSync(path.join(process.cwd(), altPath, "schema.prisma")); + }) ?? alternativePaths[0]; + config3.dirname = path.join(process.cwd(), alternativePath); + config3.isBundled = true; + } + config3.runtimeDataModel = JSON.parse('{"models":{"BlockCheckpoint":{"dbName":null,"fields":[{"name":"id","kind":"scalar","isList":false,"isRequired":true,"isUnique":false,"isId":true,"isReadOnly":false,"hasDefaultValue":true,"type":"Int","default":{"name":"autoincrement","args":[]},"isGenerated":false,"isUpdatedAt":false},{"name":"network","kind":"scalar","isList":false,"isRequired":true,"isUnique":true,"isId":false,"isReadOnly":false,"hasDefaultValue":false,"type":"String","isGenerated":false,"isUpdatedAt":false},{"name":"blockNumber","kind":"scalar","isList":false,"isRequired":true,"isUnique":false,"isId":false,"isReadOnly":false,"hasDefaultValue":false,"type":"BigInt","isGenerated":false,"isUpdatedAt":false},{"name":"timestamp","kind":"scalar","isList":false,"isRequired":true,"isUnique":false,"isId":false,"isReadOnly":false,"hasDefaultValue":true,"type":"DateTime","default":{"name":"now","args":[]},"isGenerated":false,"isUpdatedAt":false}],"primaryKey":null,"uniqueFields":[],"uniqueIndexes":[],"isGenerated":false}},"enums":{},"types":{}}'); + defineDmmfProperty2(exports2.Prisma, config3.runtimeDataModel); + config3.engineWasm = void 0; + var { warnEnvConflicts: warnEnvConflicts2 } = require_library(); + warnEnvConflicts2({ + rootEnvPath: config3.relativeEnvPaths.rootEnvPath && path.resolve(config3.dirname, config3.relativeEnvPaths.rootEnvPath), + schemaEnvPath: config3.relativeEnvPaths.schemaEnvPath && path.resolve(config3.dirname, config3.relativeEnvPaths.schemaEnvPath) + }); + var PrismaClient2 = getPrismaClient2(config3); + exports2.PrismaClient = PrismaClient2; + Object.assign(exports2, Prisma); + path.join(__dirname, "libquery_engine-darwin-arm64.dylib.node"); + path.join(process.cwd(), "node_modules/.prisma/client/libquery_engine-darwin-arm64.dylib.node"); + path.join(__dirname, "schema.prisma"); + path.join(process.cwd(), "node_modules/.prisma/client/schema.prisma"); } -}; -var CancelToken_default = CancelToken; - -// node_modules/axios/lib/helpers/spread.js -function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; -} +}); -// node_modules/axios/lib/helpers/isAxiosError.js -function isAxiosError(payload) { - return utils_default.isObject(payload) && payload.isAxiosError === true; -} +// node_modules/.prisma/client/default.js +var require_default = __commonJS({ + "node_modules/.prisma/client/default.js"(exports2, module2) { + module2.exports = { ...require_client() }; + } +}); -// node_modules/axios/lib/helpers/HttpStatusCode.js -var HttpStatusCode = { - Continue: 100, - SwitchingProtocols: 101, - Processing: 102, - EarlyHints: 103, - Ok: 200, - Created: 201, - Accepted: 202, - NonAuthoritativeInformation: 203, - NoContent: 204, - ResetContent: 205, - PartialContent: 206, - MultiStatus: 207, - AlreadyReported: 208, - ImUsed: 226, - MultipleChoices: 300, - MovedPermanently: 301, - Found: 302, - SeeOther: 303, - NotModified: 304, - UseProxy: 305, - Unused: 306, - TemporaryRedirect: 307, - PermanentRedirect: 308, - BadRequest: 400, - Unauthorized: 401, - PaymentRequired: 402, - Forbidden: 403, - NotFound: 404, - MethodNotAllowed: 405, - NotAcceptable: 406, - ProxyAuthenticationRequired: 407, - RequestTimeout: 408, - Conflict: 409, - Gone: 410, - LengthRequired: 411, - PreconditionFailed: 412, - PayloadTooLarge: 413, - UriTooLong: 414, - UnsupportedMediaType: 415, - RangeNotSatisfiable: 416, - ExpectationFailed: 417, - ImATeapot: 418, - MisdirectedRequest: 421, - UnprocessableEntity: 422, - Locked: 423, - FailedDependency: 424, - TooEarly: 425, - UpgradeRequired: 426, - PreconditionRequired: 428, - TooManyRequests: 429, - RequestHeaderFieldsTooLarge: 431, - UnavailableForLegalReasons: 451, - InternalServerError: 500, - NotImplemented: 501, - BadGateway: 502, - ServiceUnavailable: 503, - GatewayTimeout: 504, - HttpVersionNotSupported: 505, - VariantAlsoNegotiates: 506, - InsufficientStorage: 507, - LoopDetected: 508, - NotExtended: 510, - NetworkAuthenticationRequired: 511 -}; -Object.entries(HttpStatusCode).forEach(([key, value]) => { - HttpStatusCode[value] = key; +// node_modules/@prisma/client/default.js +var require_default2 = __commonJS({ + "node_modules/@prisma/client/default.js"(exports2, module2) { + module2.exports = { + ...require_default() + }; + } }); -var HttpStatusCode_default = HttpStatusCode; -// node_modules/axios/lib/axios.js -function createInstance(defaultConfig) { - const context = new Axios_default(defaultConfig); - const instance = bind(Axios_default.prototype.request, context); - utils_default.extend(instance, Axios_default.prototype, context, { allOwnKeys: true }); - utils_default.extend(instance, context, null, { allOwnKeys: true }); - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; - return instance; +// src/common/utils/configureDotEnv.ts +var dotenv = __toESM(require_main(), 1); +var ENV_FILES = [".env", ".env.wallets", ".env.deployments.testnet", ".env.deployments.mainnet"]; +function configureDotEnv(basePath = "./") { + const normalizedBasePath = basePath.endsWith("/") ? basePath : `${basePath}/`; + ENV_FILES.forEach((file) => { + dotenv.config({ path: `${normalizedBasePath}${file}` }); + }); } -var axios = createInstance(defaults_default); -axios.Axios = Axios_default; -axios.CanceledError = CanceledError_default; -axios.CancelToken = CancelToken_default; -axios.isCancel = isCancel; -axios.VERSION = VERSION; -axios.toFormData = toFormData_default; -axios.AxiosError = AxiosError_default; -axios.Cancel = axios.CanceledError; -axios.all = function all(promises) { - return Promise.all(promises); -}; -axios.spread = spread; -axios.isAxiosError = isAxiosError; -axios.mergeConfig = mergeConfig; -axios.AxiosHeaders = AxiosHeaders_default; -axios.formToJSON = (thing) => formDataToJSON_default(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing); -axios.getAdapter = adapters_default.getAdapter; -axios.HttpStatusCode = HttpStatusCode_default; -axios.default = axios; -var axios_default = axios; - -// node_modules/axios/index.js -var { - Axios: Axios2, - AxiosError: AxiosError2, - CanceledError: CanceledError2, - isCancel: isCancel2, - CancelToken: CancelToken2, - VERSION: VERSION2, - all: all2, - Cancel, - isAxiosError: isAxiosError2, - spread: spread2, - toFormData: toFormData2, - AxiosHeaders: AxiosHeaders2, - HttpStatusCode: HttpStatusCode2, - formToJSON, - getAdapter, - mergeConfig: mergeConfig2 -} = axios_default; +configureDotEnv(); // src/constants/appErrors.ts var appErrors = { @@ -52496,8 +49187,8 @@ var appErrors = { }; // src/constants/eventEmitter.ts -import { EventEmitter as EventEmitter2 } from "node:events"; -var eventEmitter = new EventEmitter2(); +import { EventEmitter } from "node:events"; +var eventEmitter = new EventEmitter(); // src/abi/ConceroRouter.json var abi = [ @@ -53855,1527 +50546,3743 @@ var abi2 = [ { inputs: [ { - internalType: "address", - name: "operator", - type: "address" + internalType: "address", + name: "operator", + type: "address" + } + ], + name: "operatorDeposit", + outputs: [], + stateMutability: "payable", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32", + name: "messageId", + type: "bytes32" + }, + { + internalType: "bytes32", + name: "messageHashSum", + type: "bytes32" + }, + { + internalType: "uint24", + name: "srcChainSelector", + type: "uint24" + }, + { + internalType: "bytes", + name: "srcChainData", + type: "bytes" + } + ], + name: "requestMessageReport", + outputs: [ + { + internalType: "bytes32", + name: "", + type: "bytes32" + } + ], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "enum CommonTypes.ChainType[]", + name: "chainTypes", + type: "uint8[]" + }, + { + internalType: "enum Types.OperatorRegistrationAction[]", + name: "operatorActions", + type: "uint8[]" + }, + { + internalType: "bytes[]", + name: "operatorAddresses", + type: "bytes[]" + } + ], + name: "requestOperatorRegistration", + outputs: [ + { + internalType: "bytes32", + name: "clfRequestId", + type: "bytes32" + } + ], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "setNativeUsdRate", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32", + name: "namespace", + type: "bytes32" + }, + { + internalType: "uint256", + name: "offset", + type: "uint256" + }, + { + internalType: "bytes32", + name: "mappingKey", + type: "bytes32" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "setStorage", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "bytes32[]", + name: "namespaces", + type: "bytes32[]" + }, + { + internalType: "uint256[]", + name: "offsets", + type: "uint256[]" + }, + { + internalType: "bytes32[]", + name: "mappingKeys", + type: "bytes32[]" + }, + { + internalType: "uint256[]", + name: "values", + type: "uint256[]" + } + ], + name: "setStorageBulk", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint24[]", + name: "chainSelectors", + type: "uint24[]" + }, + { + internalType: "bool[]", + name: "isSupported", + type: "bool[]" + } + ], + name: "setSupportedChains", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address[]", + name: "tokens", + type: "address[]" + }, + { + internalType: "uint256[]", + name: "amounts", + type: "uint256[]" + } + ], + name: "withdrawConceroFees", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "uint256", + name: "amount", + type: "uint256" + } + ], + name: "withdrawOperatorDeposit", + outputs: [ + { + internalType: "bool", + name: "success", + type: "bool" } ], - name: "operatorDeposit", - outputs: [], - stateMutability: "payable", + stateMutability: "nonpayable", type: "function" }, { inputs: [ { - internalType: "bytes32", - name: "messageId", - type: "bytes32" - }, - { - internalType: "bytes32", - name: "messageHashSum", - type: "bytes32" - }, - { - internalType: "uint24", - name: "srcChainSelector", - type: "uint24" - }, - { - internalType: "bytes", - name: "srcChainData", - type: "bytes" + internalType: "uint256", + name: "amount", + type: "uint256" } ], - name: "requestMessageReport", + name: "withdrawOperatorFee", outputs: [ { - internalType: "bytes32", - name: "", - type: "bytes32" + internalType: "bool", + name: "success", + type: "bool" } ], stateMutability: "nonpayable", type: "function" }, { - inputs: [ - { - internalType: "enum CommonTypes.ChainType[]", - name: "chainTypes", - type: "uint8[]" + stateMutability: "payable", + type: "receive" + } +]; + +// src/common/utils/AppError.ts +var AppError = class extends Error { + isOperational; + constructor(errorType, originalError) { + const { message, isOperational } = appErrors[errorType]; + super(originalError ? `${message}: ${originalError.message}` : message); + Object.setPrototypeOf(this, new.target.prototype); + this.name = this.constructor.name; + this.isOperational = isOperational; + this.stack = originalError?.stack; + this.logError(); + if (!this.isOperational) { + process.exit(1); + } + } + logError() { + console.error({ + name: this.name, + message: this.message, + stack: this.stack, + isOperational: this.isOperational + }); + } +}; + +// src/common/utils/Logger.ts +var import_winston = __toESM(require_winston(), 1); +var import_winston_daily_rotate_file = __toESM(require_winston_daily_rotate_file(), 1); + +// src/common/managers/ManagerBase.ts +var ManagerBase = class { + initialized = false; + async initialize() { + if (this.initialized) { + return; + } + try { + this.initialized = true; + } catch (error) { + throw error; + } + } + dispose() { + this.initialized = false; + } +}; + +// src/common/utils/Logger.ts +var Logger = class _Logger extends ManagerBase { + static instance; + baseLogger; + consumerLoggers = /* @__PURE__ */ new Map(); + config; + constructor(config3) { + super(); + this.config = config3; + this.baseLogger = this.createBaseLogger(); + } + static createInstance(config3) { + if (!_Logger.instance) { + _Logger.instance = new _Logger(config3); + } + return _Logger.instance; + } + static getInstance() { + if (!_Logger.instance) { + throw new Error("Logger is not initialized. Call createInstance() first."); + } + return _Logger.instance; + } + createBaseLogger() { + const logFormat = import_winston.default.format.combine( + import_winston.default.format.colorize({ level: true }), + import_winston.default.format.timestamp({ + format: "MM-DD HH:mm:ss" + }), + import_winston.default.format.printf(({ level, message, timestamp, consumer, ...meta }) => { + const prefix = consumer ? `${consumer}` : ""; + const formattedMessage = typeof message === "object" ? JSON.stringify(message, null, 2) : message; + const formattedMeta = meta && Object.keys(meta).length ? JSON.stringify(meta, null, 2) : ""; + return `${timestamp} ${level} ${prefix}: ${formattedMessage} ${formattedMeta}`.trim(); + }) + ); + const logger = import_winston.default.createLogger({ + level: "debug", + // Allow all logs through at base logger level + format: import_winston.default.format.json(), + transports: [ + new import_winston_daily_rotate_file.default({ + level: "debug", + dirname: this.config.logDir, + filename: "log-%DATE%.log", + datePattern: "YYYY-MM-DD", + maxSize: this.config.logMaxSize, + maxFiles: this.config.logMaxFiles + }), + new import_winston_daily_rotate_file.default({ + level: "error", + dirname: this.config.logDir, + filename: "error-%DATE%.log", + datePattern: "YYYY-MM-DD", + maxSize: this.config.logMaxSize, + maxFiles: this.config.logMaxFiles + }) + ] + }); + if (process.env.NODE_ENV !== "production") { + logger.add( + new import_winston.default.transports.Console({ + level: "debug", + format: logFormat + }) + ); + } + return logger; + } + async initialize() { + if (this.initialized) return; + super.initialize(); + this.getLogger("Logger").info("Initialized"); + } + getLogger(consumerName) { + const cacheKey2 = consumerName || "__default__"; + if (this.consumerLoggers.has(cacheKey2)) { + return this.consumerLoggers.get(cacheKey2); + } + const logger = this.createConsumerLogger(consumerName); + this.consumerLoggers.set(cacheKey2, logger); + return logger; + } + createConsumerLogger(consumerName) { + const getLogLevel = () => { + if (!consumerName) { + return this.config.logLevelDefault; + } + return this.config.logLevelsGranular[consumerName] || this.config.logLevelDefault; + }; + const logLevelValue = { + error: 0, + warn: 1, + info: 2, + debug: 3 + }; + const shouldLog = (messageLevel) => { + const configuredLevel = getLogLevel(); + const configLevelValue = logLevelValue[configuredLevel] || 2; + const messageLevelValue = logLevelValue[messageLevel] || 0; + return messageLevelValue <= configLevelValue; + }; + const logLevel = getLogLevel(); + return { + error: (message, ...meta) => { + this.baseLogger.error( + message, + consumerName ? { consumer: consumerName, ...meta } : meta + ); }, - { - internalType: "enum Types.OperatorRegistrationAction[]", - name: "operatorActions", - type: "uint8[]" + warn: (message, ...meta) => { + if (shouldLog("warn")) { + this.baseLogger.warn( + message, + consumerName ? { consumer: consumerName, ...meta } : meta + ); + } }, - { - internalType: "bytes[]", - name: "operatorAddresses", - type: "bytes[]" + info: (message, ...meta) => { + if (shouldLog("info")) { + this.baseLogger.info( + message, + consumerName ? { consumer: consumerName, ...meta } : meta + ); + } + }, + debug: (message, ...meta) => { + if (shouldLog("debug")) { + this.baseLogger.debug( + message, + consumerName ? { consumer: consumerName, ...meta } : meta + ); + } } - ], - name: "requestOperatorRegistration", - outputs: [ + }; + } + dispose() { + this.consumerLoggers.clear(); + super.dispose(); + } +}; + +// src/common/utils/sleep.ts +async function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// src/common/utils/asyncRetry.ts +async function asyncRetry(fn2, options = {}) { + const { maxRetries = 3, delayMs = 2e3, isRetryableError = () => false } = options; + const logger = Logger.getInstance().getLogger("AsyncRetry"); + let attempt = 0; + let lastError; + while (attempt <= maxRetries) { + try { + return await fn2(); + } catch (error) { + lastError = error; + if (await isRetryableError(error) && attempt < maxRetries) { + ++attempt; + logger.debug(`Retry attempt ${attempt} failed. Retrying in ${delayMs}ms...`); + await sleep(delayMs); + } else { + throw error; + } + } + } + throw lastError; +} + +// src/constants/confirmations.json +var confirmations_default = { + "1270": 3 +}; + +// node_modules/viem/_esm/index.js +init_exports(); + +// node_modules/viem/_esm/utils/getAction.js +function getAction(client, actionFn, name) { + const action_implicit = client[actionFn.name]; + if (typeof action_implicit === "function") + return action_implicit; + const action_explicit = client[name]; + if (typeof action_explicit === "function") + return action_explicit; + return (params) => actionFn(client, params); +} + +// node_modules/viem/_esm/utils/abi/encodeEventTopics.js +init_abi(); + +// node_modules/viem/_esm/errors/log.js +init_base(); +var FilterTypeNotSupportedError = class extends BaseError2 { + constructor(type) { + super(`Filter type "${type}" is not supported.`, { + name: "FilterTypeNotSupportedError" + }); + } +}; + +// node_modules/viem/_esm/utils/abi/encodeEventTopics.js +init_toBytes(); +init_keccak256(); +init_toEventSelector(); +init_encodeAbiParameters(); +init_formatAbiItem2(); +init_getAbiItem(); +var docsPath = "/docs/contract/encodeEventTopics"; +function encodeEventTopics(parameters) { + const { abi: abi4, eventName, args } = parameters; + let abiItem = abi4[0]; + if (eventName) { + const item = getAbiItem({ abi: abi4, name: eventName }); + if (!item) + throw new AbiEventNotFoundError(eventName, { docsPath }); + abiItem = item; + } + if (abiItem.type !== "event") + throw new AbiEventNotFoundError(void 0, { docsPath }); + const definition = formatAbiItem2(abiItem); + const signature = toEventSelector(definition); + let topics = []; + if (args && "inputs" in abiItem) { + const indexedInputs = abiItem.inputs?.filter((param) => "indexed" in param && param.indexed); + const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? indexedInputs?.map((x2) => args[x2.name]) ?? [] : []; + if (args_.length > 0) { + topics = indexedInputs?.map((param, i) => { + if (Array.isArray(args_[i])) + return args_[i].map((_, j2) => encodeArg({ param, value: args_[i][j2] })); + return typeof args_[i] !== "undefined" && args_[i] !== null ? encodeArg({ param, value: args_[i] }) : null; + }) ?? []; + } + } + return [signature, ...topics]; +} +function encodeArg({ param, value }) { + if (param.type === "string" || param.type === "bytes") + return keccak256(toBytes(value)); + if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) + throw new FilterTypeNotSupportedError(param.type); + return encodeAbiParameters([param], [value]); +} + +// node_modules/viem/_esm/actions/public/createContractEventFilter.js +init_toHex(); + +// node_modules/viem/_esm/utils/filters/createFilterRequestScope.js +function createFilterRequestScope(client, { method }) { + const requestMap = {}; + if (client.transport.type === "fallback") + client.transport.onResponse?.(({ method: method_, response: id2, status, transport }) => { + if (status === "success" && method === method_) + requestMap[id2] = transport.request; + }); + return (id2) => requestMap[id2] || client.request; +} + +// node_modules/viem/_esm/actions/public/createContractEventFilter.js +async function createContractEventFilter(client, parameters) { + const { address, abi: abi4, args, eventName, fromBlock, strict, toBlock } = parameters; + const getRequest = createFilterRequestScope(client, { + method: "eth_newFilter" + }); + const topics = eventName ? encodeEventTopics({ + abi: abi4, + args, + eventName + }) : void 0; + const id2 = await client.request({ + method: "eth_newFilter", + params: [ { - internalType: "bytes32", - name: "clfRequestId", - type: "bytes32" + address, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, + topics + } + ] + }); + return { + abi: abi4, + args, + eventName, + id: id2, + request: getRequest(id2), + strict: Boolean(strict), + type: "event" + }; +} + +// node_modules/viem/_esm/actions/public/estimateContractGas.js +init_parseAccount(); +init_encodeFunctionData(); + +// node_modules/viem/_esm/utils/errors/getContractError.js +init_abi(); +init_base(); +init_contract(); +init_request(); +init_rpc(); +var EXECUTION_REVERTED_ERROR_CODE = 3; +function getContractError(err, { abi: abi4, address, args, docsPath: docsPath6, functionName, sender }) { + const error = err instanceof RawContractError ? err : err instanceof BaseError2 ? err.walk((err2) => "data" in err2) || err.walk() : {}; + const { code, data, details, message, shortMessage } = error; + const cause = (() => { + if (err instanceof AbiDecodingZeroDataError) + return new ContractFunctionZeroDataError({ functionName }); + if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) && (data || details || message || shortMessage)) { + return new ContractFunctionRevertedError({ + abi: abi4, + data: typeof data === "object" ? data.data : data, + functionName, + message: error instanceof RpcRequestError ? details : shortMessage ?? message + }); + } + return err; + })(); + return new ContractFunctionExecutionError(cause, { + abi: abi4, + args, + contractAddress: address, + docsPath: docsPath6, + functionName, + sender + }); +} + +// node_modules/viem/_esm/actions/public/estimateGas.js +init_parseAccount(); +init_base(); + +// node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js +init_getAddress(); +init_keccak256(); +function publicKeyToAddress(publicKey) { + const address = keccak256(`0x${publicKey.substring(4)}`).substring(26); + return checksumAddress(`0x${address}`); +} + +// node_modules/viem/_esm/utils/signature/recoverPublicKey.js +init_isHex(); +init_fromHex(); +init_toHex(); +async function recoverPublicKey({ hash: hash2, signature }) { + const hashHex = isHex(hash2) ? hash2 : toHex(hash2); + const { secp256k1: secp256k12 } = await Promise.resolve().then(() => (init_secp256k1(), secp256k1_exports)); + const signature_ = (() => { + if (typeof signature === "object" && "r" in signature && "s" in signature) { + const { r, s, v, yParity } = signature; + const yParityOrV2 = Number(yParity ?? v); + const recoveryBit2 = toRecoveryBit(yParityOrV2); + return new secp256k12.Signature(hexToBigInt(r), hexToBigInt(s)).addRecoveryBit(recoveryBit2); + } + const signatureHex = isHex(signature) ? signature : toHex(signature); + const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`); + const recoveryBit = toRecoveryBit(yParityOrV); + return secp256k12.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit); + })(); + const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false); + return `0x${publicKey}`; +} +function toRecoveryBit(yParityOrV) { + if (yParityOrV === 0 || yParityOrV === 1) + return yParityOrV; + if (yParityOrV === 27) + return 0; + if (yParityOrV === 28) + return 1; + throw new Error("Invalid yParityOrV value"); +} + +// node_modules/viem/_esm/utils/signature/recoverAddress.js +async function recoverAddress({ hash: hash2, signature }) { + return publicKeyToAddress(await recoverPublicKey({ hash: hash2, signature })); +} + +// node_modules/viem/_esm/utils/authorization/hashAuthorization.js +init_concat(); +init_toBytes(); +init_toHex(); + +// node_modules/viem/_esm/utils/encoding/toRlp.js +init_base(); +init_cursor2(); +init_toBytes(); +init_toHex(); +function toRlp(bytes, to2 = "hex") { + const encodable = getEncodable(bytes); + const cursor = createCursor(new Uint8Array(encodable.length)); + encodable.encode(cursor); + if (to2 === "hex") + return bytesToHex(cursor.bytes); + return cursor.bytes; +} +function getEncodable(bytes) { + if (Array.isArray(bytes)) + return getEncodableList(bytes.map((x2) => getEncodable(x2))); + return getEncodableBytes(bytes); +} +function getEncodableList(list) { + const bodyLength = list.reduce((acc, x2) => acc + x2.length, 0); + const sizeOfBodyLength = getSizeOfLength(bodyLength); + const length = (() => { + if (bodyLength <= 55) + return 1 + bodyLength; + return 1 + sizeOfBodyLength + bodyLength; + })(); + return { + length, + encode(cursor) { + if (bodyLength <= 55) { + cursor.pushByte(192 + bodyLength); + } else { + cursor.pushByte(192 + 55 + sizeOfBodyLength); + if (sizeOfBodyLength === 1) + cursor.pushUint8(bodyLength); + else if (sizeOfBodyLength === 2) + cursor.pushUint16(bodyLength); + else if (sizeOfBodyLength === 3) + cursor.pushUint24(bodyLength); + else + cursor.pushUint32(bodyLength); } - ], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "uint256", - name: "amount", - type: "uint256" + for (const { encode: encode6 } of list) { + encode6(cursor); } - ], - name: "setNativeUsdRate", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "bytes32", - name: "namespace", - type: "bytes32" - }, - { - internalType: "uint256", - name: "offset", - type: "uint256" - }, - { - internalType: "bytes32", - name: "mappingKey", - type: "bytes32" - }, - { - internalType: "uint256", - name: "value", - type: "uint256" + } + }; +} +function getEncodableBytes(bytesOrHex) { + const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex; + const sizeOfBytesLength = getSizeOfLength(bytes.length); + const length = (() => { + if (bytes.length === 1 && bytes[0] < 128) + return 1; + if (bytes.length <= 55) + return 1 + bytes.length; + return 1 + sizeOfBytesLength + bytes.length; + })(); + return { + length, + encode(cursor) { + if (bytes.length === 1 && bytes[0] < 128) { + cursor.pushBytes(bytes); + } else if (bytes.length <= 55) { + cursor.pushByte(128 + bytes.length); + cursor.pushBytes(bytes); + } else { + cursor.pushByte(128 + 55 + sizeOfBytesLength); + if (sizeOfBytesLength === 1) + cursor.pushUint8(bytes.length); + else if (sizeOfBytesLength === 2) + cursor.pushUint16(bytes.length); + else if (sizeOfBytesLength === 3) + cursor.pushUint24(bytes.length); + else + cursor.pushUint32(bytes.length); + cursor.pushBytes(bytes); } - ], - name: "setStorage", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "bytes32[]", - name: "namespaces", - type: "bytes32[]" - }, - { - internalType: "uint256[]", - name: "offsets", - type: "uint256[]" - }, - { - internalType: "bytes32[]", - name: "mappingKeys", - type: "bytes32[]" - }, - { - internalType: "uint256[]", - name: "values", - type: "uint256[]" + } + }; +} +function getSizeOfLength(length) { + if (length < 2 ** 8) + return 1; + if (length < 2 ** 16) + return 2; + if (length < 2 ** 24) + return 3; + if (length < 2 ** 32) + return 4; + throw new BaseError2("Length is too large."); +} + +// node_modules/viem/_esm/utils/authorization/hashAuthorization.js +init_keccak256(); +function hashAuthorization(parameters) { + const { chainId, nonce, to: to2 } = parameters; + const address = parameters.contractAddress ?? parameters.address; + const hash2 = keccak256(concatHex([ + "0x05", + toRlp([ + chainId ? numberToHex(chainId) : "0x", + address, + nonce ? numberToHex(nonce) : "0x" + ]) + ])); + if (to2 === "bytes") + return hexToBytes(hash2); + return hash2; +} + +// node_modules/viem/_esm/utils/authorization/recoverAuthorizationAddress.js +async function recoverAuthorizationAddress(parameters) { + const { authorization, signature } = parameters; + return recoverAddress({ + hash: hashAuthorization(authorization), + signature: signature ?? authorization + }); +} + +// node_modules/viem/_esm/actions/public/estimateGas.js +init_toHex(); + +// node_modules/viem/_esm/errors/estimateGas.js +init_formatEther(); +init_formatGwei(); +init_base(); +init_transaction(); +var EstimateGasExecutionError = class extends BaseError2 { + constructor(cause, { account, docsPath: docsPath6, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value }) { + const prettyArgs = prettyPrint({ + from: account?.address, + to: to2, + value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, + data, + gas, + gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, + maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, + maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, + nonce + }); + super(cause.shortMessage, { + cause, + docsPath: docsPath6, + metaMessages: [ + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Estimate Gas Arguments:", + prettyArgs + ].filter(Boolean), + name: "EstimateGasExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cause = cause; + } +}; + +// node_modules/viem/_esm/utils/errors/getEstimateGasError.js +init_node(); +init_getNodeError(); +function getEstimateGasError(err, { docsPath: docsPath6, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new EstimateGasExecutionError(cause, { + docsPath: docsPath6, + ...args + }); +} + +// node_modules/viem/_esm/actions/public/estimateGas.js +init_extract(); +init_transactionRequest(); +init_stateOverride2(); +init_assertRequest(); + +// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js +init_parseAccount(); + +// node_modules/viem/_esm/errors/fee.js +init_formatGwei(); +init_base(); +var BaseFeeScalarError = class extends BaseError2 { + constructor() { + super("`baseFeeMultiplier` must be greater than 1.", { + name: "BaseFeeScalarError" + }); + } +}; +var Eip1559FeesNotSupportedError = class extends BaseError2 { + constructor() { + super("Chain does not support EIP-1559 fees.", { + name: "Eip1559FeesNotSupportedError" + }); + } +}; +var MaxFeePerGasTooLowError = class extends BaseError2 { + constructor({ maxPriorityFeePerGas }) { + super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" }); + } +}; + +// node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js +init_fromHex(); + +// node_modules/viem/_esm/errors/block.js +init_base(); +var BlockNotFoundError = class extends BaseError2 { + constructor({ blockHash, blockNumber }) { + let identifier = "Block"; + if (blockHash) + identifier = `Block at hash "${blockHash}"`; + if (blockNumber) + identifier = `Block at number "${blockNumber}"`; + super(`${identifier} could not be found.`, { name: "BlockNotFoundError" }); + } +}; + +// node_modules/viem/_esm/actions/public/getBlock.js +init_toHex(); + +// node_modules/viem/_esm/utils/formatters/transaction.js +init_fromHex(); +var transactionType = { + "0x0": "legacy", + "0x1": "eip2930", + "0x2": "eip1559", + "0x3": "eip4844", + "0x4": "eip7702" +}; +function formatTransaction(transaction) { + const transaction_ = { + ...transaction, + blockHash: transaction.blockHash ? transaction.blockHash : null, + blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null, + chainId: transaction.chainId ? hexToNumber(transaction.chainId) : void 0, + gas: transaction.gas ? BigInt(transaction.gas) : void 0, + gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0, + maxFeePerBlobGas: transaction.maxFeePerBlobGas ? BigInt(transaction.maxFeePerBlobGas) : void 0, + maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0, + maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0, + nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0, + to: transaction.to ? transaction.to : null, + transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null, + type: transaction.type ? transactionType[transaction.type] : void 0, + typeHex: transaction.type ? transaction.type : void 0, + value: transaction.value ? BigInt(transaction.value) : void 0, + v: transaction.v ? BigInt(transaction.v) : void 0 + }; + if (transaction.authorizationList) + transaction_.authorizationList = formatAuthorizationList2(transaction.authorizationList); + transaction_.yParity = (() => { + if (transaction.yParity) + return Number(transaction.yParity); + if (typeof transaction_.v === "bigint") { + if (transaction_.v === 0n || transaction_.v === 27n) + return 0; + if (transaction_.v === 1n || transaction_.v === 28n) + return 1; + if (transaction_.v >= 35n) + return transaction_.v % 2n === 0n ? 1 : 0; + } + return void 0; + })(); + if (transaction_.type === "legacy") { + delete transaction_.accessList; + delete transaction_.maxFeePerBlobGas; + delete transaction_.maxFeePerGas; + delete transaction_.maxPriorityFeePerGas; + delete transaction_.yParity; + } + if (transaction_.type === "eip2930") { + delete transaction_.maxFeePerBlobGas; + delete transaction_.maxFeePerGas; + delete transaction_.maxPriorityFeePerGas; + } + if (transaction_.type === "eip1559") { + delete transaction_.maxFeePerBlobGas; + } + return transaction_; +} +function formatAuthorizationList2(authorizationList) { + return authorizationList.map((authorization) => ({ + address: authorization.address, + chainId: Number(authorization.chainId), + nonce: Number(authorization.nonce), + r: authorization.r, + s: authorization.s, + yParity: Number(authorization.yParity) + })); +} + +// node_modules/viem/_esm/utils/formatters/block.js +function formatBlock(block) { + const transactions = (block.transactions ?? []).map((transaction) => { + if (typeof transaction === "string") + return transaction; + return formatTransaction(transaction); + }); + return { + ...block, + baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null, + blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : void 0, + difficulty: block.difficulty ? BigInt(block.difficulty) : void 0, + excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : void 0, + gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0, + gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0, + hash: block.hash ? block.hash : null, + logsBloom: block.logsBloom ? block.logsBloom : null, + nonce: block.nonce ? block.nonce : null, + number: block.number ? BigInt(block.number) : null, + size: block.size ? BigInt(block.size) : void 0, + timestamp: block.timestamp ? BigInt(block.timestamp) : void 0, + transactions, + totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null + }; +} + +// node_modules/viem/_esm/actions/public/getBlock.js +async function getBlock(client, { blockHash, blockNumber, blockTag: blockTag_, includeTransactions: includeTransactions_ } = {}) { + const blockTag = blockTag_ ?? "latest"; + const includeTransactions = includeTransactions_ ?? false; + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + let block = null; + if (blockHash) { + block = await client.request({ + method: "eth_getBlockByHash", + params: [blockHash, includeTransactions] + }, { dedupe: true }); + } else { + block = await client.request({ + method: "eth_getBlockByNumber", + params: [blockNumberHex || blockTag, includeTransactions] + }, { dedupe: Boolean(blockNumberHex) }); + } + if (!block) + throw new BlockNotFoundError({ blockHash, blockNumber }); + const format = client.chain?.formatters?.block?.format || formatBlock; + return format(block); +} + +// node_modules/viem/_esm/actions/public/getGasPrice.js +async function getGasPrice(client) { + const gasPrice = await client.request({ + method: "eth_gasPrice" + }); + return BigInt(gasPrice); +} + +// node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js +async function estimateMaxPriorityFeePerGas(client, args) { + return internal_estimateMaxPriorityFeePerGas(client, args); +} +async function internal_estimateMaxPriorityFeePerGas(client, args) { + const { block: block_, chain = client.chain, request } = args || {}; + try { + const maxPriorityFeePerGas = chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee; + if (typeof maxPriorityFeePerGas === "function") { + const block = block_ || await getAction(client, getBlock, "getBlock")({}); + const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({ + block, + client, + request + }); + if (maxPriorityFeePerGas_ === null) + throw new Error(); + return maxPriorityFeePerGas_; + } + if (typeof maxPriorityFeePerGas !== "undefined") + return maxPriorityFeePerGas; + const maxPriorityFeePerGasHex = await client.request({ + method: "eth_maxPriorityFeePerGas" + }); + return hexToBigInt(maxPriorityFeePerGasHex); + } catch { + const [block, gasPrice] = await Promise.all([ + block_ ? Promise.resolve(block_) : getAction(client, getBlock, "getBlock")({}), + getAction(client, getGasPrice, "getGasPrice")({}) + ]); + if (typeof block.baseFeePerGas !== "bigint") + throw new Eip1559FeesNotSupportedError(); + const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas; + if (maxPriorityFeePerGas < 0n) + return 0n; + return maxPriorityFeePerGas; + } +} + +// node_modules/viem/_esm/actions/public/estimateFeesPerGas.js +async function estimateFeesPerGas(client, args) { + return internal_estimateFeesPerGas(client, args); +} +async function internal_estimateFeesPerGas(client, args) { + const { block: block_, chain = client.chain, request, type = "eip1559" } = args || {}; + const baseFeeMultiplier = await (async () => { + if (typeof chain?.fees?.baseFeeMultiplier === "function") + return chain.fees.baseFeeMultiplier({ + block: block_, + client, + request + }); + return chain?.fees?.baseFeeMultiplier ?? 1.2; + })(); + if (baseFeeMultiplier < 1) + throw new BaseFeeScalarError(); + const decimals = baseFeeMultiplier.toString().split(".")[1]?.length ?? 0; + const denominator = 10 ** decimals; + const multiply = (base) => base * BigInt(Math.ceil(baseFeeMultiplier * denominator)) / BigInt(denominator); + const block = block_ ? block_ : await getAction(client, getBlock, "getBlock")({}); + if (typeof chain?.fees?.estimateFeesPerGas === "function") { + const fees = await chain.fees.estimateFeesPerGas({ + block: block_, + client, + multiply, + request, + type + }); + if (fees !== null) + return fees; + } + if (type === "eip1559") { + if (typeof block.baseFeePerGas !== "bigint") + throw new Eip1559FeesNotSupportedError(); + const maxPriorityFeePerGas = typeof request?.maxPriorityFeePerGas === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, { + block, + chain, + request + }); + const baseFeePerGas = multiply(block.baseFeePerGas); + const maxFeePerGas = request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas; + return { + maxFeePerGas, + maxPriorityFeePerGas + }; + } + const gasPrice = request?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({})); + return { + gasPrice + }; +} + +// node_modules/viem/_esm/actions/public/getTransactionCount.js +init_fromHex(); +init_toHex(); +async function getTransactionCount(client, { address, blockTag = "latest", blockNumber }) { + const count = await client.request({ + method: "eth_getTransactionCount", + params: [address, blockNumber ? numberToHex(blockNumber) : blockTag] + }, { dedupe: Boolean(blockNumber) }); + return hexToNumber(count); +} + +// node_modules/viem/_esm/utils/blob/blobsToCommitments.js +init_toBytes(); +init_toHex(); +function blobsToCommitments(parameters) { + const { kzg } = parameters; + const to2 = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); + const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x2) => hexToBytes(x2)) : parameters.blobs; + const commitments = []; + for (const blob of blobs) + commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob))); + return to2 === "bytes" ? commitments : commitments.map((x2) => bytesToHex(x2)); +} + +// node_modules/viem/_esm/utils/blob/blobsToProofs.js +init_toBytes(); +init_toHex(); +function blobsToProofs(parameters) { + const { kzg } = parameters; + const to2 = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); + const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x2) => hexToBytes(x2)) : parameters.blobs; + const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x2) => hexToBytes(x2)) : parameters.commitments; + const proofs = []; + for (let i = 0; i < blobs.length; i++) { + const blob = blobs[i]; + const commitment = commitments[i]; + proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment))); + } + return to2 === "bytes" ? proofs : proofs.map((x2) => bytesToHex(x2)); +} + +// node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js +init_toHex(); + +// node_modules/viem/_esm/utils/hash/sha256.js +init_sha256(); +init_isHex(); +init_toBytes(); +init_toHex(); +function sha2562(value, to_) { + const to2 = to_ || "hex"; + const bytes = sha256(isHex(value, { strict: false }) ? toBytes(value) : value); + if (to2 === "bytes") + return bytes; + return toHex(bytes); +} + +// node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js +function commitmentToVersionedHash(parameters) { + const { commitment, version: version4 = 1 } = parameters; + const to2 = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes"); + const versionedHash = sha2562(commitment, "bytes"); + versionedHash.set([version4], 0); + return to2 === "bytes" ? versionedHash : bytesToHex(versionedHash); +} + +// node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js +function commitmentsToVersionedHashes(parameters) { + const { commitments, version: version4 } = parameters; + const to2 = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes"); + const hashes = []; + for (const commitment of commitments) { + hashes.push(commitmentToVersionedHash({ + commitment, + to: to2, + version: version4 + })); + } + return hashes; +} + +// node_modules/viem/_esm/constants/blob.js +var blobsPerTransaction = 6; +var bytesPerFieldElement = 32; +var fieldElementsPerBlob = 4096; +var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob; +var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80). +1 - // zero byte (0x00) appended to each field element. +1 * fieldElementsPerBlob * blobsPerTransaction; + +// node_modules/viem/_esm/constants/kzg.js +var versionedHashVersionKzg = 1; + +// node_modules/viem/_esm/errors/blob.js +init_base(); +var BlobSizeTooLargeError = class extends BaseError2 { + constructor({ maxSize, size: size5 }) { + super("Blob size is too large.", { + metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size5} bytes`], + name: "BlobSizeTooLargeError" + }); + } +}; +var EmptyBlobError = class extends BaseError2 { + constructor() { + super("Blob data must not be empty.", { name: "EmptyBlobError" }); + } +}; +var InvalidVersionedHashSizeError = class extends BaseError2 { + constructor({ hash: hash2, size: size5 }) { + super(`Versioned hash "${hash2}" size is invalid.`, { + metaMessages: ["Expected: 32", `Received: ${size5}`], + name: "InvalidVersionedHashSizeError" + }); + } +}; +var InvalidVersionedHashVersionError = class extends BaseError2 { + constructor({ hash: hash2, version: version4 }) { + super(`Versioned hash "${hash2}" version is invalid.`, { + metaMessages: [ + `Expected: ${versionedHashVersionKzg}`, + `Received: ${version4}` + ], + name: "InvalidVersionedHashVersionError" + }); + } +}; + +// node_modules/viem/_esm/utils/blob/toBlobs.js +init_cursor2(); +init_size(); +init_toBytes(); +init_toHex(); +function toBlobs(parameters) { + const to2 = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes"); + const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data; + const size_ = size(data); + if (!size_) + throw new EmptyBlobError(); + if (size_ > maxBytesPerTransaction) + throw new BlobSizeTooLargeError({ + maxSize: maxBytesPerTransaction, + size: size_ + }); + const blobs = []; + let active = true; + let position = 0; + while (active) { + const blob = createCursor(new Uint8Array(bytesPerBlob)); + let size5 = 0; + while (size5 < fieldElementsPerBlob) { + const bytes = data.slice(position, position + (bytesPerFieldElement - 1)); + blob.pushByte(0); + blob.pushBytes(bytes); + if (bytes.length < 31) { + blob.pushByte(128); + active = false; + break; } - ], - name: "setStorageBulk", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "uint24[]", - name: "chainSelectors", - type: "uint24[]" - }, - { - internalType: "bool[]", - name: "isSupported", - type: "bool[]" + size5++; + position += 31; + } + blobs.push(blob); + } + return to2 === "bytes" ? blobs.map((x2) => x2.bytes) : blobs.map((x2) => bytesToHex(x2.bytes)); +} + +// node_modules/viem/_esm/utils/blob/toBlobSidecars.js +function toBlobSidecars(parameters) { + const { data, kzg, to: to2 } = parameters; + const blobs = parameters.blobs ?? toBlobs({ data, to: to2 }); + const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to: to2 }); + const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to: to2 }); + const sidecars = []; + for (let i = 0; i < blobs.length; i++) + sidecars.push({ + blob: blobs[i], + commitment: commitments[i], + proof: proofs[i] + }); + return sidecars; +} + +// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js +init_assertRequest(); + +// node_modules/viem/_esm/utils/transaction/getTransactionType.js +init_transaction(); +function getTransactionType(transaction) { + if (transaction.type) + return transaction.type; + if (typeof transaction.authorizationList !== "undefined") + return "eip7702"; + if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined") + return "eip4844"; + if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") { + return "eip1559"; + } + if (typeof transaction.gasPrice !== "undefined") { + if (typeof transaction.accessList !== "undefined") + return "eip2930"; + return "legacy"; + } + throw new InvalidSerializableTransactionError({ transaction }); +} + +// node_modules/viem/_esm/actions/public/getChainId.js +init_fromHex(); +async function getChainId(client) { + const chainIdHex = await client.request({ + method: "eth_chainId" + }, { dedupe: true }); + return hexToNumber(chainIdHex); +} + +// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js +var defaultParameters = [ + "blobVersionedHashes", + "chainId", + "fees", + "gas", + "nonce", + "type" +]; +var eip1559NetworkCache = /* @__PURE__ */ new Map(); +async function prepareTransactionRequest(client, args) { + const { account: account_ = client.account, blobs, chain, gas, kzg, nonce, nonceManager, parameters = defaultParameters, type } = args; + const account = account_ ? parseAccount(account_) : account_; + const request = { ...args, ...account ? { from: account?.address } : {} }; + let block; + async function getBlock2() { + if (block) + return block; + block = await getAction(client, getBlock, "getBlock")({ blockTag: "latest" }); + return block; + } + let chainId; + async function getChainId2() { + if (chainId) + return chainId; + if (chain) + return chain.id; + if (typeof args.chainId !== "undefined") + return args.chainId; + const chainId_ = await getAction(client, getChainId, "getChainId")({}); + chainId = chainId_; + return chainId; + } + if (parameters.includes("nonce") && typeof nonce === "undefined" && account) { + if (nonceManager) { + const chainId2 = await getChainId2(); + request.nonce = await nonceManager.consume({ + address: account.address, + chainId: chainId2, + client + }); + } else { + request.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({ + address: account.address, + blockTag: "pending" + }); + } + } + if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) { + const commitments = blobsToCommitments({ blobs, kzg }); + if (parameters.includes("blobVersionedHashes")) { + const versionedHashes = commitmentsToVersionedHashes({ + commitments, + to: "hex" + }); + request.blobVersionedHashes = versionedHashes; + } + if (parameters.includes("sidecars")) { + const proofs = blobsToProofs({ blobs, commitments, kzg }); + const sidecars = toBlobSidecars({ + blobs, + commitments, + proofs, + to: "hex" + }); + request.sidecars = sidecars; + } + } + if (parameters.includes("chainId")) + request.chainId = await getChainId2(); + if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") { + try { + request.type = getTransactionType(request); + } catch { + let isEip1559Network = eip1559NetworkCache.get(client.uid); + if (typeof isEip1559Network === "undefined") { + const block2 = await getBlock2(); + isEip1559Network = typeof block2?.baseFeePerGas === "bigint"; + eip1559NetworkCache.set(client.uid, isEip1559Network); } - ], - name: "setSupportedChains", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "address[]", - name: "tokens", - type: "address[]" - }, - { - internalType: "uint256[]", - name: "amounts", - type: "uint256[]" + request.type = isEip1559Network ? "eip1559" : "legacy"; + } + } + if (parameters.includes("fees")) { + if (request.type !== "legacy" && request.type !== "eip2930") { + if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") { + const block2 = await getBlock2(); + const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client, { + block: block2, + chain, + request + }); + if (typeof args.maxPriorityFeePerGas === "undefined" && args.maxFeePerGas && args.maxFeePerGas < maxPriorityFeePerGas) + throw new MaxFeePerGasTooLowError({ + maxPriorityFeePerGas + }); + request.maxPriorityFeePerGas = maxPriorityFeePerGas; + request.maxFeePerGas = maxFeePerGas; } - ], - name: "withdrawConceroFees", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "uint256", - name: "amount", - type: "uint256" + } else { + if (typeof args.maxFeePerGas !== "undefined" || typeof args.maxPriorityFeePerGas !== "undefined") + throw new Eip1559FeesNotSupportedError(); + if (typeof args.gasPrice === "undefined") { + const block2 = await getBlock2(); + const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, { + block: block2, + chain, + request, + type: "legacy" + }); + request.gasPrice = gasPrice_; } - ], - name: "withdrawOperatorDeposit", - outputs: [ - { - internalType: "bool", - name: "success", - type: "bool" + } + } + if (parameters.includes("gas") && typeof gas === "undefined") + request.gas = await getAction(client, estimateGas, "estimateGas")({ + ...request, + account: account ? { address: account.address, type: "json-rpc" } : account + }); + assertRequest(request); + delete request.parameters; + return request; +} + +// node_modules/viem/_esm/actions/public/getBalance.js +init_toHex(); +async function getBalance(client, { address, blockNumber, blockTag = "latest" }) { + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const balance = await client.request({ + method: "eth_getBalance", + params: [address, blockNumberHex || blockTag] + }); + return BigInt(balance); +} + +// node_modules/viem/_esm/actions/public/estimateGas.js +async function estimateGas(client, args) { + const { account: account_ = client.account } = args; + const account = account_ ? parseAccount(account_) : void 0; + try { + let estimateGas_rpc = function(parameters) { + const { block: block2, request: request2, rpcStateOverride: rpcStateOverride2 } = parameters; + return client.request({ + method: "eth_estimateGas", + params: rpcStateOverride2 ? [request2, block2 ?? "latest", rpcStateOverride2] : block2 ? [request2, block2] : [request2] + }); + }; + const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = await prepareTransactionRequest(client, { + ...args, + parameters: ( + // Some RPC Providers do not compute versioned hashes from blobs. We will need + // to compute them. + account?.type === "local" ? void 0 : ["blobVersionedHashes"] + ) + }); + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const rpcStateOverride = serializeStateOverride(stateOverride); + const to2 = await (async () => { + if (rest.to) + return rest.to; + if (authorizationList && authorizationList.length > 0) + return await recoverAuthorizationAddress({ + authorization: authorizationList[0] + }).catch(() => { + throw new BaseError2("`to` is required. Could not infer from `authorizationList`"); + }); + return void 0; + })(); + assertRequest(args); + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format = chainFormat || formatTransactionRequest; + const request = format({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + from: account?.address, + accessList, + authorizationList, + blobs, + blobVersionedHashes, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to: to2, + value + }); + let estimate = BigInt(await estimateGas_rpc({ block, request, rpcStateOverride })); + if (authorizationList) { + const value2 = await getBalance(client, { address: request.from }); + const estimates = await Promise.all(authorizationList.map(async (authorization) => { + const { address } = authorization; + const estimate2 = await estimateGas_rpc({ + block, + request: { + authorizationList: void 0, + data, + from: account?.address, + to: address, + value: numberToHex(value2) + }, + rpcStateOverride + }).catch(() => 100000n); + return 2n * BigInt(estimate2); + })); + estimate += estimates.reduce((acc, curr) => acc + curr, 0n); + } + return estimate; + } catch (err) { + throw getEstimateGasError(err, { + ...args, + account, + chain: client.chain + }); + } +} + +// node_modules/viem/_esm/actions/public/estimateContractGas.js +async function estimateContractGas(client, parameters) { + const { abi: abi4, address, args, functionName, dataSuffix, ...request } = parameters; + const data = encodeFunctionData({ + abi: abi4, + args, + functionName + }); + try { + const gas = await getAction(client, estimateGas, "estimateGas")({ + data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, + to: address, + ...request + }); + return gas; + } catch (error) { + const account = request.account ? parseAccount(request.account) : void 0; + throw getContractError(error, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/estimateContractGas", + functionName, + sender: account?.address + }); + } +} + +// node_modules/viem/_esm/actions/public/getContractEvents.js +init_getAbiItem(); + +// node_modules/viem/_esm/utils/abi/parseEventLogs.js +init_abi(); +init_isAddressEqual(); +init_toBytes(); +init_keccak256(); +init_toEventSelector(); + +// node_modules/viem/_esm/utils/abi/decodeEventLog.js +init_abi(); +init_size(); +init_toEventSelector(); +init_cursor(); +init_decodeAbiParameters(); +init_formatAbiItem2(); +var docsPath3 = "/docs/contract/decodeEventLog"; +function decodeEventLog(parameters) { + const { abi: abi4, data, strict: strict_, topics } = parameters; + const strict = strict_ ?? true; + const [signature, ...argTopics] = topics; + if (!signature) + throw new AbiEventSignatureEmptyTopicsError({ docsPath: docsPath3 }); + const abiItem = (() => { + if (abi4.length === 1) + return abi4[0]; + return abi4.find((x2) => x2.type === "event" && signature === toEventSelector(formatAbiItem2(x2))); + })(); + if (!(abiItem && "name" in abiItem) || abiItem.type !== "event") + throw new AbiEventSignatureNotFoundError(signature, { docsPath: docsPath3 }); + const { name, inputs } = abiItem; + const isUnnamed = inputs?.some((x2) => !("name" in x2 && x2.name)); + let args = isUnnamed ? [] : {}; + const indexedInputs = inputs.filter((x2) => "indexed" in x2 && x2.indexed); + for (let i = 0; i < indexedInputs.length; i++) { + const param = indexedInputs[i]; + const topic = argTopics[i]; + if (!topic) + throw new DecodeLogTopicsMismatch({ + abiItem, + param + }); + args[isUnnamed ? i : param.name || i] = decodeTopic({ param, value: topic }); + } + const nonIndexedInputs = inputs.filter((x2) => !("indexed" in x2 && x2.indexed)); + if (nonIndexedInputs.length > 0) { + if (data && data !== "0x") { + try { + const decodedData = decodeAbiParameters(nonIndexedInputs, data); + if (decodedData) { + if (isUnnamed) + args = [...args, ...decodedData]; + else { + for (let i = 0; i < nonIndexedInputs.length; i++) { + args[nonIndexedInputs[i].name] = decodedData[i]; + } + } + } + } catch (err) { + if (strict) { + if (err instanceof AbiDecodingDataSizeTooSmallError || err instanceof PositionOutOfBoundsError) + throw new DecodeLogDataMismatch({ + abiItem, + data, + params: nonIndexedInputs, + size: size(data) + }); + throw err; + } } - ], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - internalType: "uint256", - name: "amount", - type: "uint256" + } else if (strict) { + throw new DecodeLogDataMismatch({ + abiItem, + data: "0x", + params: nonIndexedInputs, + size: 0 + }); + } + } + return { + eventName: name, + args: Object.values(args).length > 0 ? args : void 0 + }; +} +function decodeTopic({ param, value }) { + if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) + return value; + const decodedArg = decodeAbiParameters([param], value) || []; + return decodedArg[0]; +} + +// node_modules/viem/_esm/utils/abi/parseEventLogs.js +function parseEventLogs(parameters) { + const { abi: abi4, args, logs, strict = true } = parameters; + const eventName = (() => { + if (!parameters.eventName) + return void 0; + if (Array.isArray(parameters.eventName)) + return parameters.eventName; + return [parameters.eventName]; + })(); + return logs.map((log) => { + try { + const abiItem = abi4.find((abiItem2) => abiItem2.type === "event" && log.topics[0] === toEventSelector(abiItem2)); + if (!abiItem) + return null; + const event = decodeEventLog({ + ...log, + abi: [abiItem], + strict + }); + if (eventName && !eventName.includes(event.eventName)) + return null; + if (!includesArgs({ + args: event.args, + inputs: abiItem.inputs, + matchArgs: args + })) + return null; + return { ...event, ...log }; + } catch (err) { + let eventName2; + let isUnnamed; + if (err instanceof AbiEventSignatureNotFoundError) + return null; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict) + return null; + eventName2 = err.abiItem.name; + isUnnamed = err.abiItem.inputs?.some((x2) => !("name" in x2 && x2.name)); } - ], - name: "withdrawOperatorFee", - outputs: [ - { - internalType: "bool", - name: "success", - type: "bool" + return { ...log, args: isUnnamed ? [] : {}, eventName: eventName2 }; + } + }).filter(Boolean); +} +function includesArgs(parameters) { + const { args, inputs, matchArgs } = parameters; + if (!matchArgs) + return true; + if (!args) + return false; + function isEqual(input, value, arg) { + try { + if (input.type === "address") + return isAddressEqual(value, arg); + if (input.type === "string" || input.type === "bytes") + return keccak256(toBytes(value)) === arg; + return value === arg; + } catch { + return false; + } + } + if (Array.isArray(args) && Array.isArray(matchArgs)) { + return matchArgs.every((value, index2) => { + if (value === null || value === void 0) + return true; + const input = inputs[index2]; + if (!input) + return false; + const value_ = Array.isArray(value) ? value : [value]; + return value_.some((value2) => isEqual(input, value2, args[index2])); + }); + } + if (typeof args === "object" && !Array.isArray(args) && typeof matchArgs === "object" && !Array.isArray(matchArgs)) + return Object.entries(matchArgs).every(([key, value]) => { + if (value === null || value === void 0) + return true; + const input = inputs.find((input2) => input2.name === key); + if (!input) + return false; + const value_ = Array.isArray(value) ? value : [value]; + return value_.some((value2) => isEqual(input, value2, args[key])); + }); + return false; +} + +// node_modules/viem/_esm/actions/public/getLogs.js +init_toHex(); + +// node_modules/viem/_esm/utils/formatters/log.js +function formatLog(log, { args, eventName } = {}) { + return { + ...log, + blockHash: log.blockHash ? log.blockHash : null, + blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null, + logIndex: log.logIndex ? Number(log.logIndex) : null, + transactionHash: log.transactionHash ? log.transactionHash : null, + transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null, + ...eventName ? { args, eventName } : {} + }; +} + +// node_modules/viem/_esm/actions/public/getLogs.js +async function getLogs(client, { address, blockHash, fromBlock, toBlock, event, events: events_, args, strict: strict_ } = {}) { + const strict = strict_ ?? false; + const events = events_ ?? (event ? [event] : void 0); + let topics = []; + if (events) { + const encoded = events.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args: events_ ? void 0 : args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + let logs; + if (blockHash) { + logs = await client.request({ + method: "eth_getLogs", + params: [{ address, topics, blockHash }] + }); + } else { + logs = await client.request({ + method: "eth_getLogs", + params: [ + { + address, + topics, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock + } + ] + }); + } + const formattedLogs = logs.map((log) => formatLog(log)); + if (!events) + return formattedLogs; + return parseEventLogs({ + abi: events, + args, + logs: formattedLogs, + strict + }); +} + +// node_modules/viem/_esm/actions/public/getContractEvents.js +async function getContractEvents(client, parameters) { + const { abi: abi4, address, args, blockHash, eventName, fromBlock, toBlock, strict } = parameters; + const event = eventName ? getAbiItem({ abi: abi4, name: eventName }) : void 0; + const events = !event ? abi4.filter((x2) => x2.type === "event") : void 0; + return getAction(client, getLogs, "getLogs")({ + address, + args, + blockHash, + event, + events, + fromBlock, + toBlock, + strict + }); +} + +// node_modules/viem/_esm/actions/public/readContract.js +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_call(); +async function readContract(client, parameters) { + const { abi: abi4, address, args, functionName, ...rest } = parameters; + const calldata = encodeFunctionData({ + abi: abi4, + args, + functionName + }); + try { + const { data } = await getAction(client, call, "call")({ + ...rest, + data: calldata, + to: address + }); + return decodeFunctionResult({ + abi: abi4, + args, + functionName, + data: data || "0x" + }); + } catch (error) { + throw getContractError(error, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/readContract", + functionName + }); + } +} + +// node_modules/viem/_esm/actions/public/simulateContract.js +init_parseAccount(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_call(); +async function simulateContract(client, parameters) { + const { abi: abi4, address, args, dataSuffix, functionName, ...callRequest } = parameters; + const account = callRequest.account ? parseAccount(callRequest.account) : client.account; + const calldata = encodeFunctionData({ abi: abi4, args, functionName }); + try { + const { data } = await getAction(client, call, "call")({ + batch: false, + data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, + to: address, + ...callRequest, + account + }); + const result = decodeFunctionResult({ + abi: abi4, + args, + functionName, + data: data || "0x" + }); + const minimizedAbi = abi4.filter((abiItem) => "name" in abiItem && abiItem.name === parameters.functionName); + return { + result, + request: { + abi: minimizedAbi, + address, + args, + dataSuffix, + functionName, + ...callRequest, + account } - ], - stateMutability: "nonpayable", - type: "function" - }, - { - stateMutability: "payable", - type: "receive" + }; + } catch (error) { + throw getContractError(error, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/simulateContract", + functionName, + sender: account?.address + }); } -]; +} + +// node_modules/viem/_esm/actions/public/watchContractEvent.js +init_abi(); +init_rpc(); + +// node_modules/viem/_esm/utils/observe.js +var listenersCache = /* @__PURE__ */ new Map(); +var cleanupCache = /* @__PURE__ */ new Map(); +var callbackCount = 0; +function observe(observerId, callbacks, fn2) { + const callbackId = ++callbackCount; + const getListeners = () => listenersCache.get(observerId) || []; + const unsubscribe = () => { + const listeners2 = getListeners(); + listenersCache.set(observerId, listeners2.filter((cb) => cb.id !== callbackId)); + }; + const unwatch = () => { + const listeners2 = getListeners(); + if (!listeners2.some((cb) => cb.id === callbackId)) + return; + const cleanup2 = cleanupCache.get(observerId); + if (listeners2.length === 1 && cleanup2) + cleanup2(); + unsubscribe(); + }; + const listeners = getListeners(); + listenersCache.set(observerId, [ + ...listeners, + { id: callbackId, fns: callbacks } + ]); + if (listeners && listeners.length > 0) + return unwatch; + const emit = {}; + for (const key in callbacks) { + emit[key] = (...args) => { + const listeners2 = getListeners(); + if (listeners2.length === 0) + return; + for (const listener of listeners2) + listener.fns[key]?.(...args); + }; + } + const cleanup = fn2(emit); + if (typeof cleanup === "function") + cleanupCache.set(observerId, cleanup); + return unwatch; +} + +// node_modules/viem/_esm/utils/wait.js +async function wait(time) { + return new Promise((res) => setTimeout(res, time)); +} + +// node_modules/viem/_esm/utils/poll.js +function poll(fn2, { emitOnBegin, initialWaitTime, interval }) { + let active = true; + const unwatch = () => active = false; + const watch = async () => { + let data = void 0; + if (emitOnBegin) + data = await fn2({ unpoll: unwatch }); + const initialWait = await initialWaitTime?.(data) ?? interval; + await wait(initialWait); + const poll2 = async () => { + if (!active) + return; + await fn2({ unpoll: unwatch }); + await wait(interval); + poll2(); + }; + poll2(); + }; + watch(); + return unwatch; +} + +// node_modules/viem/_esm/actions/public/watchContractEvent.js +init_stringify(); + +// node_modules/viem/_esm/utils/promise/withCache.js +var promiseCache = /* @__PURE__ */ new Map(); +var responseCache = /* @__PURE__ */ new Map(); +function getCache(cacheKey2) { + const buildCache = (cacheKey3, cache) => ({ + clear: () => cache.delete(cacheKey3), + get: () => cache.get(cacheKey3), + set: (data) => cache.set(cacheKey3, data) + }); + const promise = buildCache(cacheKey2, promiseCache); + const response = buildCache(cacheKey2, responseCache); + return { + clear: () => { + promise.clear(); + response.clear(); + }, + promise, + response + }; +} +async function withCache(fn2, { cacheKey: cacheKey2, cacheTime = Number.POSITIVE_INFINITY }) { + const cache = getCache(cacheKey2); + const response = cache.response.get(); + if (response && cacheTime > 0) { + const age = (/* @__PURE__ */ new Date()).getTime() - response.created.getTime(); + if (age < cacheTime) + return response.data; + } + let promise = cache.promise.get(); + if (!promise) { + promise = fn2(); + cache.promise.set(promise); + } + try { + const data = await promise; + cache.response.set({ created: /* @__PURE__ */ new Date(), data }); + return data; + } finally { + cache.promise.clear(); + } +} + +// node_modules/viem/_esm/actions/public/getBlockNumber.js +var cacheKey = (id2) => `blockNumber.${id2}`; +async function getBlockNumber(client, { cacheTime = client.cacheTime } = {}) { + const blockNumberHex = await withCache(() => client.request({ + method: "eth_blockNumber" + }), { cacheKey: cacheKey(client.uid), cacheTime }); + return BigInt(blockNumberHex); +} + +// node_modules/viem/_esm/actions/public/getFilterChanges.js +async function getFilterChanges(_client, { filter: filter2 }) { + const strict = "strict" in filter2 && filter2.strict; + const logs = await filter2.request({ + method: "eth_getFilterChanges", + params: [filter2.id] + }); + if (typeof logs[0] === "string") + return logs; + const formattedLogs = logs.map((log) => formatLog(log)); + if (!("abi" in filter2) || !filter2.abi) + return formattedLogs; + return parseEventLogs({ + abi: filter2.abi, + logs: formattedLogs, + strict + }); +} + +// node_modules/viem/_esm/actions/public/uninstallFilter.js +async function uninstallFilter(_client, { filter: filter2 }) { + return filter2.request({ + method: "eth_uninstallFilter", + params: [filter2.id] + }); +} + +// node_modules/viem/_esm/actions/public/watchContractEvent.js +function watchContractEvent(client, parameters) { + const { abi: abi4, address, args, batch = true, eventName, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ } = parameters; + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (typeof fromBlock === "bigint") + return true; + if (client.transport.type === "webSocket") + return false; + if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + const pollContractEvent = () => { + const strict = strict_ ?? false; + const observerId = stringify([ + "watchContractEvent", + address, + args, + batch, + client.uid, + eventName, + pollingInterval, + strict, + fromBlock + ]); + return observe(observerId, { onLogs, onError }, (emit) => { + let previousBlockNumber; + if (fromBlock !== void 0) + previousBlockNumber = fromBlock - 1n; + let filter2; + let initialized = false; + const unwatch = poll(async () => { + if (!initialized) { + try { + filter2 = await getAction(client, createContractEventFilter, "createContractEventFilter")({ + abi: abi4, + address, + args, + eventName, + strict, + fromBlock + }); + } catch { + } + initialized = true; + return; + } + try { + let logs; + if (filter2) { + logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter: filter2 }); + } else { + const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({}); + if (previousBlockNumber && previousBlockNumber < blockNumber) { + logs = await getAction(client, getContractEvents, "getContractEvents")({ + abi: abi4, + address, + args, + eventName, + fromBlock: previousBlockNumber + 1n, + toBlock: blockNumber, + strict + }); + } else { + logs = []; + } + previousBlockNumber = blockNumber; + } + if (logs.length === 0) + return; + if (batch) + emit.onLogs(logs); + else + for (const log of logs) + emit.onLogs([log]); + } catch (err) { + if (filter2 && err instanceof InvalidInputRpcError) + initialized = false; + emit.onError?.(err); + } + }, { + emitOnBegin: true, + interval: pollingInterval + }); + return async () => { + if (filter2) + await getAction(client, uninstallFilter, "uninstallFilter")({ filter: filter2 }); + unwatch(); + }; + }); + }; + const subscribeContractEvent = () => { + const strict = strict_ ?? false; + const observerId = stringify([ + "watchContractEvent", + address, + args, + batch, + client.uid, + eventName, + pollingInterval, + strict + ]); + let active = true; + let unsubscribe = () => active = false; + return observe(observerId, { onLogs, onError }, (emit) => { + ; + (async () => { + try { + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const topics = eventName ? encodeEventTopics({ + abi: abi4, + eventName, + args + }) : []; + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["logs", { address, topics }], + onData(data) { + if (!active) + return; + const log = data.result; + try { + const { eventName: eventName2, args: args2 } = decodeEventLog({ + abi: abi4, + data: log.data, + topics: log.topics, + strict: strict_ + }); + const formatted = formatLog(log, { + args: args2, + eventName: eventName2 + }); + emit.onLogs([formatted]); + } catch (err) { + let eventName2; + let isUnnamed; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict_) + return; + eventName2 = err.abiItem.name; + isUnnamed = err.abiItem.inputs?.some((x2) => !("name" in x2 && x2.name)); + } + const formatted = formatLog(log, { + args: isUnnamed ? [] : {}, + eventName: eventName2 + }); + emit.onLogs([formatted]); + } + }, + onError(error) { + emit.onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }); + }; + return enablePolling ? pollContractEvent() : subscribeContractEvent(); +} -// src/common/utils/AppError.ts -var AppError = class extends Error { - isOperational; - constructor(errorType, originalError) { - const { message, isOperational } = appErrors[errorType]; - super(originalError ? `${message}: ${originalError.message}` : message); - Object.setPrototypeOf(this, new.target.prototype); - this.name = this.constructor.name; - this.isOperational = isOperational; - this.stack = originalError?.stack; - this.logError(); +// node_modules/viem/_esm/actions/wallet/writeContract.js +init_parseAccount(); + +// node_modules/viem/_esm/errors/account.js +init_base(); +var AccountNotFoundError = class extends BaseError2 { + constructor({ docsPath: docsPath6 } = {}) { + super([ + "Could not find an Account to execute with this Action.", + "Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client." + ].join("\n"), { + docsPath: docsPath6, + docsSlug: "account", + name: "AccountNotFoundError" + }); } - logError() { - console.error({ - name: this.name, - message: this.message, - stack: this.stack, - isOperational: this.isOperational +}; +var AccountTypeNotSupportedError = class extends BaseError2 { + constructor({ docsPath: docsPath6, metaMessages, type }) { + super(`Account type "${type}" is not supported.`, { + docsPath: docsPath6, + metaMessages, + name: "AccountTypeNotSupportedError" }); - if (!this.isOperational) { - process.exit(1); - } } }; -// src/common/utils/logger.ts -var import_winston = __toESM(require_winston(), 1); -var import_winston_daily_rotate_file = __toESM(require_winston_daily_rotate_file(), 1); +// node_modules/viem/_esm/actions/wallet/writeContract.js +init_encodeFunctionData(); -// src/common/managers/ManagerBase.ts -var ManagerBase = class { - initialized = false; - async initialize() { - if (this.initialized) { - return; +// node_modules/viem/_esm/actions/wallet/sendTransaction.js +init_parseAccount(); +init_base(); + +// node_modules/viem/_esm/utils/chain/assertCurrentChain.js +init_chain(); +function assertCurrentChain({ chain, currentChainId }) { + if (!chain) + throw new ChainNotFoundError(); + if (currentChainId !== chain.id) + throw new ChainMismatchError({ chain, currentChainId }); +} + +// node_modules/viem/_esm/utils/errors/getTransactionError.js +init_node(); +init_transaction(); +init_getNodeError(); +function getTransactionError(err, { docsPath: docsPath6, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new TransactionExecutionError(cause, { + docsPath: docsPath6, + ...args + }); +} + +// node_modules/viem/_esm/actions/wallet/sendTransaction.js +init_extract(); +init_transactionRequest(); +init_lru(); +init_assertRequest(); + +// node_modules/viem/_esm/actions/wallet/sendRawTransaction.js +async function sendRawTransaction(client, { serializedTransaction }) { + return client.request({ + method: "eth_sendRawTransaction", + params: [serializedTransaction] + }, { retryCount: 0 }); +} + +// node_modules/viem/_esm/actions/wallet/sendTransaction.js +var supportsWalletNamespace = new LruMap(128); +async function sendTransaction(client, parameters) { + const { account: account_ = client.account, chain = client.chain, accessList, authorizationList, blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, ...rest } = parameters; + if (typeof account_ === "undefined") + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/sendTransaction" + }); + const account = account_ ? parseAccount(account_) : null; + try { + assertRequest(parameters); + const to2 = await (async () => { + if (parameters.to) + return parameters.to; + if (parameters.to === null) + return void 0; + if (authorizationList && authorizationList.length > 0) + return await recoverAuthorizationAddress({ + authorization: authorizationList[0] + }).catch(() => { + throw new BaseError2("`to` is required. Could not infer from `authorizationList`."); + }); + return void 0; + })(); + if (account?.type === "json-rpc" || account === null) { + let chainId; + if (chain !== null) { + chainId = await getAction(client, getChainId, "getChainId")({}); + assertCurrentChain({ + currentChainId: chainId, + chain + }); + } + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format = chainFormat || formatTransactionRequest; + const request = format({ + // Pick out extra data that might exist on the chain's transaction request type. + ...extract(rest, { format: chainFormat }), + accessList, + authorizationList, + blobs, + chainId, + data, + from: account?.address, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to: to2, + value + }); + const isWalletNamespaceSupported = supportsWalletNamespace.get(client.uid); + const method = isWalletNamespaceSupported ? "wallet_sendTransaction" : "eth_sendTransaction"; + try { + return await client.request({ + method, + params: [request] + }, { retryCount: 0 }); + } catch (e) { + if (isWalletNamespaceSupported === false) + throw e; + const error = e; + if (error.name === "InvalidInputRpcError" || error.name === "InvalidParamsRpcError" || error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError") { + return await client.request({ + method: "wallet_sendTransaction", + params: [request] + }, { retryCount: 0 }).then((hash2) => { + supportsWalletNamespace.set(client.uid, true); + return hash2; + }).catch((e2) => { + const walletNamespaceError = e2; + if (walletNamespaceError.name === "MethodNotFoundRpcError" || walletNamespaceError.name === "MethodNotSupportedRpcError") { + supportsWalletNamespace.set(client.uid, false); + throw error; + } + throw walletNamespaceError; + }); + } + throw error; + } } - try { - this.initialized = true; - } catch (error) { - throw error; + if (account?.type === "local") { + const request = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({ + account, + accessList, + authorizationList, + blobs, + chain, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + nonceManager: account.nonceManager, + parameters: [...defaultParameters, "sidecars"], + value, + ...rest, + to: to2 + }); + const serializer = chain?.serializers?.transaction; + const serializedTransaction = await account.signTransaction(request, { + serializer + }); + return await getAction(client, sendRawTransaction, "sendRawTransaction")({ + serializedTransaction + }); } + if (account?.type === "smart") + throw new AccountTypeNotSupportedError({ + metaMessages: [ + "Consider using the `sendUserOperation` Action instead." + ], + docsPath: "/docs/actions/bundler/sendUserOperation", + type: "smart" + }); + throw new AccountTypeNotSupportedError({ + docsPath: "/docs/actions/wallet/sendTransaction", + type: account?.type + }); + } catch (err) { + if (err instanceof AccountTypeNotSupportedError) + throw err; + throw getTransactionError(err, { + ...parameters, + account, + chain: parameters.chain || void 0 + }); } - dispose() { - this.initialized = false; - } -}; +} -// src/common/utils/logger.ts -var Logger = class _Logger extends ManagerBase { - static instance; - baseLogger; - consumerLoggers = /* @__PURE__ */ new Map(); - constructor() { - super(); - this.baseLogger = this.createBaseLogger(); - } - static createInstance() { - if (!_Logger.instance) { - _Logger.instance = new _Logger(); - } - return _Logger.instance; +// node_modules/viem/_esm/actions/wallet/writeContract.js +async function writeContract(client, parameters) { + const { abi: abi4, account: account_ = client.account, address, args, dataSuffix, functionName, ...request } = parameters; + if (typeof account_ === "undefined") + throw new AccountNotFoundError({ + docsPath: "/docs/contract/writeContract" + }); + const account = account_ ? parseAccount(account_) : null; + const data = encodeFunctionData({ + abi: abi4, + args, + functionName + }); + try { + return await getAction(client, sendTransaction, "sendTransaction")({ + data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, + to: address, + account, + ...request + }); + } catch (error) { + throw getContractError(error, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/writeContract", + functionName, + sender: account?.address + }); } - static getInstance() { - if (!_Logger.instance) { - throw new Error("Logger is not initialized. Call createInstance() first."); - } - return _Logger.instance; +} + +// node_modules/viem/_esm/errors/eip712.js +init_base(); +var Eip712DomainNotFoundError = class extends BaseError2 { + constructor({ address }) { + super(`No EIP-712 domain found on contract "${address}".`, { + metaMessages: [ + "Ensure that:", + `- The contract is deployed at the address "${address}".`, + "- `eip712Domain()` function exists on the contract.", + "- `eip712Domain()` function matches signature to ERC-5267 specification." + ], + name: "Eip712DomainNotFoundError" + }); } - createBaseLogger() { - const logFormat = import_winston.default.format.combine( - import_winston.default.format.colorize({ level: true }), - import_winston.default.format.timestamp({ - format: "MM-DD HH:mm:ss" - }), - import_winston.default.format.printf(({ level, message, timestamp, consumer, ...meta }) => { - const prefix = consumer ? `${consumer}` : ""; - const formattedMessage = typeof message === "object" ? JSON.stringify(message, null, 2) : message; - const formattedMeta = meta && Object.keys(meta).length ? JSON.stringify(meta, null, 2) : ""; - return `${timestamp} ${level} ${prefix}: ${formattedMessage} ${formattedMeta}`.trim(); - }) - ); - const logger = import_winston.default.createLogger({ - level: "debug", - // Allow all logs through at base logger level - format: import_winston.default.format.json(), - transports: [ - new import_winston_daily_rotate_file.default({ - level: "debug", - dirname: globalConfig.LOGGER.LOG_DIR, - filename: "log-%DATE%.log", - datePattern: "YYYY-MM-DD", - maxSize: globalConfig.LOGGER.LOG_MAX_SIZE, - maxFiles: globalConfig.LOGGER.LOG_MAX_FILES - }), - new import_winston_daily_rotate_file.default({ - level: "error", - dirname: globalConfig.LOGGER.LOG_DIR, - filename: "error-%DATE%.log", - datePattern: "YYYY-MM-DD", - maxSize: globalConfig.LOGGER.LOG_MAX_SIZE, - maxFiles: globalConfig.LOGGER.LOG_MAX_FILES - }) - ] +}; + +// node_modules/viem/_esm/actions/public/getEip712Domain.js +async function getEip712Domain(client, parameters) { + const { address, factory, factoryData } = parameters; + try { + const [fields, name, version4, chainId, verifyingContract, salt, extensions] = await getAction(client, readContract, "readContract")({ + abi: abi3, + address, + functionName: "eip712Domain", + factory, + factoryData }); - if (process.env.NODE_ENV !== "production") { - logger.add( - new import_winston.default.transports.Console({ - level: "debug", - format: logFormat - }) - ); + return { + domain: { + name, + version: version4, + chainId: Number(chainId), + verifyingContract, + salt + }, + extensions, + fields + }; + } catch (e) { + const error = e; + if (error.name === "ContractFunctionExecutionError" && error.cause.name === "ContractFunctionZeroDataError") { + throw new Eip712DomainNotFoundError({ address }); } - return logger; + throw error; } - async initialize() { - if (this.initialized) return; - super.initialize(); - this.getLogger("Logger").info("Initialized"); +} +var abi3 = [ + { + inputs: [], + name: "eip712Domain", + outputs: [ + { name: "fields", type: "bytes1" }, + { name: "name", type: "string" }, + { name: "version", type: "string" }, + { name: "chainId", type: "uint256" }, + { name: "verifyingContract", type: "address" }, + { name: "salt", type: "bytes32" }, + { name: "extensions", type: "uint256[]" } + ], + stateMutability: "view", + type: "function" } - getLogger(consumerName) { - const cacheKey2 = consumerName || "__default__"; - if (this.consumerLoggers.has(cacheKey2)) { - return this.consumerLoggers.get(cacheKey2); +]; + +// node_modules/viem/_esm/actions/wallet/addChain.js +init_toHex(); +async function addChain(client, { chain }) { + const { id: id2, name, nativeCurrency, rpcUrls, blockExplorers } = chain; + await client.request({ + method: "wallet_addEthereumChain", + params: [ + { + chainId: numberToHex(id2), + chainName: name, + nativeCurrency, + rpcUrls: rpcUrls.default.http, + blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url: url2 }) => url2) : void 0 + } + ] + }, { dedupe: true, retryCount: 0 }); +} + +// node_modules/viem/_esm/clients/createClient.js +init_parseAccount(); + +// node_modules/viem/_esm/utils/uid.js +var size2 = 256; +var index = size2; +var buffer; +function uid(length = 11) { + if (!buffer || index + length > size2 * 2) { + buffer = ""; + index = 0; + for (let i = 0; i < size2; i++) { + buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1); } - const logger = this.createConsumerLogger(consumerName); - this.consumerLoggers.set(cacheKey2, logger); - return logger; } - createConsumerLogger(consumerName) { - const getLogLevel = () => { - if (!consumerName) { - return globalConfig.LOGGER.LOG_LEVEL_DEFAULT; - } - return globalConfig.LOGGER.LOG_LEVELS_GRANULAR[consumerName] || globalConfig.LOGGER.LOG_LEVEL_DEFAULT; + return buffer.substring(index, index++ + length); +} + +// node_modules/viem/_esm/clients/createClient.js +function createClient(parameters) { + const { batch, cacheTime = parameters.pollingInterval ?? 4e3, ccipRead, key = "base", name = "Base Client", pollingInterval = 4e3, type = "base" } = parameters; + const chain = parameters.chain; + const account = parameters.account ? parseAccount(parameters.account) : void 0; + const { config: config3, request, value } = parameters.transport({ + chain, + pollingInterval + }); + const transport = { ...config3, ...value }; + const client = { + account, + batch, + cacheTime, + ccipRead, + chain, + key, + name, + pollingInterval, + request, + transport, + type, + uid: uid() + }; + function extend2(base) { + return (extendFn) => { + const extended = extendFn(base); + for (const key2 in client) + delete extended[key2]; + const combined = { ...base, ...extended }; + return Object.assign(combined, { extend: extend2(combined) }); }; - const logLevelValue = { - error: 0, - warn: 1, - info: 2, - debug: 3 + } + return Object.assign(client, { extend: extend2(client) }); +} + +// node_modules/viem/_esm/utils/buildRequest.js +init_base(); +init_request(); +init_rpc(); +init_toHex(); + +// node_modules/viem/_esm/utils/promise/withDedupe.js +init_lru(); +var promiseCache2 = /* @__PURE__ */ new LruMap(8192); +function withDedupe(fn2, { enabled = true, id: id2 }) { + if (!enabled || !id2) + return fn2(); + if (promiseCache2.get(id2)) + return promiseCache2.get(id2); + const promise = fn2().finally(() => promiseCache2.delete(id2)); + promiseCache2.set(id2, promise); + return promise; +} + +// node_modules/viem/_esm/utils/promise/withRetry.js +function withRetry(fn2, { delay: delay_ = 100, retryCount = 2, shouldRetry: shouldRetry2 = () => true } = {}) { + return new Promise((resolve, reject) => { + const attemptRetry = async ({ count = 0 } = {}) => { + const retry = async ({ error }) => { + const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_; + if (delay) + await wait(delay); + attemptRetry({ count: count + 1 }); + }; + try { + const data = await fn2(); + resolve(data); + } catch (err) { + if (count < retryCount && await shouldRetry2({ count, error: err })) + return retry({ error: err }); + reject(err); + } }; - const shouldLog = (messageLevel) => { - const configuredLevel = getLogLevel(); - const configLevelValue = logLevelValue[configuredLevel] || 2; - const messageLevelValue = logLevelValue[messageLevel] || 0; - return messageLevelValue <= configLevelValue; + attemptRetry(); + }); +} + +// node_modules/viem/_esm/utils/buildRequest.js +init_stringify(); +function buildRequest(request, options = {}) { + return async (args, overrideOptions = {}) => { + const { dedupe = false, methods, retryDelay = 150, retryCount = 3, uid: uid2 } = { + ...options, + ...overrideOptions }; - const logLevel = getLogLevel(); - return { - error: (message, ...meta) => { - this.baseLogger.error( - message, - consumerName ? { consumer: consumerName, ...meta } : meta - ); - }, - warn: (message, ...meta) => { - if (shouldLog("warn")) { - this.baseLogger.warn( - message, - consumerName ? { consumer: consumerName, ...meta } : meta - ); + const { method } = args; + if (methods?.exclude?.includes(method)) + throw new MethodNotSupportedRpcError(new Error("method not supported"), { + method + }); + if (methods?.include && !methods.include.includes(method)) + throw new MethodNotSupportedRpcError(new Error("method not supported"), { + method + }); + const requestId = dedupe ? stringToHex(`${uid2}.${stringify(args)}`) : void 0; + return withDedupe(() => withRetry(async () => { + try { + return await request(args); + } catch (err_) { + const err = err_; + switch (err.code) { + // -32700 + case ParseRpcError.code: + throw new ParseRpcError(err); + // -32600 + case InvalidRequestRpcError.code: + throw new InvalidRequestRpcError(err); + // -32601 + case MethodNotFoundRpcError.code: + throw new MethodNotFoundRpcError(err, { method: args.method }); + // -32602 + case InvalidParamsRpcError.code: + throw new InvalidParamsRpcError(err); + // -32603 + case InternalRpcError.code: + throw new InternalRpcError(err); + // -32000 + case InvalidInputRpcError.code: + throw new InvalidInputRpcError(err); + // -32001 + case ResourceNotFoundRpcError.code: + throw new ResourceNotFoundRpcError(err); + // -32002 + case ResourceUnavailableRpcError.code: + throw new ResourceUnavailableRpcError(err); + // -32003 + case TransactionRejectedRpcError.code: + throw new TransactionRejectedRpcError(err); + // -32004 + case MethodNotSupportedRpcError.code: + throw new MethodNotSupportedRpcError(err, { + method: args.method + }); + // -32005 + case LimitExceededRpcError.code: + throw new LimitExceededRpcError(err); + // -32006 + case JsonRpcVersionUnsupportedError.code: + throw new JsonRpcVersionUnsupportedError(err); + // 4001 + case UserRejectedRequestError.code: + throw new UserRejectedRequestError(err); + // 4100 + case UnauthorizedProviderError.code: + throw new UnauthorizedProviderError(err); + // 4200 + case UnsupportedProviderMethodError.code: + throw new UnsupportedProviderMethodError(err); + // 4900 + case ProviderDisconnectedError.code: + throw new ProviderDisconnectedError(err); + // 4901 + case ChainDisconnectedError.code: + throw new ChainDisconnectedError(err); + // 4902 + case SwitchChainError.code: + throw new SwitchChainError(err); + // CAIP-25: User Rejected Error + // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25 + case 5e3: + throw new UserRejectedRequestError(err); + default: + if (err_ instanceof BaseError2) + throw err_; + throw new UnknownRpcError(err); } - }, - info: (message, ...meta) => { - if (shouldLog("info")) { - this.baseLogger.info( - message, - consumerName ? { consumer: consumerName, ...meta } : meta - ); + } + }, { + delay: ({ count, error }) => { + if (error && error instanceof HttpRequestError) { + const retryAfter = error?.headers?.get("Retry-After"); + if (retryAfter?.match(/\d/)) + return Number.parseInt(retryAfter) * 1e3; } + return ~~(1 << count) * retryDelay; }, - debug: (message, ...meta) => { - if (shouldLog("debug")) { - this.baseLogger.debug( - message, - consumerName ? { consumer: consumerName, ...meta } : meta - ); - } - } - }; + retryCount, + shouldRetry: ({ error }) => shouldRetry(error) + }), { enabled: dedupe, id: requestId }); + }; +} +function shouldRetry(error) { + if ("code" in error && typeof error.code === "number") { + if (error.code === -1) + return true; + if (error.code === LimitExceededRpcError.code) + return true; + if (error.code === InternalRpcError.code) + return true; + return false; } - dispose() { - this.consumerLoggers.clear(); - super.dispose(); + if (error instanceof HttpRequestError && error.status) { + if (error.status === 403) + return true; + if (error.status === 408) + return true; + if (error.status === 413) + return true; + if (error.status === 429) + return true; + if (error.status === 500) + return true; + if (error.status === 502) + return true; + if (error.status === 503) + return true; + if (error.status === 504) + return true; + return false; } -}; + return true; +} -// src/common/utils/sleep.ts -async function sleep(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); +// node_modules/viem/_esm/clients/transports/createTransport.js +function createTransport({ key, methods, name, request, retryCount = 3, retryDelay = 150, timeout, type }, value) { + const uid2 = uid(); + return { + config: { + key, + methods, + name, + request, + retryCount, + retryDelay, + timeout, + type + }, + request: buildRequest(request, { methods, retryCount, retryDelay, uid: uid2 }), + value + }; } -// src/common/utils/asyncRetry.ts -async function asyncRetry(fn2, options = {}) { - const { maxRetries = 3, delayMs = 2e3, isRetryableError = () => false } = options; - const logger = Logger.getInstance().getLogger("AsyncRetry"); - let attempt = 0; - let lastError; - while (attempt <= maxRetries) { - try { - return await fn2(); - } catch (error) { - lastError = error; - if (await isRetryableError(error) && attempt < maxRetries) { - ++attempt; - logger.debug(`Retry attempt ${attempt} failed. Retrying in ${delayMs}ms...`); - await sleep(delayMs); - } else { - throw error; - } +// node_modules/viem/_esm/clients/transports/fallback.js +init_node(); +init_rpc(); +function fallback(transports_, config3 = {}) { + const { key = "fallback", name = "Fallback", rank = false, shouldThrow: shouldThrow_ = shouldThrow, retryCount, retryDelay } = config3; + return ({ chain, pollingInterval = 4e3, timeout, ...rest }) => { + let transports = transports_; + let onResponse = () => { + }; + const transport = createTransport({ + key, + name, + async request({ method, params }) { + let includes; + const fetch2 = async (i = 0) => { + const transport2 = transports[i]({ + ...rest, + chain, + retryCount: 0, + timeout + }); + try { + const response = await transport2.request({ + method, + params + }); + onResponse({ + method, + params, + response, + transport: transport2, + status: "success" + }); + return response; + } catch (err) { + onResponse({ + error: err, + method, + params, + transport: transport2, + status: "error" + }); + if (shouldThrow_(err)) + throw err; + if (i === transports.length - 1) + throw err; + includes ??= transports.slice(i + 1).some((transport3) => { + const { include, exclude } = transport3({ chain }).config.methods || {}; + if (include) + return include.includes(method); + if (exclude) + return !exclude.includes(method); + return true; + }); + if (!includes) + throw err; + return fetch2(i + 1); + } + }; + return fetch2(); + }, + retryCount, + retryDelay, + type: "fallback" + }, { + onResponse: (fn2) => onResponse = fn2, + transports: transports.map((fn2) => fn2({ chain, retryCount: 0 })) + }); + if (rank) { + const rankOptions = typeof rank === "object" ? rank : {}; + rankTransports({ + chain, + interval: rankOptions.interval ?? pollingInterval, + onTransports: (transports_2) => transports = transports_2, + ping: rankOptions.ping, + sampleCount: rankOptions.sampleCount, + timeout: rankOptions.timeout, + transports, + weights: rankOptions.weights + }); } + return transport; + }; +} +function shouldThrow(error) { + if ("code" in error && typeof error.code === "number") { + if (error.code === TransactionRejectedRpcError.code || error.code === UserRejectedRequestError.code || ExecutionRevertedError.nodeMessage.test(error.message) || error.code === 5e3) + return true; } - throw lastError; + return false; +} +function rankTransports({ chain, interval = 4e3, onTransports, ping, sampleCount = 10, timeout = 1e3, transports, weights = {} }) { + const { stability: stabilityWeight = 0.7, latency: latencyWeight = 0.3 } = weights; + const samples = []; + const rankTransports_ = async () => { + const sample = await Promise.all(transports.map(async (transport) => { + const transport_ = transport({ chain, retryCount: 0, timeout }); + const start = Date.now(); + let end; + let success; + try { + await (ping ? ping({ transport: transport_ }) : transport_.request({ method: "net_listening" })); + success = 1; + } catch { + success = 0; + } finally { + end = Date.now(); + } + const latency = end - start; + return { latency, success }; + })); + samples.push(sample); + if (samples.length > sampleCount) + samples.shift(); + const maxLatency = Math.max(...samples.map((sample2) => Math.max(...sample2.map(({ latency }) => latency)))); + const scores = transports.map((_, i) => { + const latencies = samples.map((sample2) => sample2[i].latency); + const meanLatency = latencies.reduce((acc, latency) => acc + latency, 0) / latencies.length; + const latencyScore = 1 - meanLatency / maxLatency; + const successes = samples.map((sample2) => sample2[i].success); + const stabilityScore = successes.reduce((acc, success) => acc + success, 0) / successes.length; + if (stabilityScore === 0) + return [0, i]; + return [ + latencyWeight * latencyScore + stabilityWeight * stabilityScore, + i + ]; + }).sort((a, b2) => b2[0] - a[0]); + onTransports(scores.map(([, i]) => transports[i])); + await wait(interval); + rankTransports_(); + }; + rankTransports_(); +} + +// node_modules/viem/_esm/clients/transports/http.js +init_request(); + +// node_modules/viem/_esm/errors/transport.js +init_base(); +var UrlRequiredError = class extends BaseError2 { + constructor() { + super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.", { + docsPath: "/docs/clients/intro", + name: "UrlRequiredError" + }); + } +}; + +// node_modules/viem/_esm/clients/transports/http.js +init_createBatchScheduler(); + +// node_modules/viem/_esm/utils/rpc/http.js +init_request(); + +// node_modules/viem/_esm/utils/promise/withTimeout.js +function withTimeout(fn2, { errorInstance = new Error("timed out"), timeout, signal }) { + return new Promise((resolve, reject) => { + ; + (async () => { + let timeoutId; + try { + const controller = new AbortController(); + if (timeout > 0) { + timeoutId = setTimeout(() => { + if (signal) { + controller.abort(); + } else { + reject(errorInstance); + } + }, timeout); + } + resolve(await fn2({ signal: controller?.signal || null })); + } catch (err) { + if (err?.name === "AbortError") + reject(errorInstance); + reject(err); + } finally { + clearTimeout(timeoutId); + } + })(); + }); } -// node_modules/viem/_esm/index.js -init_exports(); +// node_modules/viem/_esm/utils/rpc/http.js +init_stringify(); -// node_modules/viem/_esm/utils/getAction.js -function getAction(client, actionFn, name) { - const action_implicit = client[actionFn.name]; - if (typeof action_implicit === "function") - return action_implicit; - const action_explicit = client[name]; - if (typeof action_explicit === "function") - return action_explicit; - return (params) => actionFn(client, params); +// node_modules/viem/_esm/utils/rpc/id.js +function createIdStore() { + return { + current: 0, + take() { + return this.current++; + }, + reset() { + this.current = 0; + } + }; } +var idCache = /* @__PURE__ */ createIdStore(); -// node_modules/viem/_esm/utils/abi/encodeEventTopics.js -init_abi(); - -// node_modules/viem/_esm/errors/log.js -init_base(); -var FilterTypeNotSupportedError = class extends BaseError2 { - constructor(type) { - super(`Filter type "${type}" is not supported.`, { - name: "FilterTypeNotSupportedError" - }); - } -}; - -// node_modules/viem/_esm/utils/abi/encodeEventTopics.js -init_toBytes(); -init_keccak256(); -init_toEventSelector(); -init_encodeAbiParameters(); -init_formatAbiItem2(); -init_getAbiItem(); -var docsPath = "/docs/contract/encodeEventTopics"; -function encodeEventTopics(parameters) { - const { abi: abi4, eventName, args } = parameters; - let abiItem = abi4[0]; - if (eventName) { - const item = getAbiItem({ abi: abi4, name: eventName }); - if (!item) - throw new AbiEventNotFoundError(eventName, { docsPath }); - abiItem = item; - } - if (abiItem.type !== "event") - throw new AbiEventNotFoundError(void 0, { docsPath }); - const definition = formatAbiItem2(abiItem); - const signature = toEventSelector(definition); - let topics = []; - if (args && "inputs" in abiItem) { - const indexedInputs = abiItem.inputs?.filter((param) => "indexed" in param && param.indexed); - const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? indexedInputs?.map((x2) => args[x2.name]) ?? [] : []; - if (args_.length > 0) { - topics = indexedInputs?.map((param, i) => { - if (Array.isArray(args_[i])) - return args_[i].map((_, j2) => encodeArg({ param, value: args_[i][j2] })); - return typeof args_[i] !== "undefined" && args_[i] !== null ? encodeArg({ param, value: args_[i] }) : null; - }) ?? []; +// node_modules/viem/_esm/utils/rpc/http.js +function getHttpRpcClient(url2, options = {}) { + return { + async request(params) { + const { body, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 1e4 } = params; + const fetchOptions = { + ...options.fetchOptions ?? {}, + ...params.fetchOptions ?? {} + }; + const { headers, method, signal: signal_ } = fetchOptions; + try { + const response = await withTimeout(async ({ signal }) => { + const init = { + ...fetchOptions, + body: Array.isArray(body) ? stringify(body.map((body2) => ({ + jsonrpc: "2.0", + id: body2.id ?? idCache.take(), + ...body2 + }))) : stringify({ + jsonrpc: "2.0", + id: body.id ?? idCache.take(), + ...body + }), + headers: { + "Content-Type": "application/json", + ...headers + }, + method: method || "POST", + signal: signal_ || (timeout > 0 ? signal : null) + }; + const request = new Request(url2, init); + const args = await onRequest?.(request, init) ?? { ...init, url: url2 }; + const response2 = await fetch(args.url ?? url2, args); + return response2; + }, { + errorInstance: new TimeoutError({ body, url: url2 }), + timeout, + signal: true + }); + if (onResponse) + await onResponse(response); + let data; + if (response.headers.get("Content-Type")?.startsWith("application/json")) + data = await response.json(); + else { + data = await response.text(); + try { + data = JSON.parse(data || "{}"); + } catch (err) { + if (response.ok) + throw err; + data = { error: data }; + } + } + if (!response.ok) { + throw new HttpRequestError({ + body, + details: stringify(data.error) || response.statusText, + headers: response.headers, + status: response.status, + url: url2 + }); + } + return data; + } catch (err) { + if (err instanceof HttpRequestError) + throw err; + if (err instanceof TimeoutError) + throw err; + throw new HttpRequestError({ + body, + cause: err, + url: url2 + }); + } } - } - return [signature, ...topics]; -} -function encodeArg({ param, value }) { - if (param.type === "string" || param.type === "bytes") - return keccak256(toBytes(value)); - if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) - throw new FilterTypeNotSupportedError(param.type); - return encodeAbiParameters([param], [value]); + }; } -// node_modules/viem/_esm/actions/public/createContractEventFilter.js -init_toHex(); - -// node_modules/viem/_esm/utils/filters/createFilterRequestScope.js -function createFilterRequestScope(client, { method }) { - const requestMap = {}; - if (client.transport.type === "fallback") - client.transport.onResponse?.(({ method: method_, response: id2, status, transport }) => { - if (status === "success" && method === method_) - requestMap[id2] = transport.request; +// node_modules/viem/_esm/clients/transports/http.js +function http(url2, config3 = {}) { + const { batch, fetchOptions, key = "http", methods, name = "HTTP JSON-RPC", onFetchRequest, onFetchResponse, retryDelay, raw: raw2 } = config3; + return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => { + const { batchSize = 1e3, wait: wait2 = 0 } = typeof batch === "object" ? batch : {}; + const retryCount = config3.retryCount ?? retryCount_; + const timeout = timeout_ ?? config3.timeout ?? 1e4; + const url_ = url2 || chain?.rpcUrls.default.http[0]; + if (!url_) + throw new UrlRequiredError(); + const rpcClient = getHttpRpcClient(url_, { + fetchOptions, + onRequest: onFetchRequest, + onResponse: onFetchResponse, + timeout + }); + return createTransport({ + key, + methods, + name, + async request({ method, params }) { + const body = { method, params }; + const { schedule } = createBatchScheduler({ + id: url_, + wait: wait2, + shouldSplitBatch(requests) { + return requests.length > batchSize; + }, + fn: (body2) => rpcClient.request({ + body: body2 + }), + sort: (a, b2) => a.id - b2.id + }); + const fn2 = async (body2) => batch ? schedule(body2) : [ + await rpcClient.request({ + body: body2 + }) + ]; + const [{ error, result }] = await fn2(body); + if (raw2) + return { error, result }; + if (error) + throw new RpcRequestError({ + body, + error, + url: url_ + }); + return result; + }, + retryCount, + retryDelay, + timeout, + type: "http" + }, { + fetchOptions, + url: url_ }); - return (id2) => requestMap[id2] || client.request; -} - -// node_modules/viem/_esm/actions/public/createContractEventFilter.js -async function createContractEventFilter(client, parameters) { - const { address, abi: abi4, args, eventName, fromBlock, strict, toBlock } = parameters; - const getRequest = createFilterRequestScope(client, { - method: "eth_newFilter" - }); - const topics = eventName ? encodeEventTopics({ - abi: abi4, - args, - eventName - }) : void 0; - const id2 = await client.request({ - method: "eth_newFilter", - params: [ - { - address, - fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, - toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, - topics - } - ] - }); - return { - abi: abi4, - args, - eventName, - id: id2, - request: getRequest(id2), - strict: Boolean(strict), - type: "event" }; } -// node_modules/viem/_esm/actions/public/estimateContractGas.js -init_parseAccount(); +// node_modules/viem/_esm/actions/ens/getEnsAddress.js +init_abis(); +init_decodeFunctionResult(); init_encodeFunctionData(); +init_getChainContractAddress(); +init_trim(); +init_toHex(); -// node_modules/viem/_esm/utils/errors/getContractError.js -init_abi(); +// node_modules/viem/_esm/utils/ens/errors.js +init_solidity(); init_base(); init_contract(); -init_request(); -init_rpc(); -var EXECUTION_REVERTED_ERROR_CODE = 3; -function getContractError(err, { abi: abi4, address, args, docsPath: docsPath6, functionName, sender }) { - const error = err instanceof RawContractError ? err : err instanceof BaseError2 ? err.walk((err2) => "data" in err2) || err.walk() : {}; - const { code, data, details, message, shortMessage } = error; - const cause = (() => { - if (err instanceof AbiDecodingZeroDataError) - return new ContractFunctionZeroDataError({ functionName }); - if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) && (data || details || message || shortMessage)) { - return new ContractFunctionRevertedError({ - abi: abi4, - data: typeof data === "object" ? data.data : data, - functionName, - message: error instanceof RpcRequestError ? details : shortMessage ?? message - }); - } - return err; - })(); - return new ContractFunctionExecutionError(cause, { - abi: abi4, - args, - contractAddress: address, - docsPath: docsPath6, - functionName, - sender - }); +function isNullUniversalResolverError(err, callType) { + if (!(err instanceof BaseError2)) + return false; + const cause = err.walk((e) => e instanceof ContractFunctionRevertedError); + if (!(cause instanceof ContractFunctionRevertedError)) + return false; + if (cause.data?.errorName === "ResolverNotFound") + return true; + if (cause.data?.errorName === "ResolverWildcardNotSupported") + return true; + if (cause.data?.errorName === "ResolverNotContract") + return true; + if (cause.data?.errorName === "ResolverError") + return true; + if (cause.data?.errorName === "HttpError") + return true; + if (cause.reason?.includes("Wildcard on non-extended resolvers is not supported")) + return true; + if (callType === "reverse" && cause.reason === panicReasons[50]) + return true; + return false; } -// node_modules/viem/_esm/actions/public/estimateGas.js -init_parseAccount(); -init_base(); - -// node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js -init_getAddress(); +// node_modules/viem/_esm/utils/ens/namehash.js +init_concat(); +init_toBytes(); +init_toHex(); init_keccak256(); -function publicKeyToAddress(publicKey) { - const address = keccak256(`0x${publicKey.substring(4)}`).substring(26); - return checksumAddress(`0x${address}`); -} -// node_modules/viem/_esm/utils/signature/recoverPublicKey.js +// node_modules/viem/_esm/utils/ens/encodedLabelToLabelhash.js init_isHex(); -init_fromHex(); -init_toHex(); -async function recoverPublicKey({ hash: hash2, signature }) { - const hashHex = isHex(hash2) ? hash2 : toHex(hash2); - const { secp256k1: secp256k12 } = await Promise.resolve().then(() => (init_secp256k1(), secp256k1_exports)); - const signature_ = (() => { - if (typeof signature === "object" && "r" in signature && "s" in signature) { - const { r, s, v, yParity } = signature; - const yParityOrV2 = Number(yParity ?? v); - const recoveryBit2 = toRecoveryBit(yParityOrV2); - return new secp256k12.Signature(hexToBigInt(r), hexToBigInt(s)).addRecoveryBit(recoveryBit2); - } - const signatureHex = isHex(signature) ? signature : toHex(signature); - const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`); - const recoveryBit = toRecoveryBit(yParityOrV); - return secp256k12.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit); - })(); - const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false); - return `0x${publicKey}`; -} -function toRecoveryBit(yParityOrV) { - if (yParityOrV === 0 || yParityOrV === 1) - return yParityOrV; - if (yParityOrV === 27) - return 0; - if (yParityOrV === 28) - return 1; - throw new Error("Invalid yParityOrV value"); +function encodedLabelToLabelhash(label) { + if (label.length !== 66) + return null; + if (label.indexOf("[") !== 0) + return null; + if (label.indexOf("]") !== 65) + return null; + const hash2 = `0x${label.slice(1, 65)}`; + if (!isHex(hash2)) + return null; + return hash2; } -// node_modules/viem/_esm/utils/signature/recoverAddress.js -async function recoverAddress({ hash: hash2, signature }) { - return publicKeyToAddress(await recoverPublicKey({ hash: hash2, signature })); +// node_modules/viem/_esm/utils/ens/namehash.js +function namehash(name) { + let result = new Uint8Array(32).fill(0); + if (!name) + return bytesToHex(result); + const labels = name.split("."); + for (let i = labels.length - 1; i >= 0; i -= 1) { + const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]); + const hashed = hashFromEncodedLabel ? toBytes(hashFromEncodedLabel) : keccak256(stringToBytes(labels[i]), "bytes"); + result = keccak256(concat([result, hashed]), "bytes"); + } + return bytesToHex(result); } -// node_modules/viem/_esm/utils/authorization/hashAuthorization.js -init_concat(); +// node_modules/viem/_esm/utils/ens/packetToBytes.js init_toBytes(); -init_toHex(); -// node_modules/viem/_esm/utils/encoding/toRlp.js -init_base(); -init_cursor2(); -init_toBytes(); -init_toHex(); -function toRlp(bytes, to2 = "hex") { - const encodable = getEncodable(bytes); - const cursor = createCursor(new Uint8Array(encodable.length)); - encodable.encode(cursor); - if (to2 === "hex") - return bytesToHex(cursor.bytes); - return cursor.bytes; -} -function getEncodable(bytes) { - if (Array.isArray(bytes)) - return getEncodableList(bytes.map((x2) => getEncodable(x2))); - return getEncodableBytes(bytes); -} -function getEncodableList(list) { - const bodyLength = list.reduce((acc, x2) => acc + x2.length, 0); - const sizeOfBodyLength = getSizeOfLength(bodyLength); - const length = (() => { - if (bodyLength <= 55) - return 1 + bodyLength; - return 1 + sizeOfBodyLength + bodyLength; - })(); - return { - length, - encode(cursor) { - if (bodyLength <= 55) { - cursor.pushByte(192 + bodyLength); - } else { - cursor.pushByte(192 + 55 + sizeOfBodyLength); - if (sizeOfBodyLength === 1) - cursor.pushUint8(bodyLength); - else if (sizeOfBodyLength === 2) - cursor.pushUint16(bodyLength); - else if (sizeOfBodyLength === 3) - cursor.pushUint24(bodyLength); - else - cursor.pushUint32(bodyLength); - } - for (const { encode: encode6 } of list) { - encode6(cursor); - } - } - }; -} -function getEncodableBytes(bytesOrHex) { - const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex; - const sizeOfBytesLength = getSizeOfLength(bytes.length); - const length = (() => { - if (bytes.length === 1 && bytes[0] < 128) - return 1; - if (bytes.length <= 55) - return 1 + bytes.length; - return 1 + sizeOfBytesLength + bytes.length; - })(); - return { - length, - encode(cursor) { - if (bytes.length === 1 && bytes[0] < 128) { - cursor.pushBytes(bytes); - } else if (bytes.length <= 55) { - cursor.pushByte(128 + bytes.length); - cursor.pushBytes(bytes); - } else { - cursor.pushByte(128 + 55 + sizeOfBytesLength); - if (sizeOfBytesLength === 1) - cursor.pushUint8(bytes.length); - else if (sizeOfBytesLength === 2) - cursor.pushUint16(bytes.length); - else if (sizeOfBytesLength === 3) - cursor.pushUint24(bytes.length); - else - cursor.pushUint32(bytes.length); - cursor.pushBytes(bytes); - } - } - }; -} -function getSizeOfLength(length) { - if (length < 2 ** 8) - return 1; - if (length < 2 ** 16) - return 2; - if (length < 2 ** 24) - return 3; - if (length < 2 ** 32) - return 4; - throw new BaseError2("Length is too large."); +// node_modules/viem/_esm/utils/ens/encodeLabelhash.js +function encodeLabelhash(hash2) { + return `[${hash2.slice(2)}]`; } -// node_modules/viem/_esm/utils/authorization/hashAuthorization.js +// node_modules/viem/_esm/utils/ens/labelhash.js +init_toBytes(); +init_toHex(); init_keccak256(); -function hashAuthorization(parameters) { - const { chainId, nonce, to: to2 } = parameters; - const address = parameters.contractAddress ?? parameters.address; - const hash2 = keccak256(concatHex([ - "0x05", - toRlp([ - chainId ? numberToHex(chainId) : "0x", - address, - nonce ? numberToHex(nonce) : "0x" - ]) - ])); - if (to2 === "bytes") - return hexToBytes(hash2); - return hash2; -} - -// node_modules/viem/_esm/utils/authorization/recoverAuthorizationAddress.js -async function recoverAuthorizationAddress(parameters) { - const { authorization, signature } = parameters; - return recoverAddress({ - hash: hashAuthorization(authorization), - signature: signature ?? authorization - }); +function labelhash(label) { + const result = new Uint8Array(32).fill(0); + if (!label) + return bytesToHex(result); + return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label)); } -// node_modules/viem/_esm/actions/public/estimateGas.js -init_toHex(); +// node_modules/viem/_esm/utils/ens/packetToBytes.js +function packetToBytes(packet) { + const value = packet.replace(/^\.|\.$/gm, ""); + if (value.length === 0) + return new Uint8Array(1); + const bytes = new Uint8Array(stringToBytes(value).byteLength + 2); + let offset = 0; + const list = value.split("."); + for (let i = 0; i < list.length; i++) { + let encoded = stringToBytes(list[i]); + if (encoded.byteLength > 255) + encoded = stringToBytes(encodeLabelhash(labelhash(list[i]))); + bytes[offset] = encoded.length; + bytes.set(encoded, offset + 1); + offset += encoded.length + 1; + } + if (bytes.byteLength !== offset + 1) + return bytes.slice(0, offset + 1); + return bytes; +} -// node_modules/viem/_esm/errors/estimateGas.js -init_formatEther(); -init_formatGwei(); -init_base(); -init_transaction(); -var EstimateGasExecutionError = class extends BaseError2 { - constructor(cause, { account, docsPath: docsPath6, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to: to2, value }) { - const prettyArgs = prettyPrint({ - from: account?.address, - to: to2, - value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, - data, - gas, - gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`, - maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`, - maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`, - nonce +// node_modules/viem/_esm/actions/ens/getEnsAddress.js +async function getEnsAddress(client, { blockNumber, blockTag, coinType, name, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "ensUniversalResolver" }); - super(cause.shortMessage, { - cause, - docsPath: docsPath6, - metaMessages: [ - ...cause.metaMessages ? [...cause.metaMessages, " "] : [], - "Estimate Gas Arguments:", - prettyArgs - ].filter(Boolean), - name: "EstimateGasExecutionError" + } + try { + const functionData = encodeFunctionData({ + abi: addressResolverAbi, + functionName: "addr", + ...coinType != null ? { args: [namehash(name), BigInt(coinType)] } : { args: [namehash(name)] } }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverResolveAbi, + functionName: "resolve", + args: [toHex(packetToBytes(name)), functionData], + blockNumber, + blockTag + }; + const readContractAction = getAction(client, readContract, "readContract"); + const res = gatewayUrls ? await readContractAction({ + ...readContractParameters, + args: [...readContractParameters.args, gatewayUrls] + }) : await readContractAction(readContractParameters); + if (res[0] === "0x") + return null; + const address = decodeFunctionResult({ + abi: addressResolverAbi, + args: coinType != null ? [namehash(name), BigInt(coinType)] : void 0, + functionName: "addr", + data: res[0] }); - this.cause = cause; + if (address === "0x") + return null; + if (trim(address) === "0x00") + return null; + return address; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err, "resolve")) + return null; + throw err; } -}; - -// node_modules/viem/_esm/utils/errors/getEstimateGasError.js -init_node(); -init_getNodeError(); -function getEstimateGasError(err, { docsPath: docsPath6, ...args }) { - const cause = (() => { - const cause2 = getNodeError(err, args); - if (cause2 instanceof UnknownNodeError) - return err; - return cause2; - })(); - return new EstimateGasExecutionError(cause, { - docsPath: docsPath6, - ...args - }); } -// node_modules/viem/_esm/actions/public/estimateGas.js -init_extract(); -init_transactionRequest(); -init_stateOverride2(); -init_assertRequest(); - -// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js -init_parseAccount(); - -// node_modules/viem/_esm/errors/fee.js -init_formatGwei(); +// node_modules/viem/_esm/errors/ens.js init_base(); -var BaseFeeScalarError = class extends BaseError2 { - constructor() { - super("`baseFeeMultiplier` must be greater than 1.", { - name: "BaseFeeScalarError" +var EnsAvatarInvalidMetadataError = class extends BaseError2 { + constructor({ data }) { + super("Unable to extract image from metadata. The metadata may be malformed or invalid.", { + metaMessages: [ + "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.", + "", + `Provided data: ${JSON.stringify(data)}` + ], + name: "EnsAvatarInvalidMetadataError" }); } }; -var Eip1559FeesNotSupportedError = class extends BaseError2 { - constructor() { - super("Chain does not support EIP-1559 fees.", { - name: "Eip1559FeesNotSupportedError" +var EnsAvatarInvalidNftUriError = class extends BaseError2 { + constructor({ reason }) { + super(`ENS NFT avatar URI is invalid. ${reason}`, { + name: "EnsAvatarInvalidNftUriError" }); } }; -var MaxFeePerGasTooLowError = class extends BaseError2 { - constructor({ maxPriorityFeePerGas }) { - super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" }); +var EnsAvatarUriResolutionError = class extends BaseError2 { + constructor({ uri }) { + super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`, { name: "EnsAvatarUriResolutionError" }); } }; - -// node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js -init_fromHex(); - -// node_modules/viem/_esm/errors/block.js -init_base(); -var BlockNotFoundError = class extends BaseError2 { - constructor({ blockHash, blockNumber }) { - let identifier = "Block"; - if (blockHash) - identifier = `Block at hash "${blockHash}"`; - if (blockNumber) - identifier = `Block at number "${blockNumber}"`; - super(`${identifier} could not be found.`, { name: "BlockNotFoundError" }); +var EnsAvatarUnsupportedNamespaceError = class extends BaseError2 { + constructor({ namespace }) { + super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`, { name: "EnsAvatarUnsupportedNamespaceError" }); } }; -// node_modules/viem/_esm/actions/public/getBlock.js -init_toHex(); - -// node_modules/viem/_esm/utils/formatters/transaction.js -init_fromHex(); -var transactionType = { - "0x0": "legacy", - "0x1": "eip2930", - "0x2": "eip1559", - "0x3": "eip4844", - "0x4": "eip7702" -}; -function formatTransaction(transaction) { - const transaction_ = { - ...transaction, - blockHash: transaction.blockHash ? transaction.blockHash : null, - blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null, - chainId: transaction.chainId ? hexToNumber(transaction.chainId) : void 0, - gas: transaction.gas ? BigInt(transaction.gas) : void 0, - gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0, - maxFeePerBlobGas: transaction.maxFeePerBlobGas ? BigInt(transaction.maxFeePerBlobGas) : void 0, - maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0, - maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0, - nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0, - to: transaction.to ? transaction.to : null, - transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null, - type: transaction.type ? transactionType[transaction.type] : void 0, - typeHex: transaction.type ? transaction.type : void 0, - value: transaction.value ? BigInt(transaction.value) : void 0, - v: transaction.v ? BigInt(transaction.v) : void 0 - }; - if (transaction.authorizationList) - transaction_.authorizationList = formatAuthorizationList2(transaction.authorizationList); - transaction_.yParity = (() => { - if (transaction.yParity) - return Number(transaction.yParity); - if (typeof transaction_.v === "bigint") { - if (transaction_.v === 0n || transaction_.v === 27n) - return 0; - if (transaction_.v === 1n || transaction_.v === 28n) - return 1; - if (transaction_.v >= 35n) - return transaction_.v % 2n === 0n ? 1 : 0; - } - return void 0; - })(); - if (transaction_.type === "legacy") { - delete transaction_.accessList; - delete transaction_.maxFeePerBlobGas; - delete transaction_.maxFeePerGas; - delete transaction_.maxPriorityFeePerGas; - delete transaction_.yParity; - } - if (transaction_.type === "eip2930") { - delete transaction_.maxFeePerBlobGas; - delete transaction_.maxFeePerGas; - delete transaction_.maxPriorityFeePerGas; - } - if (transaction_.type === "eip1559") { - delete transaction_.maxFeePerBlobGas; - } - return transaction_; -} -function formatAuthorizationList2(authorizationList) { - return authorizationList.map((authorization) => ({ - address: authorization.address, - chainId: Number(authorization.chainId), - nonce: Number(authorization.nonce), - r: authorization.r, - s: authorization.s, - yParity: Number(authorization.yParity) - })); -} - -// node_modules/viem/_esm/utils/formatters/block.js -function formatBlock(block) { - const transactions = (block.transactions ?? []).map((transaction) => { - if (typeof transaction === "string") - return transaction; - return formatTransaction(transaction); - }); - return { - ...block, - baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null, - blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : void 0, - difficulty: block.difficulty ? BigInt(block.difficulty) : void 0, - excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : void 0, - gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0, - gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0, - hash: block.hash ? block.hash : null, - logsBloom: block.logsBloom ? block.logsBloom : null, - nonce: block.nonce ? block.nonce : null, - number: block.number ? BigInt(block.number) : null, - size: block.size ? BigInt(block.size) : void 0, - timestamp: block.timestamp ? BigInt(block.timestamp) : void 0, - transactions, - totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null - }; -} - -// node_modules/viem/_esm/actions/public/getBlock.js -async function getBlock(client, { blockHash, blockNumber, blockTag: blockTag_, includeTransactions: includeTransactions_ } = {}) { - const blockTag = blockTag_ ?? "latest"; - const includeTransactions = includeTransactions_ ?? false; - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - let block = null; - if (blockHash) { - block = await client.request({ - method: "eth_getBlockByHash", - params: [blockHash, includeTransactions] - }, { dedupe: true }); - } else { - block = await client.request({ - method: "eth_getBlockByNumber", - params: [blockNumberHex || blockTag, includeTransactions] - }, { dedupe: Boolean(blockNumberHex) }); - } - if (!block) - throw new BlockNotFoundError({ blockHash, blockNumber }); - const format = client.chain?.formatters?.block?.format || formatBlock; - return format(block); -} - -// node_modules/viem/_esm/actions/public/getGasPrice.js -async function getGasPrice(client) { - const gasPrice = await client.request({ - method: "eth_gasPrice" - }); - return BigInt(gasPrice); -} - -// node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js -async function estimateMaxPriorityFeePerGas(client, args) { - return internal_estimateMaxPriorityFeePerGas(client, args); -} -async function internal_estimateMaxPriorityFeePerGas(client, args) { - const { block: block_, chain = client.chain, request } = args || {}; +// node_modules/viem/_esm/utils/ens/avatar/utils.js +var networkRegex = /(?https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/; +var ipfsHashRegex = /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/; +var base64Regex = /^data:([a-zA-Z\-/+]*);base64,([^"].*)/; +var dataURIRegex = /^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/; +async function isImageUri(uri) { try { - const maxPriorityFeePerGas = chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee; - if (typeof maxPriorityFeePerGas === "function") { - const block = block_ || await getAction(client, getBlock, "getBlock")({}); - const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({ - block, - client, - request - }); - if (maxPriorityFeePerGas_ === null) - throw new Error(); - return maxPriorityFeePerGas_; + const res = await fetch(uri, { method: "HEAD" }); + if (res.status === 200) { + const contentType = res.headers.get("content-type"); + return contentType?.startsWith("image/"); } - if (typeof maxPriorityFeePerGas !== "undefined") - return maxPriorityFeePerGas; - const maxPriorityFeePerGasHex = await client.request({ - method: "eth_maxPriorityFeePerGas" + return false; + } catch (error) { + if (typeof error === "object" && typeof error.response !== "undefined") { + return false; + } + if (!globalThis.hasOwnProperty("Image")) + return false; + return new Promise((resolve) => { + const img = new Image(); + img.onload = () => { + resolve(true); + }; + img.onerror = () => { + resolve(false); + }; + img.src = uri; }); - return hexToBigInt(maxPriorityFeePerGasHex); - } catch { - const [block, gasPrice] = await Promise.all([ - block_ ? Promise.resolve(block_) : getAction(client, getBlock, "getBlock")({}), - getAction(client, getGasPrice, "getGasPrice")({}) - ]); - if (typeof block.baseFeePerGas !== "bigint") - throw new Eip1559FeesNotSupportedError(); - const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas; - if (maxPriorityFeePerGas < 0n) - return 0n; - return maxPriorityFeePerGas; } } - -// node_modules/viem/_esm/actions/public/estimateFeesPerGas.js -async function estimateFeesPerGas(client, args) { - return internal_estimateFeesPerGas(client, args); +function getGateway(custom, defaultGateway) { + if (!custom) + return defaultGateway; + if (custom.endsWith("/")) + return custom.slice(0, -1); + return custom; } -async function internal_estimateFeesPerGas(client, args) { - const { block: block_, chain = client.chain, request, type = "eip1559" } = args || {}; - const baseFeeMultiplier = await (async () => { - if (typeof chain?.fees?.baseFeeMultiplier === "function") - return chain.fees.baseFeeMultiplier({ - block: block_, - client, - request - }); - return chain?.fees?.baseFeeMultiplier ?? 1.2; - })(); - if (baseFeeMultiplier < 1) - throw new BaseFeeScalarError(); - const decimals = baseFeeMultiplier.toString().split(".")[1]?.length ?? 0; - const denominator = 10 ** decimals; - const multiply = (base) => base * BigInt(Math.ceil(baseFeeMultiplier * denominator)) / BigInt(denominator); - const block = block_ ? block_ : await getAction(client, getBlock, "getBlock")({}); - if (typeof chain?.fees?.estimateFeesPerGas === "function") { - const fees = await chain.fees.estimateFeesPerGas({ - block: block_, - client, - multiply, - request, - type - }); - if (fees !== null) - return fees; +function resolveAvatarUri({ uri, gatewayUrls }) { + const isEncoded = base64Regex.test(uri); + if (isEncoded) + return { uri, isOnChain: true, isEncoded }; + const ipfsGateway = getGateway(gatewayUrls?.ipfs, "https://ipfs.io"); + const arweaveGateway = getGateway(gatewayUrls?.arweave, "https://arweave.net"); + const networkRegexMatch = uri.match(networkRegex); + const { protocol, subpath, target, subtarget = "" } = networkRegexMatch?.groups || {}; + const isIPNS = protocol === "ipns:/" || subpath === "ipns/"; + const isIPFS = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri); + if (uri.startsWith("http") && !isIPNS && !isIPFS) { + let replacedUri = uri; + if (gatewayUrls?.arweave) + replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls?.arweave); + return { uri: replacedUri, isOnChain: false, isEncoded: false }; } - if (type === "eip1559") { - if (typeof block.baseFeePerGas !== "bigint") - throw new Eip1559FeesNotSupportedError(); - const maxPriorityFeePerGas = typeof request?.maxPriorityFeePerGas === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, { - block, - chain, - request - }); - const baseFeePerGas = multiply(block.baseFeePerGas); - const maxFeePerGas = request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas; + if ((isIPNS || isIPFS) && target) { return { - maxFeePerGas, - maxPriorityFeePerGas + uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`, + isOnChain: false, + isEncoded: false }; } - const gasPrice = request?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({})); - return { - gasPrice - }; -} - -// node_modules/viem/_esm/actions/public/getTransactionCount.js -init_fromHex(); -init_toHex(); -async function getTransactionCount(client, { address, blockTag = "latest", blockNumber }) { - const count = await client.request({ - method: "eth_getTransactionCount", - params: [address, blockNumber ? numberToHex(blockNumber) : blockTag] - }, { dedupe: Boolean(blockNumber) }); - return hexToNumber(count); -} - -// node_modules/viem/_esm/utils/blob/blobsToCommitments.js -init_toBytes(); -init_toHex(); -function blobsToCommitments(parameters) { - const { kzg } = parameters; - const to2 = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); - const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x2) => hexToBytes(x2)) : parameters.blobs; - const commitments = []; - for (const blob of blobs) - commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob))); - return to2 === "bytes" ? commitments : commitments.map((x2) => bytesToHex(x2)); -} - -// node_modules/viem/_esm/utils/blob/blobsToProofs.js -init_toBytes(); -init_toHex(); -function blobsToProofs(parameters) { - const { kzg } = parameters; - const to2 = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); - const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x2) => hexToBytes(x2)) : parameters.blobs; - const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x2) => hexToBytes(x2)) : parameters.commitments; - const proofs = []; - for (let i = 0; i < blobs.length; i++) { - const blob = blobs[i]; - const commitment = commitments[i]; - proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment))); + if (protocol === "ar:/" && target) { + return { + uri: `${arweaveGateway}/${target}${subtarget || ""}`, + isOnChain: false, + isEncoded: false + }; } - return to2 === "bytes" ? proofs : proofs.map((x2) => bytesToHex(x2)); -} - -// node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js -init_toHex(); - -// node_modules/viem/_esm/utils/hash/sha256.js -init_sha256(); -init_isHex(); -init_toBytes(); -init_toHex(); -function sha2562(value, to_) { - const to2 = to_ || "hex"; - const bytes = sha256(isHex(value, { strict: false }) ? toBytes(value) : value); - if (to2 === "bytes") - return bytes; - return toHex(bytes); -} - -// node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js -function commitmentToVersionedHash(parameters) { - const { commitment, version: version4 = 1 } = parameters; - const to2 = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes"); - const versionedHash = sha2562(commitment, "bytes"); - versionedHash.set([version4], 0); - return to2 === "bytes" ? versionedHash : bytesToHex(versionedHash); + let parsedUri = uri.replace(dataURIRegex, ""); + if (parsedUri.startsWith(" res2.json()); + const image = await parseAvatarUri({ + gatewayUrls, + uri: getJsonImage(res) }); + return image; + } catch { + throw new EnsAvatarUriResolutionError({ uri }); } -}; -var EmptyBlobError = class extends BaseError2 { - constructor() { - super("Blob data must not be empty.", { name: "EmptyBlobError" }); +} +async function parseAvatarUri({ gatewayUrls, uri }) { + const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls }); + if (isOnChain) + return resolvedURI; + const isImage = await isImageUri(resolvedURI); + if (isImage) + return resolvedURI; + throw new EnsAvatarUriResolutionError({ uri }); +} +function parseNftUri(uri_) { + let uri = uri_; + if (uri.startsWith("did:nft:")) { + uri = uri.replace("did:nft:", "").replace(/_/g, "/"); } -}; -var InvalidVersionedHashSizeError = class extends BaseError2 { - constructor({ hash: hash2, size: size5 }) { - super(`Versioned hash "${hash2}" size is invalid.`, { - metaMessages: ["Expected: 32", `Received: ${size5}`], - name: "InvalidVersionedHashSizeError" + const [reference, asset_namespace, tokenID] = uri.split("/"); + const [eip_namespace, chainID] = reference.split(":"); + const [erc_namespace, contractAddress] = asset_namespace.split(":"); + if (!eip_namespace || eip_namespace.toLowerCase() !== "eip155") + throw new EnsAvatarInvalidNftUriError({ reason: "Only EIP-155 supported" }); + if (!chainID) + throw new EnsAvatarInvalidNftUriError({ reason: "Chain ID not found" }); + if (!contractAddress) + throw new EnsAvatarInvalidNftUriError({ + reason: "Contract address not found" }); - } -}; -var InvalidVersionedHashVersionError = class extends BaseError2 { - constructor({ hash: hash2, version: version4 }) { - super(`Versioned hash "${hash2}" version is invalid.`, { - metaMessages: [ - `Expected: ${versionedHashVersionKzg}`, - `Received: ${version4}` + if (!tokenID) + throw new EnsAvatarInvalidNftUriError({ reason: "Token ID not found" }); + if (!erc_namespace) + throw new EnsAvatarInvalidNftUriError({ reason: "ERC namespace not found" }); + return { + chainID: Number.parseInt(chainID), + namespace: erc_namespace.toLowerCase(), + contractAddress, + tokenID + }; +} +async function getNftTokenUri(client, { nft }) { + if (nft.namespace === "erc721") { + return readContract(client, { + address: nft.contractAddress, + abi: [ + { + name: "tokenURI", + type: "function", + stateMutability: "view", + inputs: [{ name: "tokenId", type: "uint256" }], + outputs: [{ name: "", type: "string" }] + } ], - name: "InvalidVersionedHashVersionError" + functionName: "tokenURI", + args: [BigInt(nft.tokenID)] }); } -}; - -// node_modules/viem/_esm/utils/blob/toBlobs.js -init_cursor2(); -init_size(); -init_toBytes(); -init_toHex(); -function toBlobs(parameters) { - const to2 = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes"); - const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data; - const size_ = size(data); - if (!size_) - throw new EmptyBlobError(); - if (size_ > maxBytesPerTransaction) - throw new BlobSizeTooLargeError({ - maxSize: maxBytesPerTransaction, - size: size_ + if (nft.namespace === "erc1155") { + return readContract(client, { + address: nft.contractAddress, + abi: [ + { + name: "uri", + type: "function", + stateMutability: "view", + inputs: [{ name: "_id", type: "uint256" }], + outputs: [{ name: "", type: "string" }] + } + ], + functionName: "uri", + args: [BigInt(nft.tokenID)] }); - const blobs = []; - let active = true; - let position = 0; - while (active) { - const blob = createCursor(new Uint8Array(bytesPerBlob)); - let size5 = 0; - while (size5 < fieldElementsPerBlob) { - const bytes = data.slice(position, position + (bytesPerFieldElement - 1)); - blob.pushByte(0); - blob.pushBytes(bytes); - if (bytes.length < 31) { - blob.pushByte(128); - active = false; - break; - } - size5++; - position += 31; - } - blobs.push(blob); } - return to2 === "bytes" ? blobs.map((x2) => x2.bytes) : blobs.map((x2) => bytesToHex(x2.bytes)); + throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace }); } -// node_modules/viem/_esm/utils/blob/toBlobSidecars.js -function toBlobSidecars(parameters) { - const { data, kzg, to: to2 } = parameters; - const blobs = parameters.blobs ?? toBlobs({ data, to: to2 }); - const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to: to2 }); - const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to: to2 }); - const sidecars = []; - for (let i = 0; i < blobs.length; i++) - sidecars.push({ - blob: blobs[i], - commitment: commitments[i], - proof: proofs[i] - }); - return sidecars; +// node_modules/viem/_esm/utils/ens/avatar/parseAvatarRecord.js +async function parseAvatarRecord(client, { gatewayUrls, record }) { + if (/eip155:/i.test(record)) + return parseNftAvatarUri(client, { gatewayUrls, record }); + return parseAvatarUri({ uri: record, gatewayUrls }); +} +async function parseNftAvatarUri(client, { gatewayUrls, record }) { + const nft = parseNftUri(record); + const nftUri = await getNftTokenUri(client, { nft }); + const { uri: resolvedNftUri, isOnChain, isEncoded } = resolveAvatarUri({ uri: nftUri, gatewayUrls }); + if (isOnChain && (resolvedNftUri.includes("data:application/json;base64,") || resolvedNftUri.startsWith("{"))) { + const encodedJson = isEncoded ? ( + // if it is encoded, decode it + atob(resolvedNftUri.replace("data:application/json;base64,", "")) + ) : ( + // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is) + resolvedNftUri + ); + const decoded = JSON.parse(encodedJson); + return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls }); + } + let uriTokenId = nft.tokenID; + if (nft.namespace === "erc1155") + uriTokenId = uriTokenId.replace("0x", "").padStart(64, "0"); + return getMetadataAvatarUri({ + gatewayUrls, + uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId) + }); } -// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js -init_assertRequest(); - -// node_modules/viem/_esm/utils/transaction/getTransactionType.js -init_transaction(); -function getTransactionType(transaction) { - if (transaction.type) - return transaction.type; - if (typeof transaction.authorizationList !== "undefined") - return "eip7702"; - if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined") - return "eip4844"; - if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") { - return "eip1559"; +// node_modules/viem/_esm/actions/ens/getEnsText.js +init_abis(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_getChainContractAddress(); +init_toHex(); +async function getEnsText(client, { blockNumber, blockTag, name, key, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "ensUniversalResolver" + }); } - if (typeof transaction.gasPrice !== "undefined") { - if (typeof transaction.accessList !== "undefined") - return "eip2930"; - return "legacy"; + try { + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverResolveAbi, + functionName: "resolve", + args: [ + toHex(packetToBytes(name)), + encodeFunctionData({ + abi: textResolverAbi, + functionName: "text", + args: [namehash(name), key] + }) + ], + blockNumber, + blockTag + }; + const readContractAction = getAction(client, readContract, "readContract"); + const res = gatewayUrls ? await readContractAction({ + ...readContractParameters, + args: [...readContractParameters.args, gatewayUrls] + }) : await readContractAction(readContractParameters); + if (res[0] === "0x") + return null; + const record = decodeFunctionResult({ + abi: textResolverAbi, + functionName: "text", + data: res[0] + }); + return record === "" ? null : record; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err, "resolve")) + return null; + throw err; } - throw new InvalidSerializableTransactionError({ transaction }); } -// node_modules/viem/_esm/actions/public/getChainId.js -init_fromHex(); -async function getChainId(client) { - const chainIdHex = await client.request({ - method: "eth_chainId" - }, { dedupe: true }); - return hexToNumber(chainIdHex); +// node_modules/viem/_esm/actions/ens/getEnsAvatar.js +async function getEnsAvatar(client, { blockNumber, blockTag, assetGatewayUrls, name, gatewayUrls, strict, universalResolverAddress }) { + const record = await getAction(client, getEnsText, "getEnsText")({ + blockNumber, + blockTag, + key: "avatar", + name, + universalResolverAddress, + gatewayUrls, + strict + }); + if (!record) + return null; + try { + return await parseAvatarRecord(client, { + record, + gatewayUrls: assetGatewayUrls + }); + } catch { + return null; + } } -// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js -var defaultParameters = [ - "blobVersionedHashes", - "chainId", - "fees", - "gas", - "nonce", - "type" -]; -var eip1559NetworkCache = /* @__PURE__ */ new Map(); -async function prepareTransactionRequest(client, args) { - const { account: account_ = client.account, blobs, chain, gas, kzg, nonce, nonceManager, parameters = defaultParameters, type } = args; - const account = account_ ? parseAccount(account_) : account_; - const request = { ...args, ...account ? { from: account?.address } : {} }; - let block; - async function getBlock2() { - if (block) - return block; - block = await getAction(client, getBlock, "getBlock")({ blockTag: "latest" }); - return block; - } - let chainId; - async function getChainId2() { - if (chainId) - return chainId; - if (chain) - return chain.id; - if (typeof args.chainId !== "undefined") - return args.chainId; - const chainId_ = await getAction(client, getChainId, "getChainId")({}); - chainId = chainId_; - return chainId; - } - if (parameters.includes("nonce") && typeof nonce === "undefined" && account) { - if (nonceManager) { - const chainId2 = await getChainId2(); - request.nonce = await nonceManager.consume({ - address: account.address, - chainId: chainId2, - client - }); - } else { - request.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({ - address: account.address, - blockTag: "pending" - }); - } - } - if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) { - const commitments = blobsToCommitments({ blobs, kzg }); - if (parameters.includes("blobVersionedHashes")) { - const versionedHashes = commitmentsToVersionedHashes({ - commitments, - to: "hex" - }); - request.blobVersionedHashes = versionedHashes; - } - if (parameters.includes("sidecars")) { - const proofs = blobsToProofs({ blobs, commitments, kzg }); - const sidecars = toBlobSidecars({ - blobs, - commitments, - proofs, - to: "hex" - }); - request.sidecars = sidecars; - } - } - if (parameters.includes("chainId")) - request.chainId = await getChainId2(); - if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") { - try { - request.type = getTransactionType(request); - } catch { - let isEip1559Network = eip1559NetworkCache.get(client.uid); - if (typeof isEip1559Network === "undefined") { - const block2 = await getBlock2(); - isEip1559Network = typeof block2?.baseFeePerGas === "bigint"; - eip1559NetworkCache.set(client.uid, isEip1559Network); - } - request.type = isEip1559Network ? "eip1559" : "legacy"; - } +// node_modules/viem/_esm/actions/ens/getEnsName.js +init_abis(); +init_getChainContractAddress(); +init_toHex(); +async function getEnsName(client, { address, blockNumber, blockTag, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "ensUniversalResolver" + }); } - if (parameters.includes("fees")) { - if (request.type !== "legacy" && request.type !== "eip2930") { - if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") { - const block2 = await getBlock2(); - const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client, { - block: block2, - chain, - request - }); - if (typeof args.maxPriorityFeePerGas === "undefined" && args.maxFeePerGas && args.maxFeePerGas < maxPriorityFeePerGas) - throw new MaxFeePerGasTooLowError({ - maxPriorityFeePerGas - }); - request.maxPriorityFeePerGas = maxPriorityFeePerGas; - request.maxFeePerGas = maxFeePerGas; - } - } else { - if (typeof args.maxFeePerGas !== "undefined" || typeof args.maxPriorityFeePerGas !== "undefined") - throw new Eip1559FeesNotSupportedError(); - if (typeof args.gasPrice === "undefined") { - const block2 = await getBlock2(); - const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, { - block: block2, - chain, - request, - type: "legacy" - }); - request.gasPrice = gasPrice_; - } - } + const reverseNode = `${address.toLowerCase().substring(2)}.addr.reverse`; + try { + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverReverseAbi, + functionName: "reverse", + args: [toHex(packetToBytes(reverseNode))], + blockNumber, + blockTag + }; + const readContractAction = getAction(client, readContract, "readContract"); + const [name, resolvedAddress] = gatewayUrls ? await readContractAction({ + ...readContractParameters, + args: [...readContractParameters.args, gatewayUrls] + }) : await readContractAction(readContractParameters); + if (address.toLowerCase() !== resolvedAddress.toLowerCase()) + return null; + return name; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err, "reverse")) + return null; + throw err; } - if (parameters.includes("gas") && typeof gas === "undefined") - request.gas = await getAction(client, estimateGas, "estimateGas")({ - ...request, - account: account ? { address: account.address, type: "json-rpc" } : account - }); - assertRequest(request); - delete request.parameters; - return request; } -// node_modules/viem/_esm/actions/public/getBalance.js +// node_modules/viem/_esm/actions/ens/getEnsResolver.js +init_getChainContractAddress(); init_toHex(); -async function getBalance(client, { address, blockNumber, blockTag = "latest" }) { - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const balance = await client.request({ - method: "eth_getBalance", - params: [address, blockNumberHex || blockTag] +async function getEnsResolver(client, { blockNumber, blockTag, name, universalResolverAddress: universalResolverAddress_ }) { + let universalResolverAddress = universalResolverAddress_; + if (!universalResolverAddress) { + if (!client.chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + universalResolverAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "ensUniversalResolver" + }); + } + const [resolverAddress] = await getAction(client, readContract, "readContract")({ + address: universalResolverAddress, + abi: [ + { + inputs: [{ type: "bytes" }], + name: "findResolver", + outputs: [{ type: "address" }, { type: "bytes32" }], + stateMutability: "view", + type: "function" + } + ], + functionName: "findResolver", + args: [toHex(packetToBytes(name))], + blockNumber, + blockTag }); - return BigInt(balance); + return resolverAddress; } -// node_modules/viem/_esm/actions/public/estimateGas.js -async function estimateGas(client, args) { - const { account: account_ = client.account } = args; +// node_modules/viem/_esm/clients/decorators/public.js +init_call(); + +// node_modules/viem/_esm/actions/public/createAccessList.js +init_parseAccount(); +init_toHex(); +init_getCallError(); +init_extract(); +init_transactionRequest(); +init_assertRequest(); +async function createAccessList(client, args) { + const { account: account_ = client.account, blockNumber, blockTag = "latest", blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, to: to2, value, ...rest } = args; const account = account_ ? parseAccount(account_) : void 0; try { - let estimateGas_rpc = function(parameters) { - const { block: block2, request: request2, rpcStateOverride: rpcStateOverride2 } = parameters; - return client.request({ - method: "eth_estimateGas", - params: rpcStateOverride2 ? [request2, block2 ?? "latest", rpcStateOverride2] : block2 ? [request2, block2] : [request2] - }); - }; - const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = await prepareTransactionRequest(client, { - ...args, - parameters: ( - // Some RPC Providers do not compute versioned hashes from blobs. We will need - // to compute them. - account?.type === "local" ? void 0 : ["blobVersionedHashes"] - ) - }); + assertRequest(args); const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; const block = blockNumberHex || blockTag; - const rpcStateOverride = serializeStateOverride(stateOverride); - const to2 = await (async () => { - if (rest.to) - return rest.to; - if (authorizationList && authorizationList.length > 0) - return await recoverAuthorizationAddress({ - authorization: authorizationList[0] - }).catch(() => { - throw new BaseError2("`to` is required. Could not infer from `authorizationList`"); - }); - return void 0; - })(); - assertRequest(args); const chainFormat = client.chain?.formatters?.transactionRequest?.format; const format = chainFormat || formatTransactionRequest; const request = format({ // Pick out extra data that might exist on the chain's transaction request type. ...extract(rest, { format: chainFormat }), from: account?.address, - accessList, - authorizationList, blobs, - blobVersionedHashes, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, - nonce, to: to2, value }); - let estimate = BigInt(await estimateGas_rpc({ block, request, rpcStateOverride })); - if (authorizationList) { - const value2 = await getBalance(client, { address: request.from }); - const estimates = await Promise.all(authorizationList.map(async (authorization) => { - const { address } = authorization; - const estimate2 = await estimateGas_rpc({ - block, - request: { - authorizationList: void 0, - data, - from: account?.address, - to: address, - value: numberToHex(value2) - }, - rpcStateOverride - }).catch(() => 100000n); - return 2n * BigInt(estimate2); - })); - estimate += estimates.reduce((acc, curr) => acc + curr, 0n); - } - return estimate; + const response = await client.request({ + method: "eth_createAccessList", + params: [request, block] + }); + return { + accessList: response.accessList, + gasUsed: BigInt(response.gasUsed) + }; } catch (err) { - throw getEstimateGasError(err, { + throw getCallError(err, { ...args, account, chain: client.chain @@ -55383,6784 +54290,7643 @@ async function estimateGas(client, args) { } } -// node_modules/viem/_esm/actions/public/estimateContractGas.js -async function estimateContractGas(client, parameters) { - const { abi: abi4, address, args, functionName, dataSuffix, ...request } = parameters; - const data = encodeFunctionData({ - abi: abi4, +// node_modules/viem/_esm/actions/public/createBlockFilter.js +async function createBlockFilter(client) { + const getRequest = createFilterRequestScope(client, { + method: "eth_newBlockFilter" + }); + const id2 = await client.request({ + method: "eth_newBlockFilter" + }); + return { id: id2, request: getRequest(id2), type: "block" }; +} + +// node_modules/viem/_esm/actions/public/createEventFilter.js +init_toHex(); +async function createEventFilter(client, { address, args, event, events: events_, fromBlock, strict, toBlock } = {}) { + const events = events_ ?? (event ? [event] : void 0); + const getRequest = createFilterRequestScope(client, { + method: "eth_newFilter" + }); + let topics = []; + if (events) { + const encoded = events.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + const id2 = await client.request({ + method: "eth_newFilter", + params: [ + { + address, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, + ...topics.length ? { topics } : {} + } + ] + }); + return { + abi: events, args, - functionName + eventName: event ? event.name : void 0, + fromBlock, + id: id2, + request: getRequest(id2), + strict: Boolean(strict), + toBlock, + type: "event" + }; +} + +// node_modules/viem/_esm/actions/public/createPendingTransactionFilter.js +async function createPendingTransactionFilter(client) { + const getRequest = createFilterRequestScope(client, { + method: "eth_newPendingTransactionFilter" }); - try { - const gas = await getAction(client, estimateGas, "estimateGas")({ - data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, - to: address, - ...request - }); - return gas; - } catch (error) { - const account = request.account ? parseAccount(request.account) : void 0; - throw getContractError(error, { - abi: abi4, - address, - args, - docsPath: "/docs/contract/estimateContractGas", - functionName, - sender: account?.address - }); + const id2 = await client.request({ + method: "eth_newPendingTransactionFilter" + }); + return { id: id2, request: getRequest(id2), type: "transaction" }; +} + +// node_modules/viem/_esm/actions/public/getBlobBaseFee.js +async function getBlobBaseFee(client) { + const baseFee = await client.request({ + method: "eth_blobBaseFee" + }); + return BigInt(baseFee); +} + +// node_modules/viem/_esm/actions/public/getBlockTransactionCount.js +init_fromHex(); +init_toHex(); +async function getBlockTransactionCount(client, { blockHash, blockNumber, blockTag = "latest" } = {}) { + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + let count; + if (blockHash) { + count = await client.request({ + method: "eth_getBlockTransactionCountByHash", + params: [blockHash] + }, { dedupe: true }); + } else { + count = await client.request({ + method: "eth_getBlockTransactionCountByNumber", + params: [blockNumberHex || blockTag] + }, { dedupe: Boolean(blockNumberHex) }); } + return hexToNumber(count); } -// node_modules/viem/_esm/actions/public/getContractEvents.js -init_getAbiItem(); +// node_modules/viem/_esm/actions/public/getCode.js +init_toHex(); +async function getCode(client, { address, blockNumber, blockTag = "latest" }) { + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + const hex = await client.request({ + method: "eth_getCode", + params: [address, blockNumberHex || blockTag] + }, { dedupe: Boolean(blockNumberHex) }); + if (hex === "0x") + return void 0; + return hex; +} -// node_modules/viem/_esm/utils/abi/parseEventLogs.js +// node_modules/viem/_esm/actions/public/getFeeHistory.js +init_toHex(); + +// node_modules/viem/_esm/utils/formatters/feeHistory.js +function formatFeeHistory(feeHistory) { + return { + baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)), + gasUsedRatio: feeHistory.gasUsedRatio, + oldestBlock: BigInt(feeHistory.oldestBlock), + reward: feeHistory.reward?.map((reward) => reward.map((value) => BigInt(value))) + }; +} + +// node_modules/viem/_esm/actions/public/getFeeHistory.js +async function getFeeHistory(client, { blockCount, blockNumber, blockTag = "latest", rewardPercentiles }) { + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const feeHistory = await client.request({ + method: "eth_feeHistory", + params: [ + numberToHex(blockCount), + blockNumberHex || blockTag, + rewardPercentiles + ] + }, { dedupe: Boolean(blockNumberHex) }); + return formatFeeHistory(feeHistory); +} + +// node_modules/viem/_esm/actions/public/getFilterLogs.js +async function getFilterLogs(_client, { filter: filter2 }) { + const strict = filter2.strict ?? false; + const logs = await filter2.request({ + method: "eth_getFilterLogs", + params: [filter2.id] + }); + const formattedLogs = logs.map((log) => formatLog(log)); + if (!filter2.abi) + return formattedLogs; + return parseEventLogs({ + abi: filter2.abi, + logs: formattedLogs, + strict + }); +} + +// node_modules/viem/_esm/actions/public/getProof.js +init_toHex(); + +// node_modules/viem/_esm/utils/chain/defineChain.js +function defineChain(chain) { + return { + formatters: void 0, + fees: void 0, + serializers: void 0, + ...chain + }; +} + +// node_modules/viem/_esm/utils/typedData.js init_abi(); -init_isAddressEqual(); -init_toBytes(); +init_address(); + +// node_modules/viem/_esm/errors/typedData.js +init_stringify(); +init_base(); +var InvalidDomainError = class extends BaseError2 { + constructor({ domain }) { + super(`Invalid domain "${stringify(domain)}".`, { + metaMessages: ["Must be a valid EIP-712 domain."] + }); + } +}; +var InvalidPrimaryTypeError = class extends BaseError2 { + constructor({ primaryType, types }) { + super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, { + docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror", + metaMessages: ["Check that the primary type is a key in `types`."] + }); + } +}; +var InvalidStructTypeError = class extends BaseError2 { + constructor({ type }) { + super(`Struct type "${type}" is invalid.`, { + metaMessages: ["Struct type must not be a Solidity type."], + name: "InvalidStructTypeError" + }); + } +}; + +// node_modules/viem/_esm/utils/typedData.js +init_isAddress(); +init_size(); +init_toHex(); +init_regex2(); + +// node_modules/viem/_esm/utils/signature/hashTypedData.js +init_encodeAbiParameters(); +init_concat(); +init_toHex(); init_keccak256(); -init_toEventSelector(); +function hashTypedData(parameters) { + const { domain = {}, message, primaryType } = parameters; + const types = { + EIP712Domain: getTypesForEIP712Domain({ domain }), + ...parameters.types + }; + validateTypedData({ + domain, + message, + primaryType, + types + }); + const parts = ["0x1901"]; + if (domain) + parts.push(hashDomain({ + domain, + types + })); + if (primaryType !== "EIP712Domain") + parts.push(hashStruct({ + data: message, + primaryType, + types + })); + return keccak256(concat(parts)); +} +function hashDomain({ domain, types }) { + return hashStruct({ + data: domain, + primaryType: "EIP712Domain", + types + }); +} +function hashStruct({ data, primaryType, types }) { + const encoded = encodeData({ + data, + primaryType, + types + }); + return keccak256(encoded); +} +function encodeData({ data, primaryType, types }) { + const encodedTypes = [{ type: "bytes32" }]; + const encodedValues = [hashType({ primaryType, types })]; + for (const field of types[primaryType]) { + const [type, value] = encodeField({ + types, + name: field.name, + type: field.type, + value: data[field.name] + }); + encodedTypes.push(type); + encodedValues.push(value); + } + return encodeAbiParameters(encodedTypes, encodedValues); +} +function hashType({ primaryType, types }) { + const encodedHashType = toHex(encodeType({ primaryType, types })); + return keccak256(encodedHashType); +} +function encodeType({ primaryType, types }) { + let result = ""; + const unsortedDeps = findTypeDependencies({ primaryType, types }); + unsortedDeps.delete(primaryType); + const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; + for (const type of deps) { + result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`; + } + return result; +} +function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) { + const match = primaryType_.match(/^\w*/u); + const primaryType = match?.[0]; + if (results.has(primaryType) || types[primaryType] === void 0) { + return results; + } + results.add(primaryType); + for (const field of types[primaryType]) { + findTypeDependencies({ primaryType: field.type, types }, results); + } + return results; +} +function encodeField({ types, name, type, value }) { + if (types[type] !== void 0) { + return [ + { type: "bytes32" }, + keccak256(encodeData({ data: value, primaryType: type, types })) + ]; + } + if (type === "bytes") { + const prepend = value.length % 2 ? "0" : ""; + value = `0x${prepend + value.slice(2)}`; + return [{ type: "bytes32" }, keccak256(value)]; + } + if (type === "string") + return [{ type: "bytes32" }, keccak256(toHex(value))]; + if (type.lastIndexOf("]") === type.length - 1) { + const parsedType = type.slice(0, type.lastIndexOf("[")); + const typeValuePairs = value.map((item) => encodeField({ + name, + type: parsedType, + types, + value: item + })); + return [ + { type: "bytes32" }, + keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v))) + ]; + } + return [{ type }, value]; +} + +// node_modules/viem/_esm/utils/typedData.js +init_stringify(); +function serializeTypedData(parameters) { + const { domain: domain_, message: message_, primaryType, types } = parameters; + const normalizeData = (struct, data_) => { + const data = { ...data_ }; + for (const param of struct) { + const { name, type } = param; + if (type === "address") + data[name] = data[name].toLowerCase(); + } + return data; + }; + const domain = (() => { + if (!types.EIP712Domain) + return {}; + if (!domain_) + return {}; + return normalizeData(types.EIP712Domain, domain_); + })(); + const message = (() => { + if (primaryType === "EIP712Domain") + return void 0; + return normalizeData(types[primaryType], message_); + })(); + return stringify({ domain, message, primaryType, types }); +} +function validateTypedData(parameters) { + const { domain, message, primaryType, types } = parameters; + const validateData = (struct, data) => { + for (const param of struct) { + const { name, type } = param; + const value = data[name]; + const integerMatch = type.match(integerRegex2); + if (integerMatch && (typeof value === "number" || typeof value === "bigint")) { + const [_type, base, size_] = integerMatch; + numberToHex(value, { + signed: base === "int", + size: Number.parseInt(size_) / 8 + }); + } + if (type === "address" && typeof value === "string" && !isAddress(value)) + throw new InvalidAddressError({ address: value }); + const bytesMatch = type.match(bytesRegex2); + if (bytesMatch) { + const [_type, size_] = bytesMatch; + if (size_ && size(value) !== Number.parseInt(size_)) + throw new BytesSizeMismatchError({ + expectedSize: Number.parseInt(size_), + givenSize: size(value) + }); + } + const struct2 = types[type]; + if (struct2) { + validateReference(type); + validateData(struct2, value); + } + } + }; + if (types.EIP712Domain && domain) { + if (typeof domain !== "object") + throw new InvalidDomainError({ domain }); + validateData(types.EIP712Domain, domain); + } + if (primaryType !== "EIP712Domain") { + if (types[primaryType]) + validateData(types[primaryType], message); + else + throw new InvalidPrimaryTypeError({ primaryType, types }); + } +} +function getTypesForEIP712Domain({ domain }) { + return [ + typeof domain?.name === "string" && { name: "name", type: "string" }, + domain?.version && { name: "version", type: "string" }, + (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && { + name: "chainId", + type: "uint256" + }, + domain?.verifyingContract && { + name: "verifyingContract", + type: "address" + }, + domain?.salt && { name: "salt", type: "bytes32" } + ].filter(Boolean); +} +function validateReference(type) { + if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int")) + throw new InvalidStructTypeError({ type }); +} + +// node_modules/viem/_esm/utils/index.js +init_encodeFunctionData(); + +// node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js +init_toHex(); + +// node_modules/viem/_esm/utils/transaction/serializeTransaction.js +init_transaction(); +init_concat(); +init_trim(); +init_toHex(); -// node_modules/viem/_esm/utils/abi/decodeEventLog.js -init_abi(); +// node_modules/viem/_esm/utils/transaction/assertTransaction.js +init_number(); +init_address(); +init_base(); +init_chain(); +init_node(); +init_isAddress(); init_size(); -init_toEventSelector(); -init_cursor(); -init_decodeAbiParameters(); -init_formatAbiItem2(); -var docsPath3 = "/docs/contract/decodeEventLog"; -function decodeEventLog(parameters) { - const { abi: abi4, data, strict: strict_, topics } = parameters; - const strict = strict_ ?? true; - const [signature, ...argTopics] = topics; - if (!signature) - throw new AbiEventSignatureEmptyTopicsError({ docsPath: docsPath3 }); - const abiItem = (() => { - if (abi4.length === 1) - return abi4[0]; - return abi4.find((x2) => x2.type === "event" && signature === toEventSelector(formatAbiItem2(x2))); - })(); - if (!(abiItem && "name" in abiItem) || abiItem.type !== "event") - throw new AbiEventSignatureNotFoundError(signature, { docsPath: docsPath3 }); - const { name, inputs } = abiItem; - const isUnnamed = inputs?.some((x2) => !("name" in x2 && x2.name)); - let args = isUnnamed ? [] : {}; - const indexedInputs = inputs.filter((x2) => "indexed" in x2 && x2.indexed); - for (let i = 0; i < indexedInputs.length; i++) { - const param = indexedInputs[i]; - const topic = argTopics[i]; - if (!topic) - throw new DecodeLogTopicsMismatch({ - abiItem, - param - }); - args[isUnnamed ? i : param.name || i] = decodeTopic({ param, value: topic }); +init_slice(); +init_fromHex(); +function assertTransactionEIP7702(transaction) { + const { authorizationList } = transaction; + if (authorizationList) { + for (const authorization of authorizationList) { + const { chainId } = authorization; + const address = authorization.address; + if (!isAddress(address)) + throw new InvalidAddressError({ address }); + if (chainId < 0) + throw new InvalidChainIdError({ chainId }); + } } - const nonIndexedInputs = inputs.filter((x2) => !("indexed" in x2 && x2.indexed)); - if (nonIndexedInputs.length > 0) { - if (data && data !== "0x") { - try { - const decodedData = decodeAbiParameters(nonIndexedInputs, data); - if (decodedData) { - if (isUnnamed) - args = [...args, ...decodedData]; - else { - for (let i = 0; i < nonIndexedInputs.length; i++) { - args[nonIndexedInputs[i].name] = decodedData[i]; - } - } - } - } catch (err) { - if (strict) { - if (err instanceof AbiDecodingDataSizeTooSmallError || err instanceof PositionOutOfBoundsError) - throw new DecodeLogDataMismatch({ - abiItem, - data, - params: nonIndexedInputs, - size: size(data) - }); - throw err; - } - } - } else if (strict) { - throw new DecodeLogDataMismatch({ - abiItem, - data: "0x", - params: nonIndexedInputs, - size: 0 - }); + assertTransactionEIP1559(transaction); +} +function assertTransactionEIP4844(transaction) { + const { blobVersionedHashes } = transaction; + if (blobVersionedHashes) { + if (blobVersionedHashes.length === 0) + throw new EmptyBlobError(); + for (const hash2 of blobVersionedHashes) { + const size_ = size(hash2); + const version4 = hexToNumber(slice(hash2, 0, 1)); + if (size_ !== 32) + throw new InvalidVersionedHashSizeError({ hash: hash2, size: size_ }); + if (version4 !== versionedHashVersionKzg) + throw new InvalidVersionedHashVersionError({ + hash: hash2, + version: version4 + }); } } - return { - eventName: name, - args: Object.values(args).length > 0 ? args : void 0 - }; + assertTransactionEIP1559(transaction); } -function decodeTopic({ param, value }) { - if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) - return value; - const decodedArg = decodeAbiParameters([param], value) || []; - return decodedArg[0]; +function assertTransactionEIP1559(transaction) { + const { chainId, maxPriorityFeePerGas, maxFeePerGas, to: to2 } = transaction; + if (chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (to2 && !isAddress(to2)) + throw new InvalidAddressError({ address: to2 }); + if (maxFeePerGas && maxFeePerGas > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas }); + if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) + throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); +} +function assertTransactionEIP2930(transaction) { + const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to: to2 } = transaction; + if (chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (to2 && !isAddress(to2)) + throw new InvalidAddressError({ address: to2 }); + if (maxPriorityFeePerGas || maxFeePerGas) + throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute."); + if (gasPrice && gasPrice > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); +} +function assertTransactionLegacy(transaction) { + const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to: to2 } = transaction; + if (to2 && !isAddress(to2)) + throw new InvalidAddressError({ address: to2 }); + if (typeof chainId !== "undefined" && chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (maxPriorityFeePerGas || maxFeePerGas) + throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute."); + if (gasPrice && gasPrice > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); } -// node_modules/viem/_esm/utils/abi/parseEventLogs.js -function parseEventLogs(parameters) { - const { abi: abi4, args, logs, strict = true } = parameters; - const eventName = (() => { - if (!parameters.eventName) - return void 0; - if (Array.isArray(parameters.eventName)) - return parameters.eventName; - return [parameters.eventName]; - })(); - return logs.map((log) => { - try { - const abiItem = abi4.find((abiItem2) => abiItem2.type === "event" && log.topics[0] === toEventSelector(abiItem2)); - if (!abiItem) - return null; - const event = decodeEventLog({ - ...log, - abi: [abiItem], - strict - }); - if (eventName && !eventName.includes(event.eventName)) - return null; - if (!includesArgs({ - args: event.args, - inputs: abiItem.inputs, - matchArgs: args - })) - return null; - return { ...event, ...log }; - } catch (err) { - let eventName2; - let isUnnamed; - if (err instanceof AbiEventSignatureNotFoundError) - return null; - if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { - if (strict) - return null; - eventName2 = err.abiItem.name; - isUnnamed = err.abiItem.inputs?.some((x2) => !("name" in x2 && x2.name)); +// node_modules/viem/_esm/utils/transaction/serializeAccessList.js +init_address(); +init_transaction(); +init_isAddress(); +function serializeAccessList(accessList) { + if (!accessList || accessList.length === 0) + return []; + const serializedAccessList = []; + for (let i = 0; i < accessList.length; i++) { + const { address, storageKeys } = accessList[i]; + for (let j2 = 0; j2 < storageKeys.length; j2++) { + if (storageKeys[j2].length - 2 !== 64) { + throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j2] }); } - return { ...log, args: isUnnamed ? [] : {}, eventName: eventName2 }; } - }).filter(Boolean); -} -function includesArgs(parameters) { - const { args, inputs, matchArgs } = parameters; - if (!matchArgs) - return true; - if (!args) - return false; - function isEqual(input, value, arg) { - try { - if (input.type === "address") - return isAddressEqual(value, arg); - if (input.type === "string" || input.type === "bytes") - return keccak256(toBytes(value)) === arg; - return value === arg; - } catch { - return false; + if (!isAddress(address, { strict: false })) { + throw new InvalidAddressError({ address }); } + serializedAccessList.push([address, storageKeys]); } - if (Array.isArray(args) && Array.isArray(matchArgs)) { - return matchArgs.every((value, index2) => { - if (value === null || value === void 0) - return true; - const input = inputs[index2]; - if (!input) - return false; - const value_ = Array.isArray(value) ? value : [value]; - return value_.some((value2) => isEqual(input, value2, args[index2])); - }); - } - if (typeof args === "object" && !Array.isArray(args) && typeof matchArgs === "object" && !Array.isArray(matchArgs)) - return Object.entries(matchArgs).every(([key, value]) => { - if (value === null || value === void 0) - return true; - const input = inputs.find((input2) => input2.name === key); - if (!input) - return false; - const value_ = Array.isArray(value) ? value : [value]; - return value_.some((value2) => isEqual(input, value2, args[key])); - }); - return false; + return serializedAccessList; } -// node_modules/viem/_esm/actions/public/getLogs.js -init_toHex(); - -// node_modules/viem/_esm/utils/formatters/log.js -function formatLog(log, { args, eventName } = {}) { - return { - ...log, - blockHash: log.blockHash ? log.blockHash : null, - blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null, - logIndex: log.logIndex ? Number(log.logIndex) : null, - transactionHash: log.transactionHash ? log.transactionHash : null, - transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null, - ...eventName ? { args, eventName } : {} - }; +// node_modules/viem/_esm/utils/transaction/serializeTransaction.js +function serializeTransaction(transaction, signature) { + const type = getTransactionType(transaction); + if (type === "eip1559") + return serializeTransactionEIP1559(transaction, signature); + if (type === "eip2930") + return serializeTransactionEIP2930(transaction, signature); + if (type === "eip4844") + return serializeTransactionEIP4844(transaction, signature); + if (type === "eip7702") + return serializeTransactionEIP7702(transaction, signature); + return serializeTransactionLegacy(transaction, signature); } - -// node_modules/viem/_esm/actions/public/getLogs.js -async function getLogs(client, { address, blockHash, fromBlock, toBlock, event, events: events_, args, strict: strict_ } = {}) { - const strict = strict_ ?? false; - const events = events_ ?? (event ? [event] : void 0); - let topics = []; - if (events) { - const encoded = events.flatMap((event2) => encodeEventTopics({ - abi: [event2], - eventName: event2.name, - args: events_ ? void 0 : args - })); - topics = [encoded]; - if (event) - topics = topics[0]; - } - let logs; - if (blockHash) { - logs = await client.request({ - method: "eth_getLogs", - params: [{ address, topics, blockHash }] - }); - } else { - logs = await client.request({ - method: "eth_getLogs", - params: [ - { - address, - topics, - fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, - toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock - } - ] +function serializeTransactionEIP7702(transaction, signature) { + const { authorizationList, chainId, gas, nonce, to: to2, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP7702(transaction); + const serializedAccessList = serializeAccessList(accessList); + const serializedAuthorizationList = serializeAuthorizationList(authorizationList); + return concatHex([ + "0x04", + toRlp([ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? toHex(maxFeePerGas) : "0x", + gas ? toHex(gas) : "0x", + to2 ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + serializedAuthorizationList, + ...toYParitySignatureArray(transaction, signature) + ]) + ]); +} +function serializeTransactionEIP4844(transaction, signature) { + const { chainId, gas, nonce, to: to2, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP4844(transaction); + let blobVersionedHashes = transaction.blobVersionedHashes; + let sidecars = transaction.sidecars; + if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) { + const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x2) => bytesToHex(x2)); + const kzg = transaction.kzg; + const commitments2 = blobsToCommitments({ + blobs: blobs2, + kzg }); + if (typeof blobVersionedHashes === "undefined") + blobVersionedHashes = commitmentsToVersionedHashes({ + commitments: commitments2 + }); + if (typeof sidecars === "undefined") { + const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg }); + sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 }); + } } - const formattedLogs = logs.map((log) => formatLog(log)); - if (!events) - return formattedLogs; - return parseEventLogs({ - abi: events, - args, - logs: formattedLogs, - strict - }); + const serializedAccessList = serializeAccessList(accessList); + const serializedTransaction = [ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? toHex(maxFeePerGas) : "0x", + gas ? toHex(gas) : "0x", + to2 ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : "0x", + blobVersionedHashes ?? [], + ...toYParitySignatureArray(transaction, signature) + ]; + const blobs = []; + const commitments = []; + const proofs = []; + if (sidecars) + for (let i = 0; i < sidecars.length; i++) { + const { blob, commitment, proof } = sidecars[i]; + blobs.push(blob); + commitments.push(commitment); + proofs.push(proof); + } + return concatHex([ + "0x03", + sidecars ? ( + // If sidecars are enabled, envelope turns into a "wrapper": + toRlp([serializedTransaction, blobs, commitments, proofs]) + ) : ( + // If sidecars are disabled, standard envelope is used: + toRlp(serializedTransaction) + ) + ]); } - -// node_modules/viem/_esm/actions/public/getContractEvents.js -async function getContractEvents(client, parameters) { - const { abi: abi4, address, args, blockHash, eventName, fromBlock, toBlock, strict } = parameters; - const event = eventName ? getAbiItem({ abi: abi4, name: eventName }) : void 0; - const events = !event ? abi4.filter((x2) => x2.type === "event") : void 0; - return getAction(client, getLogs, "getLogs")({ - address, - args, - blockHash, - event, - events, - fromBlock, - toBlock, - strict - }); +function serializeTransactionEIP1559(transaction, signature) { + const { chainId, gas, nonce, to: to2, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP1559(transaction); + const serializedAccessList = serializeAccessList(accessList); + const serializedTransaction = [ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? toHex(maxFeePerGas) : "0x", + gas ? toHex(gas) : "0x", + to2 ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + ...toYParitySignatureArray(transaction, signature) + ]; + return concatHex([ + "0x02", + toRlp(serializedTransaction) + ]); } - -// node_modules/viem/_esm/actions/public/readContract.js -init_decodeFunctionResult(); -init_encodeFunctionData(); -init_call(); -async function readContract(client, parameters) { - const { abi: abi4, address, args, functionName, ...rest } = parameters; - const calldata = encodeFunctionData({ - abi: abi4, - args, - functionName - }); - try { - const { data } = await getAction(client, call, "call")({ - ...rest, - data: calldata, - to: address - }); - return decodeFunctionResult({ - abi: abi4, - args, - functionName, - data: data || "0x" - }); - } catch (error) { - throw getContractError(error, { - abi: abi4, - address, - args, - docsPath: "/docs/contract/readContract", - functionName - }); +function serializeTransactionEIP2930(transaction, signature) { + const { chainId, gas, data, nonce, to: to2, value, accessList, gasPrice } = transaction; + assertTransactionEIP2930(transaction); + const serializedAccessList = serializeAccessList(accessList); + const serializedTransaction = [ + toHex(chainId), + nonce ? toHex(nonce) : "0x", + gasPrice ? toHex(gasPrice) : "0x", + gas ? toHex(gas) : "0x", + to2 ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x", + serializedAccessList, + ...toYParitySignatureArray(transaction, signature) + ]; + return concatHex([ + "0x01", + toRlp(serializedTransaction) + ]); +} +function serializeTransactionLegacy(transaction, signature) { + const { chainId = 0, gas, data, nonce, to: to2, value, gasPrice } = transaction; + assertTransactionLegacy(transaction); + let serializedTransaction = [ + nonce ? toHex(nonce) : "0x", + gasPrice ? toHex(gasPrice) : "0x", + gas ? toHex(gas) : "0x", + to2 ?? "0x", + value ? toHex(value) : "0x", + data ?? "0x" + ]; + if (signature) { + const v = (() => { + if (signature.v >= 35n) { + const inferredChainId = (signature.v - 35n) / 2n; + if (inferredChainId > 0) + return signature.v; + return 27n + (signature.v === 35n ? 0n : 1n); + } + if (chainId > 0) + return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n); + const v2 = 27n + (signature.v === 27n ? 0n : 1n); + if (signature.v !== v2) + throw new InvalidLegacyVError({ v: signature.v }); + return v2; + })(); + const r = trim(signature.r); + const s = trim(signature.s); + serializedTransaction = [ + ...serializedTransaction, + toHex(v), + r === "0x00" ? "0x" : r, + s === "0x00" ? "0x" : s + ]; + } else if (chainId > 0) { + serializedTransaction = [ + ...serializedTransaction, + toHex(chainId), + "0x", + "0x" + ]; } + return toRlp(serializedTransaction); +} +function toYParitySignatureArray(transaction, signature_) { + const signature = signature_ ?? transaction; + const { v, yParity } = signature; + if (typeof signature.r === "undefined") + return []; + if (typeof signature.s === "undefined") + return []; + if (typeof v === "undefined" && typeof yParity === "undefined") + return []; + const r = trim(signature.r); + const s = trim(signature.s); + const yParity_ = (() => { + if (typeof yParity === "number") + return yParity ? toHex(1) : "0x"; + if (v === 0n) + return "0x"; + if (v === 1n) + return toHex(1); + return v === 27n ? "0x" : toHex(1); + })(); + return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s]; } -// node_modules/viem/_esm/actions/public/simulateContract.js -init_parseAccount(); -init_decodeFunctionResult(); -init_encodeFunctionData(); -init_call(); -async function simulateContract(client, parameters) { - const { abi: abi4, address, args, dataSuffix, functionName, ...callRequest } = parameters; - const account = callRequest.account ? parseAccount(callRequest.account) : client.account; - const calldata = encodeFunctionData({ abi: abi4, args, functionName }); - try { - const { data } = await getAction(client, call, "call")({ - batch: false, - data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, - to: address, - ...callRequest, - account - }); - const result = decodeFunctionResult({ - abi: abi4, - args, - functionName, - data: data || "0x" - }); - const minimizedAbi = abi4.filter((abiItem) => "name" in abiItem && abiItem.name === parameters.functionName); - return { - result, - request: { - abi: minimizedAbi, - address, - args, - dataSuffix, - functionName, - ...callRequest, - account - } - }; - } catch (error) { - throw getContractError(error, { - abi: abi4, - address, - args, - docsPath: "/docs/contract/simulateContract", - functionName, - sender: account?.address - }); +// node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js +function serializeAuthorizationList(authorizationList) { + if (!authorizationList || authorizationList.length === 0) + return []; + const serializedAuthorizationList = []; + for (const authorization of authorizationList) { + const { chainId, nonce, ...signature } = authorization; + const contractAddress = authorization.address; + serializedAuthorizationList.push([ + chainId ? toHex(chainId) : "0x", + contractAddress, + nonce ? toHex(nonce) : "0x", + ...toYParitySignatureArray({}, signature) + ]); } + return serializedAuthorizationList; } -// node_modules/viem/_esm/actions/public/watchContractEvent.js -init_abi(); -init_rpc(); - -// node_modules/viem/_esm/utils/observe.js -var listenersCache = /* @__PURE__ */ new Map(); -var cleanupCache = /* @__PURE__ */ new Map(); -var callbackCount = 0; -function observe(observerId, callbacks, fn2) { - const callbackId = ++callbackCount; - const getListeners = () => listenersCache.get(observerId) || []; - const unsubscribe = () => { - const listeners2 = getListeners(); - listenersCache.set(observerId, listeners2.filter((cb) => cb.id !== callbackId)); - }; - const unwatch = () => { - const listeners2 = getListeners(); - if (!listeners2.some((cb) => cb.id === callbackId)) - return; - const cleanup2 = cleanupCache.get(observerId); - if (listeners2.length === 1 && cleanup2) - cleanup2(); - unsubscribe(); +// node_modules/viem/_esm/utils/formatters/transactionReceipt.js +init_fromHex(); +var receiptStatuses = { + "0x0": "reverted", + "0x1": "success" +}; +function formatTransactionReceipt(transactionReceipt) { + const receipt = { + ...transactionReceipt, + blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null, + contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null, + cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null, + effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null, + gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null, + logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null, + to: transactionReceipt.to ? transactionReceipt.to : null, + transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null, + status: transactionReceipt.status ? receiptStatuses[transactionReceipt.status] : null, + type: transactionReceipt.type ? transactionType[transactionReceipt.type] || transactionReceipt.type : null }; - const listeners = getListeners(); - listenersCache.set(observerId, [ - ...listeners, - { id: callbackId, fns: callbacks } - ]); - if (listeners && listeners.length > 0) - return unwatch; - const emit = {}; - for (const key in callbacks) { - emit[key] = (...args) => { - const listeners2 = getListeners(); - if (listeners2.length === 0) - return; - for (const listener of listeners2) - listener.fns[key]?.(...args); - }; - } - const cleanup = fn2(emit); - if (typeof cleanup === "function") - cleanupCache.set(observerId, cleanup); - return unwatch; + if (transactionReceipt.blobGasPrice) + receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice); + if (transactionReceipt.blobGasUsed) + receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed); + return receipt; } -// node_modules/viem/_esm/utils/wait.js -async function wait(time) { - return new Promise((res) => setTimeout(res, time)); -} +// node_modules/viem/_esm/utils/index.js +init_fromHex(); -// node_modules/viem/_esm/utils/poll.js -function poll(fn2, { emitOnBegin, initialWaitTime, interval }) { - let active = true; - const unwatch = () => active = false; - const watch = async () => { - let data = void 0; - if (emitOnBegin) - data = await fn2({ unpoll: unwatch }); - const initialWait = await initialWaitTime?.(data) ?? interval; - await wait(initialWait); - const poll2 = async () => { - if (!active) - return; - await fn2({ unpoll: unwatch }); - await wait(interval); - poll2(); - }; - poll2(); - }; - watch(); - return unwatch; -} +// node_modules/viem/_esm/utils/signature/hashMessage.js +init_keccak256(); -// node_modules/viem/_esm/actions/public/watchContractEvent.js -init_stringify(); +// node_modules/viem/_esm/constants/strings.js +var presignMessagePrefix = "Ethereum Signed Message:\n"; -// node_modules/viem/_esm/utils/promise/withCache.js -var promiseCache = /* @__PURE__ */ new Map(); -var responseCache = /* @__PURE__ */ new Map(); -function getCache(cacheKey2) { - const buildCache = (cacheKey3, cache) => ({ - clear: () => cache.delete(cacheKey3), - get: () => cache.get(cacheKey3), - set: (data) => cache.set(cacheKey3, data) - }); - const promise = buildCache(cacheKey2, promiseCache); - const response = buildCache(cacheKey2, responseCache); - return { - clear: () => { - promise.clear(); - response.clear(); - }, - promise, - response - }; -} -async function withCache(fn2, { cacheKey: cacheKey2, cacheTime = Number.POSITIVE_INFINITY }) { - const cache = getCache(cacheKey2); - const response = cache.response.get(); - if (response && cacheTime > 0) { - const age = (/* @__PURE__ */ new Date()).getTime() - response.created.getTime(); - if (age < cacheTime) - return response.data; - } - let promise = cache.promise.get(); - if (!promise) { - promise = fn2(); - cache.promise.set(promise); - } - try { - const data = await promise; - cache.response.set({ created: /* @__PURE__ */ new Date(), data }); - return data; - } finally { - cache.promise.clear(); - } +// node_modules/viem/_esm/utils/signature/toPrefixedMessage.js +init_concat(); +init_size(); +init_toHex(); +function toPrefixedMessage(message_) { + const message = (() => { + if (typeof message_ === "string") + return stringToHex(message_); + if (typeof message_.raw === "string") + return message_.raw; + return bytesToHex(message_.raw); + })(); + const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`); + return concat([prefix, message]); } -// node_modules/viem/_esm/actions/public/getBlockNumber.js -var cacheKey = (id2) => `blockNumber.${id2}`; -async function getBlockNumber(client, { cacheTime = client.cacheTime } = {}) { - const blockNumberHex = await withCache(() => client.request({ - method: "eth_blockNumber" - }), { cacheKey: cacheKey(client.uid), cacheTime }); - return BigInt(blockNumberHex); +// node_modules/viem/_esm/utils/signature/hashMessage.js +function hashMessage(message, to_) { + return keccak256(toPrefixedMessage(message), to_); } -// node_modules/viem/_esm/actions/public/getFilterChanges.js -async function getFilterChanges(_client, { filter: filter2 }) { - const strict = "strict" in filter2 && filter2.strict; - const logs = await filter2.request({ - method: "eth_getFilterChanges", - params: [filter2.id] - }); - if (typeof logs[0] === "string") - return logs; - const formattedLogs = logs.map((log) => formatLog(log)); - if (!("abi" in filter2) || !filter2.abi) - return formattedLogs; - return parseEventLogs({ - abi: filter2.abi, - logs: formattedLogs, - strict - }); +// node_modules/viem/_esm/constants/bytes.js +var erc6492MagicBytes = "0x6492649264926492649264926492649264926492649264926492649264926492"; + +// node_modules/viem/_esm/utils/signature/isErc6492Signature.js +init_slice(); +function isErc6492Signature(signature) { + return sliceHex(signature, -32) === erc6492MagicBytes; } -// node_modules/viem/_esm/actions/public/uninstallFilter.js -async function uninstallFilter(_client, { filter: filter2 }) { - return filter2.request({ - method: "eth_uninstallFilter", - params: [filter2.id] - }); +// node_modules/viem/_esm/utils/signature/serializeErc6492Signature.js +init_encodeAbiParameters(); +init_concat(); +init_toBytes(); +function serializeErc6492Signature(parameters) { + const { address, data, signature, to: to2 = "hex" } = parameters; + const signature_ = concatHex([ + encodeAbiParameters([{ type: "address" }, { type: "bytes" }, { type: "bytes" }], [address, data, signature]), + erc6492MagicBytes + ]); + if (to2 === "hex") + return signature_; + return hexToBytes(signature_); } -// node_modules/viem/_esm/actions/public/watchContractEvent.js -function watchContractEvent(client, parameters) { - const { abi: abi4, address, args, batch = true, eventName, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ } = parameters; - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (typeof fromBlock === "bigint") - return true; - if (client.transport.type === "webSocket") - return false; - if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") - return false; - return true; - })(); - const pollContractEvent = () => { - const strict = strict_ ?? false; - const observerId = stringify([ - "watchContractEvent", - address, - args, - batch, - client.uid, - eventName, - pollingInterval, - strict, - fromBlock - ]); - return observe(observerId, { onLogs, onError }, (emit) => { - let previousBlockNumber; - if (fromBlock !== void 0) - previousBlockNumber = fromBlock - 1n; - let filter2; - let initialized = false; - const unwatch = poll(async () => { - if (!initialized) { - try { - filter2 = await getAction(client, createContractEventFilter, "createContractEventFilter")({ - abi: abi4, - address, - args, - eventName, - strict, - fromBlock - }); - } catch { - } - initialized = true; - return; - } - try { - let logs; - if (filter2) { - logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter: filter2 }); - } else { - const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({}); - if (previousBlockNumber && previousBlockNumber < blockNumber) { - logs = await getAction(client, getContractEvents, "getContractEvents")({ - abi: abi4, - address, - args, - eventName, - fromBlock: previousBlockNumber + 1n, - toBlock: blockNumber, - strict - }); - } else { - logs = []; - } - previousBlockNumber = blockNumber; - } - if (logs.length === 0) - return; - if (batch) - emit.onLogs(logs); - else - for (const log of logs) - emit.onLogs([log]); - } catch (err) { - if (filter2 && err instanceof InvalidInputRpcError) - initialized = false; - emit.onError?.(err); - } - }, { - emitOnBegin: true, - interval: pollingInterval - }); - return async () => { - if (filter2) - await getAction(client, uninstallFilter, "uninstallFilter")({ filter: filter2 }); - unwatch(); - }; - }); - }; - const subscribeContractEvent = () => { - const strict = strict_ ?? false; - const observerId = stringify([ - "watchContractEvent", - address, - args, - batch, - client.uid, - eventName, - pollingInterval, - strict - ]); - let active = true; - let unsubscribe = () => active = false; - return observe(observerId, { onLogs, onError }, (emit) => { - ; - (async () => { - try { - const transport = (() => { - if (client.transport.type === "fallback") { - const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); - if (!transport2) - return client.transport; - return transport2.value; - } - return client.transport; - })(); - const topics = eventName ? encodeEventTopics({ - abi: abi4, - eventName, - args - }) : []; - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["logs", { address, topics }], - onData(data) { - if (!active) - return; - const log = data.result; - try { - const { eventName: eventName2, args: args2 } = decodeEventLog({ - abi: abi4, - data: log.data, - topics: log.topics, - strict: strict_ - }); - const formatted = formatLog(log, { - args: args2, - eventName: eventName2 - }); - emit.onLogs([formatted]); - } catch (err) { - let eventName2; - let isUnnamed; - if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { - if (strict_) - return; - eventName2 = err.abiItem.name; - isUnnamed = err.abiItem.inputs?.some((x2) => !("name" in x2 && x2.name)); - } - const formatted = formatLog(log, { - args: isUnnamed ? [] : {}, - eventName: eventName2 - }); - emit.onLogs([formatted]); - } - }, - onError(error) { - emit.onError?.(error); - } - }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError?.(err); - } - })(); - return () => unsubscribe(); - }); +// node_modules/viem/_esm/utils/formatters/proof.js +function formatStorageProof(storageProof) { + return storageProof.map((proof) => ({ + ...proof, + value: BigInt(proof.value) + })); +} +function formatProof(proof) { + return { + ...proof, + balance: proof.balance ? BigInt(proof.balance) : void 0, + nonce: proof.nonce ? hexToNumber(proof.nonce) : void 0, + storageProof: proof.storageProof ? formatStorageProof(proof.storageProof) : void 0 }; - return enablePolling ? pollContractEvent() : subscribeContractEvent(); } -// node_modules/viem/_esm/actions/wallet/writeContract.js -init_parseAccount(); - -// node_modules/viem/_esm/errors/account.js -init_base(); -var AccountNotFoundError = class extends BaseError2 { - constructor({ docsPath: docsPath6 } = {}) { - super([ - "Could not find an Account to execute with this Action.", - "Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client." - ].join("\n"), { - docsPath: docsPath6, - docsSlug: "account", - name: "AccountNotFoundError" - }); - } -}; -var AccountTypeNotSupportedError = class extends BaseError2 { - constructor({ docsPath: docsPath6, metaMessages, type }) { - super(`Account type "${type}" is not supported.`, { - docsPath: docsPath6, - metaMessages, - name: "AccountTypeNotSupportedError" - }); - } -}; - -// node_modules/viem/_esm/actions/wallet/writeContract.js -init_encodeFunctionData(); - -// node_modules/viem/_esm/actions/wallet/sendTransaction.js -init_parseAccount(); -init_base(); +// node_modules/viem/_esm/actions/public/getProof.js +async function getProof(client, { address, blockNumber, blockTag: blockTag_, storageKeys }) { + const blockTag = blockTag_ ?? "latest"; + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + const proof = await client.request({ + method: "eth_getProof", + params: [address, storageKeys, blockNumberHex || blockTag] + }); + return formatProof(proof); +} -// node_modules/viem/_esm/utils/chain/assertCurrentChain.js -init_chain(); -function assertCurrentChain({ chain, currentChainId }) { - if (!chain) - throw new ChainNotFoundError(); - if (currentChainId !== chain.id) - throw new ChainMismatchError({ chain, currentChainId }); +// node_modules/viem/_esm/actions/public/getStorageAt.js +init_toHex(); +async function getStorageAt(client, { address, blockNumber, blockTag = "latest", slot }) { + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + const data = await client.request({ + method: "eth_getStorageAt", + params: [address, slot, blockNumberHex || blockTag] + }); + return data; } -// node_modules/viem/_esm/utils/errors/getTransactionError.js -init_node(); +// node_modules/viem/_esm/actions/public/getTransaction.js init_transaction(); -init_getNodeError(); -function getTransactionError(err, { docsPath: docsPath6, ...args }) { - const cause = (() => { - const cause2 = getNodeError(err, args); - if (cause2 instanceof UnknownNodeError) - return err; - return cause2; - })(); - return new TransactionExecutionError(cause, { - docsPath: docsPath6, - ...args - }); +init_toHex(); +async function getTransaction(client, { blockHash, blockNumber, blockTag: blockTag_, hash: hash2, index: index2 }) { + const blockTag = blockTag_ || "latest"; + const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; + let transaction = null; + if (hash2) { + transaction = await client.request({ + method: "eth_getTransactionByHash", + params: [hash2] + }, { dedupe: true }); + } else if (blockHash) { + transaction = await client.request({ + method: "eth_getTransactionByBlockHashAndIndex", + params: [blockHash, numberToHex(index2)] + }, { dedupe: true }); + } else if (blockNumberHex || blockTag) { + transaction = await client.request({ + method: "eth_getTransactionByBlockNumberAndIndex", + params: [blockNumberHex || blockTag, numberToHex(index2)] + }, { dedupe: Boolean(blockNumberHex) }); + } + if (!transaction) + throw new TransactionNotFoundError({ + blockHash, + blockNumber, + blockTag, + hash: hash2, + index: index2 + }); + const format = client.chain?.formatters?.transaction?.format || formatTransaction; + return format(transaction); } -// node_modules/viem/_esm/actions/wallet/sendTransaction.js -init_extract(); -init_transactionRequest(); -init_lru(); -init_assertRequest(); +// node_modules/viem/_esm/actions/public/getTransactionConfirmations.js +async function getTransactionConfirmations(client, { hash: hash2, transactionReceipt }) { + const [blockNumber, transaction] = await Promise.all([ + getAction(client, getBlockNumber, "getBlockNumber")({}), + hash2 ? getAction(client, getTransaction, "getTransaction")({ hash: hash2 }) : void 0 + ]); + const transactionBlockNumber = transactionReceipt?.blockNumber || transaction?.blockNumber; + if (!transactionBlockNumber) + return 0n; + return blockNumber - transactionBlockNumber + 1n; +} -// node_modules/viem/_esm/actions/wallet/sendRawTransaction.js -async function sendRawTransaction(client, { serializedTransaction }) { - return client.request({ - method: "eth_sendRawTransaction", - params: [serializedTransaction] - }, { retryCount: 0 }); +// node_modules/viem/_esm/actions/public/getTransactionReceipt.js +init_transaction(); +async function getTransactionReceipt(client, { hash: hash2 }) { + const receipt = await client.request({ + method: "eth_getTransactionReceipt", + params: [hash2] + }, { dedupe: true }); + if (!receipt) + throw new TransactionReceiptNotFoundError({ hash: hash2 }); + const format = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt; + return format(receipt); } -// node_modules/viem/_esm/actions/wallet/sendTransaction.js -var supportsWalletNamespace = new LruMap(128); -async function sendTransaction(client, parameters) { - const { account: account_ = client.account, chain = client.chain, accessList, authorizationList, blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, ...rest } = parameters; - if (typeof account_ === "undefined") - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/sendTransaction" +// node_modules/viem/_esm/actions/public/multicall.js +init_abis(); +init_abi(); +init_base(); +init_contract(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_getChainContractAddress(); +async function multicall(client, parameters) { + const { allowFailure = true, batchSize: batchSize_, blockNumber, blockTag, multicallAddress: multicallAddress_, stateOverride } = parameters; + const contracts = parameters.contracts; + const batchSize = batchSize_ ?? (typeof client.batch?.multicall === "object" && client.batch.multicall.batchSize || 1024); + let multicallAddress = multicallAddress_; + if (!multicallAddress) { + if (!client.chain) + throw new Error("client chain not configured. multicallAddress is required."); + multicallAddress = getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "multicall3" }); - const account = account_ ? parseAccount(account_) : null; - try { - assertRequest(parameters); - const to2 = await (async () => { - if (parameters.to) - return parameters.to; - if (parameters.to === null) - return void 0; - if (authorizationList && authorizationList.length > 0) - return await recoverAuthorizationAddress({ - authorization: authorizationList[0] - }).catch(() => { - throw new BaseError2("`to` is required. Could not infer from `authorizationList`."); - }); - return void 0; - })(); - if (account?.type === "json-rpc" || account === null) { - let chainId; - if (chain !== null) { - chainId = await getAction(client, getChainId, "getChainId")({}); - assertCurrentChain({ - currentChainId: chainId, - chain - }); + } + const chunkedCalls = [[]]; + let currentChunk = 0; + let currentChunkSize = 0; + for (let i = 0; i < contracts.length; i++) { + const { abi: abi4, address, args, functionName } = contracts[i]; + try { + const callData = encodeFunctionData({ abi: abi4, args, functionName }); + currentChunkSize += (callData.length - 2) / 2; + if ( + // Check if batching is enabled. + batchSize > 0 && // Check if the current size of the batch exceeds the size limit. + currentChunkSize > batchSize && // Check if the current chunk is not already empty. + chunkedCalls[currentChunk].length > 0 + ) { + currentChunk++; + currentChunkSize = (callData.length - 2) / 2; + chunkedCalls[currentChunk] = []; } - const chainFormat = client.chain?.formatters?.transactionRequest?.format; - const format = chainFormat || formatTransactionRequest; - const request = format({ - // Pick out extra data that might exist on the chain's transaction request type. - ...extract(rest, { format: chainFormat }), - accessList, - authorizationList, - blobs, - chainId, - data, - from: account?.address, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to: to2, - value - }); - const isWalletNamespaceSupported = supportsWalletNamespace.get(client.uid); - const method = isWalletNamespaceSupported ? "wallet_sendTransaction" : "eth_sendTransaction"; - try { - return await client.request({ - method, - params: [request] - }, { retryCount: 0 }); - } catch (e) { - if (isWalletNamespaceSupported === false) - throw e; - const error = e; - if (error.name === "InvalidInputRpcError" || error.name === "InvalidParamsRpcError" || error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError") { - return await client.request({ - method: "wallet_sendTransaction", - params: [request] - }, { retryCount: 0 }).then((hash2) => { - supportsWalletNamespace.set(client.uid, true); - return hash2; - }).catch((e2) => { - const walletNamespaceError = e2; - if (walletNamespaceError.name === "MethodNotFoundRpcError" || walletNamespaceError.name === "MethodNotSupportedRpcError") { - supportsWalletNamespace.set(client.uid, false); - throw error; - } - throw walletNamespaceError; - }); + chunkedCalls[currentChunk] = [ + ...chunkedCalls[currentChunk], + { + allowFailure: true, + callData, + target: address } + ]; + } catch (err) { + const error = getContractError(err, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/multicall", + functionName + }); + if (!allowFailure) throw error; + chunkedCalls[currentChunk] = [ + ...chunkedCalls[currentChunk], + { + allowFailure: true, + callData: "0x", + target: address + } + ]; + } + } + const aggregate3Results = await Promise.allSettled(chunkedCalls.map((calls) => getAction(client, readContract, "readContract")({ + abi: multicall3Abi, + address: multicallAddress, + args: [calls], + blockNumber, + blockTag, + functionName: "aggregate3", + stateOverride + }))); + const results = []; + for (let i = 0; i < aggregate3Results.length; i++) { + const result = aggregate3Results[i]; + if (result.status === "rejected") { + if (!allowFailure) + throw result.reason; + for (let j2 = 0; j2 < chunkedCalls[i].length; j2++) { + results.push({ + status: "failure", + error: result.reason, + result: void 0 + }); } + continue; } - if (account?.type === "local") { - const request = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({ - account, - accessList, - authorizationList, - blobs, - chain, - data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - nonceManager: account.nonceManager, - parameters: [...defaultParameters, "sidecars"], - value, - ...rest, - to: to2 - }); - const serializer = chain?.serializers?.transaction; - const serializedTransaction = await account.signTransaction(request, { - serializer - }); - return await getAction(client, sendRawTransaction, "sendRawTransaction")({ - serializedTransaction - }); + const aggregate3Result = result.value; + for (let j2 = 0; j2 < aggregate3Result.length; j2++) { + const { returnData, success } = aggregate3Result[j2]; + const { callData } = chunkedCalls[i][j2]; + const { abi: abi4, address, functionName, args } = contracts[results.length]; + try { + if (callData === "0x") + throw new AbiDecodingZeroDataError(); + if (!success) + throw new RawContractError({ data: returnData }); + const result2 = decodeFunctionResult({ + abi: abi4, + args, + data: returnData, + functionName + }); + results.push(allowFailure ? { result: result2, status: "success" } : result2); + } catch (err) { + const error = getContractError(err, { + abi: abi4, + address, + args, + docsPath: "/docs/contract/multicall", + functionName + }); + if (!allowFailure) + throw error; + results.push({ error, result: void 0, status: "failure" }); + } } - if (account?.type === "smart") - throw new AccountTypeNotSupportedError({ - metaMessages: [ - "Consider using the `sendUserOperation` Action instead." - ], - docsPath: "/docs/actions/bundler/sendUserOperation", - type: "smart" - }); - throw new AccountTypeNotSupportedError({ - docsPath: "/docs/actions/wallet/sendTransaction", - type: account?.type + } + if (results.length !== contracts.length) + throw new BaseError2("multicall results mismatch"); + return results; +} + +// node_modules/ox/_esm/core/version.js +var version3 = "0.1.1"; + +// node_modules/ox/_esm/core/internal/errors.js +function getVersion() { + return version3; +} + +// node_modules/ox/_esm/core/Errors.js +var BaseError3 = class _BaseError extends Error { + constructor(shortMessage, options = {}) { + const details = (() => { + if (options.cause instanceof _BaseError) { + if (options.cause.details) + return options.cause.details; + if (options.cause.shortMessage) + return options.cause.shortMessage; + } + if (options.cause?.message) + return options.cause.message; + return options.details; + })(); + const docsPath6 = (() => { + if (options.cause instanceof _BaseError) + return options.cause.docsPath || options.docsPath; + return options.docsPath; + })(); + const docsBaseUrl = "https://oxlib.sh"; + const docs = `${docsBaseUrl}${docsPath6 ?? ""}`; + const message = [ + shortMessage || "An error occurred.", + ...options.metaMessages ? ["", ...options.metaMessages] : [], + ...details || docsPath6 ? [ + "", + details ? `Details: ${details}` : void 0, + docsPath6 ? `See: ${docs}` : void 0 + ] : [] + ].filter((x2) => typeof x2 === "string").join("\n"); + super(message, options.cause ? { cause: options.cause } : void 0); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - } catch (err) { - if (err instanceof AccountTypeNotSupportedError) - throw err; - throw getTransactionError(err, { - ...parameters, - account, - chain: parameters.chain || void 0 + Object.defineProperty(this, "docs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "docsPath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "shortMessage", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "BaseError" + }); + Object.defineProperty(this, "version", { + enumerable: true, + configurable: true, + writable: true, + value: `ox@${getVersion()}` }); + this.cause = options.cause; + this.details = details; + this.docs = docs; + this.docsPath = docsPath6; + this.shortMessage = shortMessage; + } + walk(fn2) { + return walk2(this, fn2); } +}; +function walk2(err, fn2) { + if (fn2?.(err)) + return err; + if (err && typeof err === "object" && "cause" in err && err.cause) + return walk2(err.cause, fn2); + return fn2 ? null : err; } -// node_modules/viem/_esm/actions/wallet/writeContract.js -async function writeContract(client, parameters) { - const { abi: abi4, account: account_ = client.account, address, args, dataSuffix, functionName, ...request } = parameters; - if (typeof account_ === "undefined") - throw new AccountNotFoundError({ - docsPath: "/docs/contract/writeContract" - }); - const account = account_ ? parseAccount(account_) : null; - const data = encodeFunctionData({ - abi: abi4, - args, - functionName - }); - try { - return await getAction(client, sendTransaction, "sendTransaction")({ - data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, - to: address, - account, - ...request +// node_modules/ox/_esm/core/Json.js +var bigIntSuffix = "#__bigint"; +function stringify2(value, replacer, space) { + return JSON.stringify(value, (key, value2) => { + if (typeof replacer === "function") + return replacer(key, value2); + if (typeof value2 === "bigint") + return value2.toString() + bigIntSuffix; + return value2; + }, space); +} + +// node_modules/ox/_esm/core/internal/bytes.js +function assertSize2(bytes, size_) { + if (size3(bytes) > size_) + throw new SizeOverflowError2({ + givenSize: size3(bytes), + maxSize: size_ }); - } catch (error) { - throw getContractError(error, { - abi: abi4, - address, - args, - docsPath: "/docs/contract/writeContract", - functionName, - sender: account?.address +} +var charCodeMap2 = { + zero: 48, + nine: 57, + A: 65, + F: 70, + a: 97, + f: 102 +}; +function charCodeToBase162(char) { + if (char >= charCodeMap2.zero && char <= charCodeMap2.nine) + return char - charCodeMap2.zero; + if (char >= charCodeMap2.A && char <= charCodeMap2.F) + return char - (charCodeMap2.A - 10); + if (char >= charCodeMap2.a && char <= charCodeMap2.f) + return char - (charCodeMap2.a - 10); + return void 0; +} +function pad2(bytes, options = {}) { + const { dir, size: size5 = 32 } = options; + if (size5 === 0) + return bytes; + if (bytes.length > size5) + throw new SizeExceedsPaddingSizeError2({ + size: bytes.length, + targetSize: size5, + type: "Bytes" }); + const paddedBytes = new Uint8Array(size5); + for (let i = 0; i < size5; i++) { + const padEnd = dir === "right"; + paddedBytes[padEnd ? i : size5 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; } + return paddedBytes; } -// node_modules/viem/_esm/errors/eip712.js -init_base(); -var Eip712DomainNotFoundError = class extends BaseError2 { - constructor({ address }) { - super(`No EIP-712 domain found on contract "${address}".`, { - metaMessages: [ - "Ensure that:", - `- The contract is deployed at the address "${address}".`, - "- `eip712Domain()` function exists on the contract.", - "- `eip712Domain()` function matches signature to ERC-5267 specification." - ], - name: "Eip712DomainNotFoundError" +// node_modules/ox/_esm/core/internal/hex.js +function assertSize3(hex, size_) { + if (size4(hex) > size_) + throw new SizeOverflowError3({ + givenSize: size4(hex), + maxSize: size_ }); - } -}; - -// node_modules/viem/_esm/actions/public/getEip712Domain.js -async function getEip712Domain(client, parameters) { - const { address, factory, factoryData } = parameters; - try { - const [fields, name, version4, chainId, verifyingContract, salt, extensions] = await getAction(client, readContract, "readContract")({ - abi: abi3, - address, - functionName: "eip712Domain", - factory, - factoryData +} +function assertStartOffset2(value, start) { + if (typeof start === "number" && start > 0 && start > size4(value) - 1) + throw new SliceOffsetOutOfBoundsError3({ + offset: start, + position: "start", + size: size4(value) }); - return { - domain: { - name, - version: version4, - chainId: Number(chainId), - verifyingContract, - salt - }, - extensions, - fields - }; - } catch (e) { - const error = e; - if (error.name === "ContractFunctionExecutionError" && error.cause.name === "ContractFunctionZeroDataError") { - throw new Eip712DomainNotFoundError({ address }); - } - throw error; - } } -var abi3 = [ - { - inputs: [], - name: "eip712Domain", - outputs: [ - { name: "fields", type: "bytes1" }, - { name: "name", type: "string" }, - { name: "version", type: "string" }, - { name: "chainId", type: "uint256" }, - { name: "verifyingContract", type: "address" }, - { name: "salt", type: "bytes32" }, - { name: "extensions", type: "uint256[]" } - ], - stateMutability: "view", - type: "function" +function assertEndOffset2(value, start, end) { + if (typeof start === "number" && typeof end === "number" && size4(value) !== end - start) { + throw new SliceOffsetOutOfBoundsError3({ + offset: end, + position: "end", + size: size4(value) + }); } -]; - -// node_modules/viem/_esm/actions/wallet/addChain.js -init_toHex(); -async function addChain(client, { chain }) { - const { id: id2, name, nativeCurrency, rpcUrls, blockExplorers } = chain; - await client.request({ - method: "wallet_addEthereumChain", - params: [ - { - chainId: numberToHex(id2), - chainName: name, - nativeCurrency, - rpcUrls: rpcUrls.default.http, - blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url: url2 }) => url2) : void 0 - } - ] - }, { dedupe: true, retryCount: 0 }); +} +function pad3(hex_, options = {}) { + const { dir, size: size5 = 32 } = options; + if (size5 === 0) + return hex_; + const hex = hex_.replace("0x", ""); + if (hex.length > size5 * 2) + throw new SizeExceedsPaddingSizeError3({ + size: Math.ceil(hex.length / 2), + targetSize: size5, + type: "Hex" + }); + return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`; } -// node_modules/viem/_esm/clients/createClient.js -init_parseAccount(); - -// node_modules/viem/_esm/utils/uid.js -var size2 = 256; -var index = size2; -var buffer; -function uid(length = 11) { - if (!buffer || index + length > size2 * 2) { - buffer = ""; - index = 0; - for (let i = 0; i < size2; i++) { - buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1); +// node_modules/ox/_esm/core/Bytes.js +var encoder3 = /* @__PURE__ */ new TextEncoder(); +function from(value) { + if (value instanceof Uint8Array) + return value; + if (typeof value === "string") + return fromHex2(value); + return fromArray(value); +} +function fromArray(value) { + return value instanceof Uint8Array ? value : new Uint8Array(value); +} +function fromHex2(value, options = {}) { + const { size: size5 } = options; + let hex = value; + if (size5) { + assertSize3(value, size5); + hex = padRight(value, size5); + } + let hexString = hex.slice(2); + if (hexString.length % 2) + hexString = `0${hexString}`; + const length = hexString.length / 2; + const bytes = new Uint8Array(length); + for (let index2 = 0, j2 = 0; index2 < length; index2++) { + const nibbleLeft = charCodeToBase162(hexString.charCodeAt(j2++)); + const nibbleRight = charCodeToBase162(hexString.charCodeAt(j2++)); + if (nibbleLeft === void 0 || nibbleRight === void 0) { + throw new BaseError3(`Invalid byte sequence ("${hexString[j2 - 2]}${hexString[j2 - 1]}" in "${hexString}").`); } + bytes[index2] = nibbleLeft * 16 + nibbleRight; } - return buffer.substring(index, index++ + length); + return bytes; } - -// node_modules/viem/_esm/clients/createClient.js -function createClient(parameters) { - const { batch, cacheTime = parameters.pollingInterval ?? 4e3, ccipRead, key = "base", name = "Base Client", pollingInterval = 4e3, type = "base" } = parameters; - const chain = parameters.chain; - const account = parameters.account ? parseAccount(parameters.account) : void 0; - const { config: config3, request, value } = parameters.transport({ - chain, - pollingInterval - }); - const transport = { ...config3, ...value }; - const client = { - account, - batch, - cacheTime, - ccipRead, - chain, - key, - name, - pollingInterval, - request, - transport, - type, - uid: uid() - }; - function extend2(base) { - return (extendFn) => { - const extended = extendFn(base); - for (const key2 in client) - delete extended[key2]; - const combined = { ...base, ...extended }; - return Object.assign(combined, { extend: extend2(combined) }); - }; +function fromString(value, options = {}) { + const { size: size5 } = options; + const bytes = encoder3.encode(value); + if (typeof size5 === "number") { + assertSize2(bytes, size5); + return padRight2(bytes, size5); } - return Object.assign(client, { extend: extend2(client) }); -} - -// node_modules/viem/_esm/utils/buildRequest.js -init_base(); -init_request(); -init_rpc(); -init_toHex(); - -// node_modules/viem/_esm/utils/promise/withDedupe.js -init_lru(); -var promiseCache2 = /* @__PURE__ */ new LruMap(8192); -function withDedupe(fn2, { enabled = true, id: id2 }) { - if (!enabled || !id2) - return fn2(); - if (promiseCache2.get(id2)) - return promiseCache2.get(id2); - const promise = fn2().finally(() => promiseCache2.delete(id2)); - promiseCache2.set(id2, promise); - return promise; + return bytes; } - -// node_modules/viem/_esm/utils/promise/withRetry.js -function withRetry(fn2, { delay: delay_ = 100, retryCount = 2, shouldRetry: shouldRetry2 = () => true } = {}) { - return new Promise((resolve, reject) => { - const attemptRetry = async ({ count = 0 } = {}) => { - const retry = async ({ error }) => { - const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_; - if (delay) - await wait(delay); - attemptRetry({ count: count + 1 }); - }; - try { - const data = await fn2(); - resolve(data); - } catch (err) { - if (count < retryCount && await shouldRetry2({ count, error: err })) - return retry({ error: err }); - reject(err); - } - }; - attemptRetry(); - }); +function padRight2(value, size5) { + return pad2(value, { dir: "right", size: size5 }); } - -// node_modules/viem/_esm/utils/buildRequest.js -init_stringify(); -function buildRequest(request, options = {}) { - return async (args, overrideOptions = {}) => { - const { dedupe = false, methods, retryDelay = 150, retryCount = 3, uid: uid2 } = { - ...options, - ...overrideOptions - }; - const { method } = args; - if (methods?.exclude?.includes(method)) - throw new MethodNotSupportedRpcError(new Error("method not supported"), { - method - }); - if (methods?.include && !methods.include.includes(method)) - throw new MethodNotSupportedRpcError(new Error("method not supported"), { - method - }); - const requestId = dedupe ? stringToHex(`${uid2}.${stringify(args)}`) : void 0; - return withDedupe(() => withRetry(async () => { - try { - return await request(args); - } catch (err_) { - const err = err_; - switch (err.code) { - // -32700 - case ParseRpcError.code: - throw new ParseRpcError(err); - // -32600 - case InvalidRequestRpcError.code: - throw new InvalidRequestRpcError(err); - // -32601 - case MethodNotFoundRpcError.code: - throw new MethodNotFoundRpcError(err, { method: args.method }); - // -32602 - case InvalidParamsRpcError.code: - throw new InvalidParamsRpcError(err); - // -32603 - case InternalRpcError.code: - throw new InternalRpcError(err); - // -32000 - case InvalidInputRpcError.code: - throw new InvalidInputRpcError(err); - // -32001 - case ResourceNotFoundRpcError.code: - throw new ResourceNotFoundRpcError(err); - // -32002 - case ResourceUnavailableRpcError.code: - throw new ResourceUnavailableRpcError(err); - // -32003 - case TransactionRejectedRpcError.code: - throw new TransactionRejectedRpcError(err); - // -32004 - case MethodNotSupportedRpcError.code: - throw new MethodNotSupportedRpcError(err, { - method: args.method - }); - // -32005 - case LimitExceededRpcError.code: - throw new LimitExceededRpcError(err); - // -32006 - case JsonRpcVersionUnsupportedError.code: - throw new JsonRpcVersionUnsupportedError(err); - // 4001 - case UserRejectedRequestError.code: - throw new UserRejectedRequestError(err); - // 4100 - case UnauthorizedProviderError.code: - throw new UnauthorizedProviderError(err); - // 4200 - case UnsupportedProviderMethodError.code: - throw new UnsupportedProviderMethodError(err); - // 4900 - case ProviderDisconnectedError.code: - throw new ProviderDisconnectedError(err); - // 4901 - case ChainDisconnectedError.code: - throw new ChainDisconnectedError(err); - // 4902 - case SwitchChainError.code: - throw new SwitchChainError(err); - // CAIP-25: User Rejected Error - // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25 - case 5e3: - throw new UserRejectedRequestError(err); - default: - if (err_ instanceof BaseError2) - throw err_; - throw new UnknownRpcError(err); - } - } - }, { - delay: ({ count, error }) => { - if (error && error instanceof HttpRequestError) { - const retryAfter = error?.headers?.get("Retry-After"); - if (retryAfter?.match(/\d/)) - return Number.parseInt(retryAfter) * 1e3; - } - return ~~(1 << count) * retryDelay; - }, - retryCount, - shouldRetry: ({ error }) => shouldRetry(error) - }), { enabled: dedupe, id: requestId }); - }; +function size3(value) { + return value.length; } -function shouldRetry(error) { - if ("code" in error && typeof error.code === "number") { - if (error.code === -1) - return true; - if (error.code === LimitExceededRpcError.code) - return true; - if (error.code === InternalRpcError.code) - return true; - return false; +var SizeOverflowError2 = class extends BaseError3 { + constructor({ givenSize, maxSize }) { + super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Bytes.SizeOverflowError" + }); } - if (error instanceof HttpRequestError && error.status) { - if (error.status === 403) - return true; - if (error.status === 408) - return true; - if (error.status === 413) - return true; - if (error.status === 429) - return true; - if (error.status === 500) - return true; - if (error.status === 502) - return true; - if (error.status === 503) - return true; - if (error.status === 504) - return true; - return false; +}; +var SizeExceedsPaddingSizeError2 = class extends BaseError3 { + constructor({ size: size5, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Bytes.SizeExceedsPaddingSizeError" + }); } - return true; -} - -// node_modules/viem/_esm/clients/transports/createTransport.js -function createTransport({ key, methods, name, request, retryCount = 3, retryDelay = 150, timeout, type }, value) { - const uid2 = uid(); - return { - config: { - key, - methods, - name, - request, - retryCount, - retryDelay, - timeout, - type - }, - request: buildRequest(request, { methods, retryCount, retryDelay, uid: uid2 }), - value - }; -} +}; -// node_modules/viem/_esm/clients/transports/fallback.js -init_node(); -init_rpc(); -function fallback(transports_, config3 = {}) { - const { key = "fallback", name = "Fallback", rank = false, shouldThrow: shouldThrow_ = shouldThrow, retryCount, retryDelay } = config3; - return ({ chain, pollingInterval = 4e3, timeout, ...rest }) => { - let transports = transports_; - let onResponse = () => { - }; - const transport = createTransport({ - key, - name, - async request({ method, params }) { - let includes; - const fetch2 = async (i = 0) => { - const transport2 = transports[i]({ - ...rest, - chain, - retryCount: 0, - timeout - }); - try { - const response = await transport2.request({ - method, - params - }); - onResponse({ - method, - params, - response, - transport: transport2, - status: "success" - }); - return response; - } catch (err) { - onResponse({ - error: err, - method, - params, - transport: transport2, - status: "error" - }); - if (shouldThrow_(err)) - throw err; - if (i === transports.length - 1) - throw err; - includes ??= transports.slice(i + 1).some((transport3) => { - const { include, exclude } = transport3({ chain }).config.methods || {}; - if (include) - return include.includes(method); - if (exclude) - return !exclude.includes(method); - return true; - }); - if (!includes) - throw err; - return fetch2(i + 1); - } - }; - return fetch2(); - }, - retryCount, - retryDelay, - type: "fallback" - }, { - onResponse: (fn2) => onResponse = fn2, - transports: transports.map((fn2) => fn2({ chain, retryCount: 0 })) - }); - if (rank) { - const rankOptions = typeof rank === "object" ? rank : {}; - rankTransports({ - chain, - interval: rankOptions.interval ?? pollingInterval, - onTransports: (transports_2) => transports = transports_2, - ping: rankOptions.ping, - sampleCount: rankOptions.sampleCount, - timeout: rankOptions.timeout, - transports, - weights: rankOptions.weights - }); - } - return transport; - }; +// node_modules/ox/_esm/core/Hex.js +var encoder4 = /* @__PURE__ */ new TextEncoder(); +var hexes3 = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); +function assert(value, options = {}) { + const { strict = false } = options; + if (!value) + throw new InvalidHexTypeError(value); + if (typeof value !== "string") + throw new InvalidHexTypeError(value); + if (strict) { + if (!/^0x[0-9a-fA-F]*$/.test(value)) + throw new InvalidHexValueError(value); + } + if (!value.startsWith("0x")) + throw new InvalidHexValueError(value); } -function shouldThrow(error) { - if ("code" in error && typeof error.code === "number") { - if (error.code === TransactionRejectedRpcError.code || error.code === UserRejectedRequestError.code || ExecutionRevertedError.nodeMessage.test(error.message) || error.code === 5e3) - return true; +function concat2(...values) { + return `0x${values.reduce((acc, x2) => acc + x2.replace("0x", ""), "")}`; +} +function fromBoolean(value, options = {}) { + const hex = `0x${Number(value)}`; + if (typeof options.size === "number") { + assertSize3(hex, options.size); + return padLeft(hex, options.size); } - return false; + return hex; } -function rankTransports({ chain, interval = 4e3, onTransports, ping, sampleCount = 10, timeout = 1e3, transports, weights = {} }) { - const { stability: stabilityWeight = 0.7, latency: latencyWeight = 0.3 } = weights; - const samples = []; - const rankTransports_ = async () => { - const sample = await Promise.all(transports.map(async (transport) => { - const transport_ = transport({ chain, retryCount: 0, timeout }); - const start = Date.now(); - let end; - let success; - try { - await (ping ? ping({ transport: transport_ }) : transport_.request({ method: "net_listening" })); - success = 1; - } catch { - success = 0; - } finally { - end = Date.now(); - } - const latency = end - start; - return { latency, success }; - })); - samples.push(sample); - if (samples.length > sampleCount) - samples.shift(); - const maxLatency = Math.max(...samples.map((sample2) => Math.max(...sample2.map(({ latency }) => latency)))); - const scores = transports.map((_, i) => { - const latencies = samples.map((sample2) => sample2[i].latency); - const meanLatency = latencies.reduce((acc, latency) => acc + latency, 0) / latencies.length; - const latencyScore = 1 - meanLatency / maxLatency; - const successes = samples.map((sample2) => sample2[i].success); - const stabilityScore = successes.reduce((acc, success) => acc + success, 0) / successes.length; - if (stabilityScore === 0) - return [0, i]; - return [ - latencyWeight * latencyScore + stabilityWeight * stabilityScore, - i - ]; - }).sort((a, b2) => b2[0] - a[0]); - onTransports(scores.map(([, i]) => transports[i])); - await wait(interval); - rankTransports_(); - }; - rankTransports_(); +function fromBytes(value, options = {}) { + let string = ""; + for (let i = 0; i < value.length; i++) + string += hexes3[value[i]]; + const hex = `0x${string}`; + if (typeof options.size === "number") { + assertSize3(hex, options.size); + return padRight(hex, options.size); + } + return hex; } - -// node_modules/viem/_esm/clients/transports/http.js -init_request(); - -// node_modules/viem/_esm/errors/transport.js -init_base(); -var UrlRequiredError = class extends BaseError2 { - constructor() { - super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.", { - docsPath: "/docs/clients/intro", - name: "UrlRequiredError" +function fromNumber(value, options = {}) { + const { signed, size: size5 } = options; + const value_ = BigInt(value); + let maxValue; + if (size5) { + if (signed) + maxValue = (1n << BigInt(size5) * 8n - 1n) - 1n; + else + maxValue = 2n ** (BigInt(size5) * 8n) - 1n; + } else if (typeof value === "number") { + maxValue = BigInt(Number.MAX_SAFE_INTEGER); + } + const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0; + if (maxValue && value_ > maxValue || value_ < minValue) { + const suffix = typeof value === "bigint" ? "n" : ""; + throw new IntegerOutOfRangeError2({ + max: maxValue ? `${maxValue}${suffix}` : void 0, + min: `${minValue}${suffix}`, + signed, + size: size5, + value: `${value}${suffix}` }); } -}; - -// node_modules/viem/_esm/clients/transports/http.js -init_createBatchScheduler(); - -// node_modules/viem/_esm/utils/rpc/http.js -init_request(); - -// node_modules/viem/_esm/utils/promise/withTimeout.js -function withTimeout(fn2, { errorInstance = new Error("timed out"), timeout, signal }) { - return new Promise((resolve, reject) => { - ; - (async () => { - let timeoutId; - try { - const controller = new AbortController(); - if (timeout > 0) { - timeoutId = setTimeout(() => { - if (signal) { - controller.abort(); - } else { - reject(errorInstance); - } - }, timeout); - } - resolve(await fn2({ signal: controller?.signal || null })); - } catch (err) { - if (err?.name === "AbortError") - reject(errorInstance); - reject(err); - } finally { - clearTimeout(timeoutId); - } - })(); - }); + const stringValue = (signed && value_ < 0 ? (1n << BigInt(size5 * 8)) + BigInt(value_) : value_).toString(16); + const hex = `0x${stringValue}`; + if (size5) + return padLeft(hex, size5); + return hex; } +function fromString2(value, options = {}) { + return fromBytes(encoder4.encode(value), options); +} +function padLeft(value, size5) { + return pad3(value, { dir: "left", size: size5 }); +} +function padRight(value, size5) { + return pad3(value, { dir: "right", size: size5 }); +} +function slice2(value, start, end, options = {}) { + const { strict } = options; + assertStartOffset2(value, start); + const value_ = `0x${value.replace("0x", "").slice((start ?? 0) * 2, (end ?? value.length) * 2)}`; + if (strict) + assertEndOffset2(value_, start, end); + return value_; +} +function size4(value) { + return Math.ceil((value.length - 2) / 2); +} +function validate(value, options = {}) { + const { strict = false } = options; + try { + assert(value, { strict }); + return true; + } catch { + return false; + } +} +var IntegerOutOfRangeError2 = class extends BaseError3 { + constructor({ max, min, signed, size: size5, value }) { + super(`Number \`${value}\` is not in safe${size5 ? ` ${size5 * 8}-bit` : ""}${signed ? " signed" : " unsigned"} integer range ${max ? `(\`${min}\` to \`${max}\`)` : `(above \`${min}\`)`}`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.IntegerOutOfRangeError" + }); + } +}; +var InvalidHexTypeError = class extends BaseError3 { + constructor(value) { + super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid hex type.`, { + metaMessages: ['Hex types must be represented as `"0x${string}"`.'] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.InvalidHexTypeError" + }); + } +}; +var InvalidHexValueError = class extends BaseError3 { + constructor(value) { + super(`Value \`${value}\` is an invalid hex value.`, { + metaMessages: [ + 'Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).' + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.InvalidHexValueError" + }); + } +}; +var SizeOverflowError3 = class extends BaseError3 { + constructor({ givenSize, maxSize }) { + super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.SizeOverflowError" + }); + } +}; +var SliceOffsetOutOfBoundsError3 = class extends BaseError3 { + constructor({ offset, position, size: size5 }) { + super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size5}\`).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.SliceOffsetOutOfBoundsError" + }); + } +}; +var SizeExceedsPaddingSizeError3 = class extends BaseError3 { + constructor({ size: size5, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.SizeExceedsPaddingSizeError" + }); + } +}; -// node_modules/viem/_esm/utils/rpc/http.js -init_stringify(); - -// node_modules/viem/_esm/utils/rpc/id.js -function createIdStore() { +// node_modules/ox/_esm/core/Withdrawal.js +function toRpc(withdrawal) { return { - current: 0, - take() { - return this.current++; - }, - reset() { - this.current = 0; - } + address: withdrawal.address, + amount: fromNumber(withdrawal.amount), + index: fromNumber(withdrawal.index), + validatorIndex: fromNumber(withdrawal.validatorIndex) }; } -var idCache = /* @__PURE__ */ createIdStore(); -// node_modules/viem/_esm/utils/rpc/http.js -function getHttpRpcClient(url2, options = {}) { +// node_modules/ox/_esm/core/BlockOverrides.js +function toRpc2(blockOverrides) { return { - async request(params) { - const { body, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 1e4 } = params; - const fetchOptions = { - ...options.fetchOptions ?? {}, - ...params.fetchOptions ?? {} - }; - const { headers, method, signal: signal_ } = fetchOptions; - try { - const response = await withTimeout(async ({ signal }) => { - const init = { - ...fetchOptions, - body: Array.isArray(body) ? stringify(body.map((body2) => ({ - jsonrpc: "2.0", - id: body2.id ?? idCache.take(), - ...body2 - }))) : stringify({ - jsonrpc: "2.0", - id: body.id ?? idCache.take(), - ...body - }), - headers: { - "Content-Type": "application/json", - ...headers - }, - method: method || "POST", - signal: signal_ || (timeout > 0 ? signal : null) - }; - const request = new Request(url2, init); - const args = await onRequest?.(request, init) ?? { ...init, url: url2 }; - const response2 = await fetch(args.url ?? url2, args); - return response2; - }, { - errorInstance: new TimeoutError({ body, url: url2 }), - timeout, - signal: true - }); - if (onResponse) - await onResponse(response); - let data; - if (response.headers.get("Content-Type")?.startsWith("application/json")) - data = await response.json(); - else { - data = await response.text(); - try { - data = JSON.parse(data || "{}"); - } catch (err) { - if (response.ok) - throw err; - data = { error: data }; - } - } - if (!response.ok) { - throw new HttpRequestError({ - body, - details: stringify(data.error) || response.statusText, - headers: response.headers, - status: response.status, - url: url2 - }); - } - return data; - } catch (err) { - if (err instanceof HttpRequestError) - throw err; - if (err instanceof TimeoutError) - throw err; - throw new HttpRequestError({ - body, - cause: err, - url: url2 - }); - } + ...typeof blockOverrides.baseFeePerGas === "bigint" && { + baseFeePerGas: fromNumber(blockOverrides.baseFeePerGas) + }, + ...typeof blockOverrides.blobBaseFee === "bigint" && { + blobBaseFee: fromNumber(blockOverrides.blobBaseFee) + }, + ...typeof blockOverrides.feeRecipient === "string" && { + feeRecipient: blockOverrides.feeRecipient + }, + ...typeof blockOverrides.gasLimit === "bigint" && { + gasLimit: fromNumber(blockOverrides.gasLimit) + }, + ...typeof blockOverrides.number === "bigint" && { + number: fromNumber(blockOverrides.number) + }, + ...typeof blockOverrides.prevRandao === "bigint" && { + prevRandao: fromNumber(blockOverrides.prevRandao) + }, + ...typeof blockOverrides.time === "bigint" && { + time: fromNumber(blockOverrides.time) + }, + ...blockOverrides.withdrawals && { + withdrawals: blockOverrides.withdrawals.map(toRpc) } }; } -// node_modules/viem/_esm/clients/transports/http.js -function http2(url2, config3 = {}) { - const { batch, fetchOptions, key = "http", methods, name = "HTTP JSON-RPC", onFetchRequest, onFetchResponse, retryDelay, raw: raw2 } = config3; - return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => { - const { batchSize = 1e3, wait: wait2 = 0 } = typeof batch === "object" ? batch : {}; - const retryCount = config3.retryCount ?? retryCount_; - const timeout = timeout_ ?? config3.timeout ?? 1e4; - const url_ = url2 || chain?.rpcUrls.default.http[0]; - if (!url_) - throw new UrlRequiredError(); - const rpcClient = getHttpRpcClient(url_, { - fetchOptions, - onRequest: onFetchRequest, - onResponse: onFetchResponse, - timeout - }); - return createTransport({ - key, - methods, - name, - async request({ method, params }) { - const body = { method, params }; - const { schedule } = createBatchScheduler({ - id: url_, - wait: wait2, - shouldSplitBatch(requests) { - return requests.length > batchSize; - }, - fn: (body2) => rpcClient.request({ - body: body2 - }), - sort: (a, b2) => a.id - b2.id - }); - const fn2 = async (body2) => batch ? schedule(body2) : [ - await rpcClient.request({ - body: body2 - }) - ]; - const [{ error, result }] = await fn2(body); - if (raw2) - return { error, result }; - if (error) - throw new RpcRequestError({ - body, - error, - url: url_ - }); - return result; - }, - retryCount, - retryDelay, - timeout, - type: "http" - }, { - fetchOptions, - url: url_ - }); - }; -} - -// node_modules/viem/_esm/actions/ens/getEnsAddress.js -init_abis(); +// node_modules/viem/_esm/actions/public/simulateBlocks.js +init_parseAccount(); +init_abi(); +init_contract(); +init_node(); init_decodeFunctionResult(); init_encodeFunctionData(); -init_getChainContractAddress(); -init_trim(); init_toHex(); - -// node_modules/viem/_esm/utils/ens/errors.js -init_solidity(); -init_base(); -init_contract(); -function isNullUniversalResolverError(err, callType) { - if (!(err instanceof BaseError2)) - return false; - const cause = err.walk((e) => e instanceof ContractFunctionRevertedError); - if (!(cause instanceof ContractFunctionRevertedError)) - return false; - if (cause.data?.errorName === "ResolverNotFound") - return true; - if (cause.data?.errorName === "ResolverWildcardNotSupported") - return true; - if (cause.data?.errorName === "ResolverNotContract") - return true; - if (cause.data?.errorName === "ResolverError") - return true; - if (cause.data?.errorName === "HttpError") - return true; - if (cause.reason?.includes("Wildcard on non-extended resolvers is not supported")) - return true; - if (callType === "reverse" && cause.reason === panicReasons[50]) - return true; - return false; +init_getNodeError(); +init_transactionRequest(); +init_stateOverride2(); +init_assertRequest(); +async function simulateBlocks(client, parameters) { + const { blockNumber, blockTag = "latest", blocks, returnFullTransactions, traceTransfers, validation } = parameters; + try { + const blockStateCalls = []; + for (const block2 of blocks) { + const blockOverrides = block2.blockOverrides ? toRpc2(block2.blockOverrides) : void 0; + const calls = block2.calls.map((call_) => { + const call2 = call_; + const account = call2.account ? parseAccount(call2.account) : void 0; + const request = { + ...call2, + data: call2.abi ? encodeFunctionData(call2) : call2.data, + from: call2.from ?? account?.address + }; + assertRequest(request); + return formatTransactionRequest(request); + }); + const stateOverrides = block2.stateOverrides ? serializeStateOverride(block2.stateOverrides) : void 0; + blockStateCalls.push({ + blockOverrides, + calls, + stateOverrides + }); + } + const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; + const block = blockNumberHex || blockTag; + const result = await client.request({ + method: "eth_simulateV1", + params: [ + { blockStateCalls, returnFullTransactions, traceTransfers, validation }, + block + ] + }); + return result.map((block2, i) => ({ + ...formatBlock(block2), + calls: block2.calls.map((call2, j2) => { + const { abi: abi4, args, functionName, to: to2 } = blocks[i].calls[j2]; + const data = call2.error?.data ?? call2.returnData; + const gasUsed = BigInt(call2.gasUsed); + const logs = call2.logs?.map((log) => formatLog(log)); + const status = call2.status === "0x1" ? "success" : "failure"; + const result2 = abi4 && status === "success" && data !== "0x" ? decodeFunctionResult({ + abi: abi4, + data, + functionName + }) : null; + const error = (() => { + if (status === "success") + return void 0; + let error2 = void 0; + if (call2.error?.data === "0x") + error2 = new AbiDecodingZeroDataError(); + else if (call2.error) + error2 = new RawContractError(call2.error); + if (!error2) + return void 0; + return getContractError(error2, { + abi: abi4 ?? [], + address: to2, + args, + functionName: functionName ?? "" + }); + })(); + return { + data, + gasUsed, + logs, + status, + ...status === "success" ? { + result: result2 + } : { + error + } + }; + }) + })); + } catch (e) { + const cause = e; + const error = getNodeError(cause, {}); + if (error instanceof UnknownNodeError) + throw cause; + throw error; + } } -// node_modules/viem/_esm/utils/ens/namehash.js -init_concat(); -init_toBytes(); -init_toHex(); -init_keccak256(); +// node_modules/ox/_esm/core/AbiItem.js +init_exports(); -// node_modules/viem/_esm/utils/ens/encodedLabelToLabelhash.js -init_isHex(); -function encodedLabelToLabelhash(label) { - if (label.length !== 66) - return null; - if (label.indexOf("[") !== 0) - return null; - if (label.indexOf("]") !== 65) - return null; - const hash2 = `0x${label.slice(1, 65)}`; - if (!isHex(hash2)) - return null; - return hash2; +// node_modules/ox/node_modules/@noble/hashes/esm/_assert.js +function anumber2(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error("positive integer expected, got " + n); +} +function isBytes3(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; +} +function abytes3(b2, ...lengths) { + if (!isBytes3(b2)) + throw new Error("Uint8Array expected"); + if (lengths.length > 0 && !lengths.includes(b2.length)) + throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b2.length); +} +function aexists2(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function aoutput2(out, instance) { + abytes3(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error("digestInto() expects output buffer of length at least " + min); + } } -// node_modules/viem/_esm/utils/ens/namehash.js -function namehash(name) { - let result = new Uint8Array(32).fill(0); - if (!name) - return bytesToHex(result); - const labels = name.split("."); - for (let i = labels.length - 1; i >= 0; i -= 1) { - const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]); - const hashed = hashFromEncodedLabel ? toBytes(hashFromEncodedLabel) : keccak256(stringToBytes(labels[i]), "bytes"); - result = keccak256(concat([result, hashed]), "bytes"); +// node_modules/ox/node_modules/@noble/hashes/esm/utils.js +function u322(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +var isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); +function byteSwap2(word) { + return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; +} +function byteSwap322(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap2(arr[i]); } - return bytesToHex(result); +} +function utf8ToBytes3(str) { + if (typeof str !== "string") + throw new Error("utf8ToBytes expected string, got " + typeof str); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes3(data) { + if (typeof data === "string") + data = utf8ToBytes3(data); + abytes3(data); + return data; +} +var Hash2 = class { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +}; +function wrapConstructor2(hashCons) { + const hashC = (msg) => hashCons().update(toBytes3(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function wrapXOFConstructorWithOpts2(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes3(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; } -// node_modules/viem/_esm/utils/ens/packetToBytes.js -init_toBytes(); +// node_modules/ox/node_modules/@noble/hashes/esm/_u64.js +var U32_MASK642 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +var _32n2 = /* @__PURE__ */ BigInt(32); +function fromBig2(n, le2 = false) { + if (le2) + return { h: Number(n & U32_MASK642), l: Number(n >> _32n2 & U32_MASK642) }; + return { h: Number(n >> _32n2 & U32_MASK642) | 0, l: Number(n & U32_MASK642) | 0 }; +} +function split2(lst, le2 = false) { + let Ah = new Uint32Array(lst.length); + let Al2 = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig2(lst[i], le2); + [Ah[i], Al2[i]] = [h, l]; + } + return [Ah, Al2]; +} +var rotlSH2 = (h, l, s) => h << s | l >>> 32 - s; +var rotlSL2 = (h, l, s) => l << s | h >>> 32 - s; +var rotlBH2 = (h, l, s) => l << s - 32 | h >>> 64 - s; +var rotlBL2 = (h, l, s) => h << s - 32 | l >>> 64 - s; -// node_modules/viem/_esm/utils/ens/encodeLabelhash.js -function encodeLabelhash(hash2) { - return `[${hash2.slice(2)}]`; +// node_modules/ox/node_modules/@noble/hashes/esm/sha3.js +var SHA3_PI2 = []; +var SHA3_ROTL2 = []; +var _SHA3_IOTA2 = []; +var _0n7 = /* @__PURE__ */ BigInt(0); +var _1n7 = /* @__PURE__ */ BigInt(1); +var _2n6 = /* @__PURE__ */ BigInt(2); +var _7n2 = /* @__PURE__ */ BigInt(7); +var _256n2 = /* @__PURE__ */ BigInt(256); +var _0x71n2 = /* @__PURE__ */ BigInt(113); +for (let round = 0, R2 = _1n7, x2 = 1, y2 = 0; round < 24; round++) { + [x2, y2] = [y2, (2 * x2 + 3 * y2) % 5]; + SHA3_PI2.push(2 * (5 * y2 + x2)); + SHA3_ROTL2.push((round + 1) * (round + 2) / 2 % 64); + let t = _0n7; + for (let j2 = 0; j2 < 7; j2++) { + R2 = (R2 << _1n7 ^ (R2 >> _7n2) * _0x71n2) % _256n2; + if (R2 & _2n6) + t ^= _1n7 << (_1n7 << /* @__PURE__ */ BigInt(j2)) - _1n7; + } + _SHA3_IOTA2.push(t); +} +var [SHA3_IOTA_H2, SHA3_IOTA_L2] = /* @__PURE__ */ split2(_SHA3_IOTA2, true); +var rotlH2 = (h, l, s) => s > 32 ? rotlBH2(h, l, s) : rotlSH2(h, l, s); +var rotlL2 = (h, l, s) => s > 32 ? rotlBL2(h, l, s) : rotlSL2(h, l, s); +function keccakP2(s, rounds = 24) { + const B2 = new Uint32Array(5 * 2); + for (let round = 24 - rounds; round < 24; round++) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s[x2] ^ s[x2 + 10] ^ s[x2 + 20] ^ s[x2 + 30] ^ s[x2 + 40]; + for (let x2 = 0; x2 < 10; x2 += 2) { + const idx1 = (x2 + 8) % 10; + const idx0 = (x2 + 2) % 10; + const B0 = B2[idx0]; + const B1 = B2[idx0 + 1]; + const Th = rotlH2(B0, B1, 1) ^ B2[idx1]; + const Tl2 = rotlL2(B0, B1, 1) ^ B2[idx1 + 1]; + for (let y2 = 0; y2 < 50; y2 += 10) { + s[x2 + y2] ^= Th; + s[x2 + y2 + 1] ^= Tl2; + } + } + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL2[t]; + const Th = rotlH2(curH, curL, shift); + const Tl2 = rotlL2(curH, curL, shift); + const PI = SHA3_PI2[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl2; + } + for (let y2 = 0; y2 < 50; y2 += 10) { + for (let x2 = 0; x2 < 10; x2++) + B2[x2] = s[y2 + x2]; + for (let x2 = 0; x2 < 10; x2++) + s[y2 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10]; + } + s[0] ^= SHA3_IOTA_H2[round]; + s[1] ^= SHA3_IOTA_L2[round]; + } + B2.fill(0); } +var Keccak2 = class _Keccak extends Hash2 { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + anumber2(outputLen); + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error("Sha3 supports only keccak-f1600 function"); + this.state = new Uint8Array(200); + this.state32 = u322(this.state); + } + keccak() { + if (!isLE2) + byteSwap322(this.state32); + keccakP2(this.state32, this.rounds); + if (!isLE2) + byteSwap322(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + aexists2(this); + const { blockLen, state } = this; + data = toBytes3(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + state[pos] ^= suffix; + if ((suffix & 128) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 128; + this.keccak(); + } + writeInto(out) { + aexists2(this, false); + abytes3(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); + } + xof(bytes) { + anumber2(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + aoutput2(out, this); + if (this.finished) + throw new Error("digest() was already called"); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to2) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to2 || (to2 = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to2.state32.set(this.state32); + to2.pos = this.pos; + to2.posOut = this.posOut; + to2.finished = this.finished; + to2.rounds = rounds; + to2.suffix = suffix; + to2.outputLen = outputLen; + to2.enableXOF = enableXOF; + to2.destroyed = this.destroyed; + return to2; + } +}; +var gen2 = (suffix, blockLen, outputLen) => wrapConstructor2(() => new Keccak2(blockLen, suffix, outputLen)); +var sha3_2242 = /* @__PURE__ */ gen2(6, 144, 224 / 8); +var sha3_2562 = /* @__PURE__ */ gen2(6, 136, 256 / 8); +var sha3_3842 = /* @__PURE__ */ gen2(6, 104, 384 / 8); +var sha3_5122 = /* @__PURE__ */ gen2(6, 72, 512 / 8); +var keccak_2242 = /* @__PURE__ */ gen2(1, 144, 224 / 8); +var keccak_2562 = /* @__PURE__ */ gen2(1, 136, 256 / 8); +var keccak_3842 = /* @__PURE__ */ gen2(1, 104, 384 / 8); +var keccak_5122 = /* @__PURE__ */ gen2(1, 72, 512 / 8); +var genShake2 = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts2((opts = {}) => new Keccak2(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true)); +var shake1282 = /* @__PURE__ */ genShake2(31, 168, 128 / 8); +var shake2562 = /* @__PURE__ */ genShake2(31, 136, 256 / 8); -// node_modules/viem/_esm/utils/ens/labelhash.js -init_toBytes(); -init_toHex(); -init_keccak256(); -function labelhash(label) { - const result = new Uint8Array(32).fill(0); - if (!label) - return bytesToHex(result); - return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label)); +// node_modules/ox/_esm/core/Hash.js +function keccak2562(value, options = {}) { + const { as: as2 = typeof value === "string" ? "Hex" : "Bytes" } = options; + const bytes = keccak_2562(from(value)); + if (as2 === "Bytes") + return bytes; + return fromBytes(bytes); } -// node_modules/viem/_esm/utils/ens/packetToBytes.js -function packetToBytes(packet) { - const value = packet.replace(/^\.|\.$/gm, ""); - if (value.length === 0) - return new Uint8Array(1); - const bytes = new Uint8Array(stringToBytes(value).byteLength + 2); - let offset = 0; - const list = value.split("."); - for (let i = 0; i < list.length; i++) { - let encoded = stringToBytes(list[i]); - if (encoded.byteLength > 255) - encoded = stringToBytes(encodeLabelhash(labelhash(list[i]))); - bytes[offset] = encoded.length; - bytes.set(encoded, offset + 1); - offset += encoded.length + 1; +// node_modules/ox/_esm/core/internal/lru.js +var LruMap2 = class extends Map { + constructor(size5) { + super(); + Object.defineProperty(this, "maxSize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxSize = size5; } - if (bytes.byteLength !== offset + 1) - return bytes.slice(0, offset + 1); - return bytes; -} + get(key) { + const value = super.get(key); + if (super.has(key) && value !== void 0) { + this.delete(key); + super.set(key, value); + } + return value; + } + set(key, value) { + super.set(key, value); + if (this.maxSize && this.size > this.maxSize) { + const firstKey = this.keys().next().value; + if (firstKey) + this.delete(firstKey); + } + return this; + } +}; -// node_modules/viem/_esm/actions/ens/getEnsAddress.js -async function getEnsAddress(client, { blockNumber, blockTag, coinType, name, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { - let universalResolverAddress = universalResolverAddress_; - if (!universalResolverAddress) { - if (!client.chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - universalResolverAddress = getChainContractAddress({ - blockNumber, - chain: client.chain, - contract: "ensUniversalResolver" +// node_modules/ox/_esm/core/Caches.js +var caches = { + checksum: /* @__PURE__ */ new LruMap2(8192) +}; +var checksum = caches.checksum; + +// node_modules/ox/_esm/core/Address.js +var addressRegex2 = /^0x[a-fA-F0-9]{40}$/; +function assert2(value, options = {}) { + const { strict = true } = options; + if (!addressRegex2.test(value)) + throw new InvalidAddressError2({ + address: value, + cause: new InvalidInputError() }); + if (strict) { + if (value.toLowerCase() === value) + return; + if (checksum2(value) !== value) + throw new InvalidAddressError2({ + address: value, + cause: new InvalidChecksumError() + }); + } +} +function checksum2(address) { + if (checksum.has(address)) + return checksum.get(address); + assert2(address, { strict: false }); + const hexAddress = address.substring(2).toLowerCase(); + const hash2 = keccak2562(fromString(hexAddress), { as: "Bytes" }); + const characters = hexAddress.split(""); + for (let i = 0; i < 40; i += 2) { + if (hash2[i >> 1] >> 4 >= 8 && characters[i]) { + characters[i] = characters[i].toUpperCase(); + } + if ((hash2[i >> 1] & 15) >= 8 && characters[i + 1]) { + characters[i + 1] = characters[i + 1].toUpperCase(); + } } + const result = `0x${characters.join("")}`; + checksum.set(address, result); + return result; +} +function validate2(address, options = {}) { + const { strict = true } = options ?? {}; try { - const functionData = encodeFunctionData({ - abi: addressResolverAbi, - functionName: "addr", - ...coinType != null ? { args: [namehash(name), BigInt(coinType)] } : { args: [namehash(name)] } - }); - const readContractParameters = { - address: universalResolverAddress, - abi: universalResolverResolveAbi, - functionName: "resolve", - args: [toHex(packetToBytes(name)), functionData], - blockNumber, - blockTag - }; - const readContractAction = getAction(client, readContract, "readContract"); - const res = gatewayUrls ? await readContractAction({ - ...readContractParameters, - args: [...readContractParameters.args, gatewayUrls] - }) : await readContractAction(readContractParameters); - if (res[0] === "0x") - return null; - const address = decodeFunctionResult({ - abi: addressResolverAbi, - args: coinType != null ? [namehash(name), BigInt(coinType)] : void 0, - functionName: "addr", - data: res[0] - }); - if (address === "0x") - return null; - if (trim2(address) === "0x00") - return null; - return address; - } catch (err) { - if (strict) - throw err; - if (isNullUniversalResolverError(err, "resolve")) - return null; - throw err; + assert2(address, { strict }); + return true; + } catch { + return false; } } - -// node_modules/viem/_esm/errors/ens.js -init_base(); -var EnsAvatarInvalidMetadataError = class extends BaseError2 { - constructor({ data }) { - super("Unable to extract image from metadata. The metadata may be malformed or invalid.", { - metaMessages: [ - "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.", - "", - `Provided data: ${JSON.stringify(data)}` - ], - name: "EnsAvatarInvalidMetadataError" +var InvalidAddressError2 = class extends BaseError3 { + constructor({ address, cause }) { + super(`Address "${address}" is invalid.`, { + cause }); - } -}; -var EnsAvatarInvalidNftUriError = class extends BaseError2 { - constructor({ reason }) { - super(`ENS NFT avatar URI is invalid. ${reason}`, { - name: "EnsAvatarInvalidNftUriError" + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Address.InvalidAddressError" }); } }; -var EnsAvatarUriResolutionError = class extends BaseError2 { - constructor({ uri }) { - super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`, { name: "EnsAvatarUriResolutionError" }); +var InvalidInputError = class extends BaseError3 { + constructor() { + super("Address is not a 20 byte (40 hexadecimal character) value."); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Address.InvalidInputError" + }); } }; -var EnsAvatarUnsupportedNamespaceError = class extends BaseError2 { - constructor({ namespace }) { - super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`, { name: "EnsAvatarUnsupportedNamespaceError" }); +var InvalidChecksumError = class extends BaseError3 { + constructor() { + super("Address does not match its checksum counterpart."); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Address.InvalidChecksumError" + }); } }; -// node_modules/viem/_esm/utils/ens/avatar/utils.js -var networkRegex = /(?https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/; -var ipfsHashRegex = /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/; -var base64Regex = /^data:([a-zA-Z\-/+]*);base64,([^"].*)/; -var dataURIRegex = /^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/; -async function isImageUri(uri) { - try { - const res = await fetch(uri, { method: "HEAD" }); - if (res.status === 200) { - const contentType = res.headers.get("content-type"); - return contentType?.startsWith("image/"); +// node_modules/ox/_esm/core/internal/abiItem.js +function normalizeSignature2(signature) { + let active = true; + let current = ""; + let level = 0; + let result = ""; + let valid = false; + for (let i = 0; i < signature.length; i++) { + const char = signature[i]; + if (["(", ")", ","].includes(char)) + active = true; + if (char === "(") + level++; + if (char === ")") + level--; + if (!active) + continue; + if (level === 0) { + if (char === " " && ["event", "function", "error", ""].includes(result)) + result = ""; + else { + result += char; + if (char === ")") { + valid = true; + break; + } + } + continue; } - return false; - } catch (error) { - if (typeof error === "object" && typeof error.response !== "undefined") { + if (char === " ") { + if (signature[i - 1] !== "," && current !== "," && current !== ",(") { + current = ""; + active = false; + } + continue; + } + result += char; + current += char; + } + if (!valid) + throw new BaseError3("Unable to normalize signature."); + return result; +} +function isArgOfType2(arg, abiParameter) { + const argType = typeof arg; + const abiParameterType = abiParameter.type; + switch (abiParameterType) { + case "address": + return validate2(arg, { strict: false }); + case "bool": + return argType === "boolean"; + case "function": + return argType === "string"; + case "string": + return argType === "string"; + default: { + if (abiParameterType === "tuple" && "components" in abiParameter) + return Object.values(abiParameter.components).every((component, index2) => { + return isArgOfType2(Object.values(arg)[index2], component); + }); + if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) + return argType === "number" || argType === "bigint"; + if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) + return argType === "string" || arg instanceof Uint8Array; + if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { + return Array.isArray(arg) && arg.every((x2) => isArgOfType2(x2, { + ...abiParameter, + // Pop off `[]` or `[M]` from end of type + type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") + })); + } return false; } - if (!globalThis.hasOwnProperty("Image")) + } +} +function getAmbiguousTypes2(sourceParameters, targetParameters, args) { + for (const parameterIndex in sourceParameters) { + const sourceParameter = sourceParameters[parameterIndex]; + const targetParameter = targetParameters[parameterIndex]; + if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) + return getAmbiguousTypes2(sourceParameter.components, targetParameter.components, args[parameterIndex]); + const types = [sourceParameter.type, targetParameter.type]; + const ambiguous = (() => { + if (types.includes("address") && types.includes("bytes20")) + return true; + if (types.includes("address") && types.includes("string")) + return validate2(args[parameterIndex], { + strict: false + }); + if (types.includes("address") && types.includes("bytes")) + return validate2(args[parameterIndex], { + strict: false + }); return false; - return new Promise((resolve) => { - const img = new Image(); - img.onload = () => { - resolve(true); - }; - img.onerror = () => { - resolve(false); - }; - img.src = uri; - }); + })(); + if (ambiguous) + return types; } + return; } -function getGateway(custom, defaultGateway) { - if (!custom) - return defaultGateway; - if (custom.endsWith("/")) - return custom.slice(0, -1); - return custom; + +// node_modules/ox/_esm/core/AbiItem.js +function from2(abiItem, options = {}) { + const { prepare = true } = options; + const item = (() => { + if (Array.isArray(abiItem)) + return parseAbiItem(abiItem); + if (typeof abiItem === "string") + return parseAbiItem(abiItem); + return abiItem; + })(); + return { + ...item, + ...prepare ? { hash: getSignatureHash(item) } : {} + }; } -function resolveAvatarUri({ uri, gatewayUrls }) { - const isEncoded = base64Regex.test(uri); - if (isEncoded) - return { uri, isOnChain: true, isEncoded }; - const ipfsGateway = getGateway(gatewayUrls?.ipfs, "https://ipfs.io"); - const arweaveGateway = getGateway(gatewayUrls?.arweave, "https://arweave.net"); - const networkRegexMatch = uri.match(networkRegex); - const { protocol, subpath, target, subtarget = "" } = networkRegexMatch?.groups || {}; - const isIPNS = protocol === "ipns:/" || subpath === "ipns/"; - const isIPFS = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri); - if (uri.startsWith("http") && !isIPNS && !isIPFS) { - let replacedUri = uri; - if (gatewayUrls?.arweave) - replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls?.arweave); - return { uri: replacedUri, isOnChain: false, isEncoded: false }; - } - if ((isIPNS || isIPFS) && target) { - return { - uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`, - isOnChain: false, - isEncoded: false - }; - } - if (protocol === "ar:/" && target) { - return { - uri: `${arweaveGateway}/${target}${subtarget || ""}`, - isOnChain: false, - isEncoded: false - }; - } - let parsedUri = uri.replace(dataURIRegex, ""); - if (parsedUri.startsWith(" { + if (isSelector) { + if (abiItem2.type === "function" || abiItem2.type === "error") + return getSelector(abiItem2) === slice2(name, 0, 4); + if (abiItem2.type === "event") + return getSignatureHash(abiItem2) === name; + return false; + } + return "name" in abiItem2 && abiItem2.name === name; + }); + if (abiItems.length === 0) + throw new NotFoundError2({ name }); + if (abiItems.length === 1) return { - uri: parsedUri, - isOnChain: true, - isEncoded: false + ...abiItems[0], + ...prepare ? { hash: getSignatureHash(abiItems[0]) } : {} }; + let matchedAbiItem = void 0; + for (const abiItem2 of abiItems) { + if (!("inputs" in abiItem2)) + continue; + if (!args || args.length === 0) { + if (!abiItem2.inputs || abiItem2.inputs.length === 0) + return { + ...abiItem2, + ...prepare ? { hash: getSignatureHash(abiItem2) } : {} + }; + continue; + } + if (!abiItem2.inputs) + continue; + if (abiItem2.inputs.length === 0) + continue; + if (abiItem2.inputs.length !== args.length) + continue; + const matched = args.every((arg, index2) => { + const abiParameter = "inputs" in abiItem2 && abiItem2.inputs[index2]; + if (!abiParameter) + return false; + return isArgOfType2(arg, abiParameter); + }); + if (matched) { + if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { + const ambiguousTypes = getAmbiguousTypes2(abiItem2.inputs, matchedAbiItem.inputs, args); + if (ambiguousTypes) + throw new AmbiguityError({ + abiItem: abiItem2, + type: ambiguousTypes[0] + }, { + abiItem: matchedAbiItem, + type: ambiguousTypes[1] + }); + } + matchedAbiItem = abiItem2; + } } - throw new EnsAvatarUriResolutionError({ uri }); + const abiItem = (() => { + if (matchedAbiItem) + return matchedAbiItem; + const [abiItem2, ...overloads] = abiItems; + return { ...abiItem2, overloads }; + })(); + if (!abiItem) + throw new NotFoundError2({ name }); + return { + ...abiItem, + ...prepare ? { hash: getSignatureHash(abiItem) } : {} + }; } -function getJsonImage(data) { - if (typeof data !== "object" || !("image" in data) && !("image_url" in data) && !("image_data" in data)) { - throw new EnsAvatarInvalidMetadataError({ data }); - } - return data.image || data.image_url || data.image_data; +function getSelector(abiItem) { + return slice2(getSignatureHash(abiItem), 0, 4); } -async function getMetadataAvatarUri({ gatewayUrls, uri }) { - try { - const res = await fetch(uri).then((res2) => res2.json()); - const image = await parseAvatarUri({ - gatewayUrls, - uri: getJsonImage(res) - }); - return image; - } catch { - throw new EnsAvatarUriResolutionError({ uri }); - } +function getSignature(abiItem) { + const signature = (() => { + if (typeof abiItem === "string") + return abiItem; + return formatAbiItem(abiItem); + })(); + return normalizeSignature2(signature); } -async function parseAvatarUri({ gatewayUrls, uri }) { - const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls }); - if (isOnChain) - return resolvedURI; - const isImage = await isImageUri(resolvedURI); - if (isImage) - return resolvedURI; - throw new EnsAvatarUriResolutionError({ uri }); +function getSignatureHash(abiItem) { + if (typeof abiItem !== "string" && "hash" in abiItem && abiItem.hash) + return abiItem.hash; + return keccak2562(fromString2(getSignature(abiItem))); } -function parseNftUri(uri_) { - let uri = uri_; - if (uri.startsWith("did:nft:")) { - uri = uri.replace("did:nft:", "").replace(/_/g, "/"); - } - const [reference, asset_namespace, tokenID] = uri.split("/"); - const [eip_namespace, chainID] = reference.split(":"); - const [erc_namespace, contractAddress] = asset_namespace.split(":"); - if (!eip_namespace || eip_namespace.toLowerCase() !== "eip155") - throw new EnsAvatarInvalidNftUriError({ reason: "Only EIP-155 supported" }); - if (!chainID) - throw new EnsAvatarInvalidNftUriError({ reason: "Chain ID not found" }); - if (!contractAddress) - throw new EnsAvatarInvalidNftUriError({ - reason: "Contract address not found" +var AmbiguityError = class extends BaseError3 { + constructor(x2, y2) { + super("Found ambiguous types in overloaded ABI Items.", { + metaMessages: [ + // TODO: abitype to add support for signature-formatted ABI items. + `\`${x2.type}\` in \`${normalizeSignature2(formatAbiItem(x2.abiItem))}\`, and`, + `\`${y2.type}\` in \`${normalizeSignature2(formatAbiItem(y2.abiItem))}\``, + "", + "These types encode differently and cannot be distinguished at runtime.", + "Remove one of the ambiguous items in the ABI." + ] }); - if (!tokenID) - throw new EnsAvatarInvalidNftUriError({ reason: "Token ID not found" }); - if (!erc_namespace) - throw new EnsAvatarInvalidNftUriError({ reason: "ERC namespace not found" }); - return { - chainID: Number.parseInt(chainID), - namespace: erc_namespace.toLowerCase(), - contractAddress, - tokenID - }; -} -async function getNftTokenUri(client, { nft }) { - if (nft.namespace === "erc721") { - return readContract(client, { - address: nft.contractAddress, - abi: [ - { - name: "tokenURI", - type: "function", - stateMutability: "view", - inputs: [{ name: "tokenId", type: "uint256" }], - outputs: [{ name: "", type: "string" }] - } - ], - functionName: "tokenURI", - args: [BigInt(nft.tokenID)] + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiItem.AmbiguityError" }); } - if (nft.namespace === "erc1155") { - return readContract(client, { - address: nft.contractAddress, - abi: [ - { - name: "uri", - type: "function", - stateMutability: "view", - inputs: [{ name: "_id", type: "uint256" }], - outputs: [{ name: "", type: "string" }] - } - ], - functionName: "uri", - args: [BigInt(nft.tokenID)] +}; +var NotFoundError2 = class extends BaseError3 { + constructor({ name, data, type = "item" }) { + const selector = (() => { + if (name) + return ` with name "${name}"`; + if (data) + return ` with data "${data}"`; + return ""; + })(); + super(`ABI ${type}${selector} not found.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiItem.NotFoundError" }); } - throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace }); -} +}; + +// node_modules/ox/_esm/core/Solidity.js +var arrayRegex = /^(.*)\[([0-9]*)\]$/; +var bytesRegex3 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; +var integerRegex3 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; +var maxInt82 = 2n ** (8n - 1n) - 1n; +var maxInt162 = 2n ** (16n - 1n) - 1n; +var maxInt242 = 2n ** (24n - 1n) - 1n; +var maxInt322 = 2n ** (32n - 1n) - 1n; +var maxInt402 = 2n ** (40n - 1n) - 1n; +var maxInt482 = 2n ** (48n - 1n) - 1n; +var maxInt562 = 2n ** (56n - 1n) - 1n; +var maxInt642 = 2n ** (64n - 1n) - 1n; +var maxInt722 = 2n ** (72n - 1n) - 1n; +var maxInt802 = 2n ** (80n - 1n) - 1n; +var maxInt882 = 2n ** (88n - 1n) - 1n; +var maxInt962 = 2n ** (96n - 1n) - 1n; +var maxInt1042 = 2n ** (104n - 1n) - 1n; +var maxInt1122 = 2n ** (112n - 1n) - 1n; +var maxInt1202 = 2n ** (120n - 1n) - 1n; +var maxInt1282 = 2n ** (128n - 1n) - 1n; +var maxInt1362 = 2n ** (136n - 1n) - 1n; +var maxInt1442 = 2n ** (144n - 1n) - 1n; +var maxInt1522 = 2n ** (152n - 1n) - 1n; +var maxInt1602 = 2n ** (160n - 1n) - 1n; +var maxInt1682 = 2n ** (168n - 1n) - 1n; +var maxInt1762 = 2n ** (176n - 1n) - 1n; +var maxInt1842 = 2n ** (184n - 1n) - 1n; +var maxInt1922 = 2n ** (192n - 1n) - 1n; +var maxInt2002 = 2n ** (200n - 1n) - 1n; +var maxInt2082 = 2n ** (208n - 1n) - 1n; +var maxInt2162 = 2n ** (216n - 1n) - 1n; +var maxInt2242 = 2n ** (224n - 1n) - 1n; +var maxInt2322 = 2n ** (232n - 1n) - 1n; +var maxInt2402 = 2n ** (240n - 1n) - 1n; +var maxInt2482 = 2n ** (248n - 1n) - 1n; +var maxInt2562 = 2n ** (256n - 1n) - 1n; +var minInt82 = -(2n ** (8n - 1n)); +var minInt162 = -(2n ** (16n - 1n)); +var minInt242 = -(2n ** (24n - 1n)); +var minInt322 = -(2n ** (32n - 1n)); +var minInt402 = -(2n ** (40n - 1n)); +var minInt482 = -(2n ** (48n - 1n)); +var minInt562 = -(2n ** (56n - 1n)); +var minInt642 = -(2n ** (64n - 1n)); +var minInt722 = -(2n ** (72n - 1n)); +var minInt802 = -(2n ** (80n - 1n)); +var minInt882 = -(2n ** (88n - 1n)); +var minInt962 = -(2n ** (96n - 1n)); +var minInt1042 = -(2n ** (104n - 1n)); +var minInt1122 = -(2n ** (112n - 1n)); +var minInt1202 = -(2n ** (120n - 1n)); +var minInt1282 = -(2n ** (128n - 1n)); +var minInt1362 = -(2n ** (136n - 1n)); +var minInt1442 = -(2n ** (144n - 1n)); +var minInt1522 = -(2n ** (152n - 1n)); +var minInt1602 = -(2n ** (160n - 1n)); +var minInt1682 = -(2n ** (168n - 1n)); +var minInt1762 = -(2n ** (176n - 1n)); +var minInt1842 = -(2n ** (184n - 1n)); +var minInt1922 = -(2n ** (192n - 1n)); +var minInt2002 = -(2n ** (200n - 1n)); +var minInt2082 = -(2n ** (208n - 1n)); +var minInt2162 = -(2n ** (216n - 1n)); +var minInt2242 = -(2n ** (224n - 1n)); +var minInt2322 = -(2n ** (232n - 1n)); +var minInt2402 = -(2n ** (240n - 1n)); +var minInt2482 = -(2n ** (248n - 1n)); +var minInt2562 = -(2n ** (256n - 1n)); +var maxUint82 = 2n ** 8n - 1n; +var maxUint162 = 2n ** 16n - 1n; +var maxUint242 = 2n ** 24n - 1n; +var maxUint322 = 2n ** 32n - 1n; +var maxUint402 = 2n ** 40n - 1n; +var maxUint482 = 2n ** 48n - 1n; +var maxUint562 = 2n ** 56n - 1n; +var maxUint642 = 2n ** 64n - 1n; +var maxUint722 = 2n ** 72n - 1n; +var maxUint802 = 2n ** 80n - 1n; +var maxUint882 = 2n ** 88n - 1n; +var maxUint962 = 2n ** 96n - 1n; +var maxUint1042 = 2n ** 104n - 1n; +var maxUint1122 = 2n ** 112n - 1n; +var maxUint1202 = 2n ** 120n - 1n; +var maxUint1282 = 2n ** 128n - 1n; +var maxUint1362 = 2n ** 136n - 1n; +var maxUint1442 = 2n ** 144n - 1n; +var maxUint1522 = 2n ** 152n - 1n; +var maxUint1602 = 2n ** 160n - 1n; +var maxUint1682 = 2n ** 168n - 1n; +var maxUint1762 = 2n ** 176n - 1n; +var maxUint1842 = 2n ** 184n - 1n; +var maxUint1922 = 2n ** 192n - 1n; +var maxUint2002 = 2n ** 200n - 1n; +var maxUint2082 = 2n ** 208n - 1n; +var maxUint2162 = 2n ** 216n - 1n; +var maxUint2242 = 2n ** 224n - 1n; +var maxUint2322 = 2n ** 232n - 1n; +var maxUint2402 = 2n ** 240n - 1n; +var maxUint2482 = 2n ** 248n - 1n; +var maxUint2562 = 2n ** 256n - 1n; -// node_modules/viem/_esm/utils/ens/avatar/parseAvatarRecord.js -async function parseAvatarRecord(client, { gatewayUrls, record }) { - if (/eip155:/i.test(record)) - return parseNftAvatarUri(client, { gatewayUrls, record }); - return parseAvatarUri({ uri: record, gatewayUrls }); -} -async function parseNftAvatarUri(client, { gatewayUrls, record }) { - const nft = parseNftUri(record); - const nftUri = await getNftTokenUri(client, { nft }); - const { uri: resolvedNftUri, isOnChain, isEncoded } = resolveAvatarUri({ uri: nftUri, gatewayUrls }); - if (isOnChain && (resolvedNftUri.includes("data:application/json;base64,") || resolvedNftUri.startsWith("{"))) { - const encodedJson = isEncoded ? ( - // if it is encoded, decode it - atob(resolvedNftUri.replace("data:application/json;base64,", "")) - ) : ( - // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is) - resolvedNftUri - ); - const decoded = JSON.parse(encodedJson); - return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls }); +// node_modules/ox/_esm/core/internal/abiParameters.js +function prepareParameters({ checksumAddress: checksumAddress2, parameters, values }) { + const preparedParameters = []; + for (let i = 0; i < parameters.length; i++) { + preparedParameters.push(prepareParameter({ + checksumAddress: checksumAddress2, + parameter: parameters[i], + value: values[i] + })); } - let uriTokenId = nft.tokenID; - if (nft.namespace === "erc1155") - uriTokenId = uriTokenId.replace("0x", "").padStart(64, "0"); - return getMetadataAvatarUri({ - gatewayUrls, - uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId) - }); + return preparedParameters; } - -// node_modules/viem/_esm/actions/ens/getEnsText.js -init_abis(); -init_decodeFunctionResult(); -init_encodeFunctionData(); -init_getChainContractAddress(); -init_toHex(); -async function getEnsText(client, { blockNumber, blockTag, name, key, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { - let universalResolverAddress = universalResolverAddress_; - if (!universalResolverAddress) { - if (!client.chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - universalResolverAddress = getChainContractAddress({ - blockNumber, - chain: client.chain, - contract: "ensUniversalResolver" +function prepareParameter({ checksumAddress: checksumAddress2 = false, parameter: parameter_, value }) { + const parameter = parameter_; + const arrayComponents = getArrayComponents2(parameter.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return encodeArray2(value, { + checksumAddress: checksumAddress2, + length, + parameter: { + ...parameter, + type + } }); } - try { - const readContractParameters = { - address: universalResolverAddress, - abi: universalResolverResolveAbi, - functionName: "resolve", - args: [ - toHex(packetToBytes(name)), - encodeFunctionData({ - abi: textResolverAbi, - functionName: "text", - args: [namehash(name), key] - }) - ], - blockNumber, - blockTag - }; - const readContractAction = getAction(client, readContract, "readContract"); - const res = gatewayUrls ? await readContractAction({ - ...readContractParameters, - args: [...readContractParameters.args, gatewayUrls] - }) : await readContractAction(readContractParameters); - if (res[0] === "0x") - return null; - const record = decodeFunctionResult({ - abi: textResolverAbi, - functionName: "text", - data: res[0] + if (parameter.type === "tuple") { + return encodeTuple2(value, { + checksumAddress: checksumAddress2, + parameter }); - return record === "" ? null : record; - } catch (err) { - if (strict) - throw err; - if (isNullUniversalResolverError(err, "resolve")) - return null; - throw err; } -} - -// node_modules/viem/_esm/actions/ens/getEnsAvatar.js -async function getEnsAvatar(client, { blockNumber, blockTag, assetGatewayUrls, name, gatewayUrls, strict, universalResolverAddress }) { - const record = await getAction(client, getEnsText, "getEnsText")({ - blockNumber, - blockTag, - key: "avatar", - name, - universalResolverAddress, - gatewayUrls, - strict - }); - if (!record) - return null; - try { - return await parseAvatarRecord(client, { - record, - gatewayUrls: assetGatewayUrls + if (parameter.type === "address") { + return encodeAddress2(value, { + checksum: checksumAddress2 }); - } catch { - return null; } -} - -// node_modules/viem/_esm/actions/ens/getEnsName.js -init_abis(); -init_getChainContractAddress(); -init_toHex(); -async function getEnsName(client, { address, blockNumber, blockTag, gatewayUrls, strict, universalResolverAddress: universalResolverAddress_ }) { - let universalResolverAddress = universalResolverAddress_; - if (!universalResolverAddress) { - if (!client.chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - universalResolverAddress = getChainContractAddress({ - blockNumber, - chain: client.chain, - contract: "ensUniversalResolver" + if (parameter.type === "bool") { + return encodeBoolean(value); + } + if (parameter.type.startsWith("uint") || parameter.type.startsWith("int")) { + const signed = parameter.type.startsWith("int"); + const [, , size5 = "256"] = integerRegex3.exec(parameter.type) ?? []; + return encodeNumber2(value, { + signed, + size: Number(size5) }); } - const reverseNode = `${address.toLowerCase().substring(2)}.addr.reverse`; - try { - const readContractParameters = { - address: universalResolverAddress, - abi: universalResolverReverseAbi, - functionName: "reverse", - args: [toHex(packetToBytes(reverseNode))], - blockNumber, - blockTag - }; - const readContractAction = getAction(client, readContract, "readContract"); - const [name, resolvedAddress] = gatewayUrls ? await readContractAction({ - ...readContractParameters, - args: [...readContractParameters.args, gatewayUrls] - }) : await readContractAction(readContractParameters); - if (address.toLowerCase() !== resolvedAddress.toLowerCase()) - return null; - return name; - } catch (err) { - if (strict) - throw err; - if (isNullUniversalResolverError(err, "reverse")) - return null; - throw err; + if (parameter.type.startsWith("bytes")) { + return encodeBytes2(value, { type: parameter.type }); + } + if (parameter.type === "string") { + return encodeString2(value); } + throw new InvalidTypeError(parameter.type); } - -// node_modules/viem/_esm/actions/ens/getEnsResolver.js -init_getChainContractAddress(); -init_toHex(); -async function getEnsResolver(client, { blockNumber, blockTag, name, universalResolverAddress: universalResolverAddress_ }) { - let universalResolverAddress = universalResolverAddress_; - if (!universalResolverAddress) { - if (!client.chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - universalResolverAddress = getChainContractAddress({ - blockNumber, - chain: client.chain, - contract: "ensUniversalResolver" - }); +function encode(preparedParameters) { + let staticSize = 0; + for (let i = 0; i < preparedParameters.length; i++) { + const { dynamic, encoded } = preparedParameters[i]; + if (dynamic) + staticSize += 32; + else + staticSize += size4(encoded); } - const [resolverAddress] = await getAction(client, readContract, "readContract")({ - address: universalResolverAddress, - abi: [ - { - inputs: [{ type: "bytes" }], - name: "findResolver", - outputs: [{ type: "address" }, { type: "bytes32" }], - stateMutability: "view", - type: "function" - } - ], - functionName: "findResolver", - args: [toHex(packetToBytes(name))], - blockNumber, - blockTag - }); - return resolverAddress; + const staticParameters = []; + const dynamicParameters = []; + let dynamicSize = 0; + for (let i = 0; i < preparedParameters.length; i++) { + const { dynamic, encoded } = preparedParameters[i]; + if (dynamic) { + staticParameters.push(fromNumber(staticSize + dynamicSize, { size: 32 })); + dynamicParameters.push(encoded); + dynamicSize += size4(encoded); + } else { + staticParameters.push(encoded); + } + } + return concat2(...staticParameters, ...dynamicParameters); } - -// node_modules/viem/_esm/clients/decorators/public.js -init_call(); - -// node_modules/viem/_esm/actions/public/createAccessList.js -init_parseAccount(); -init_toHex(); -init_getCallError(); -init_extract(); -init_transactionRequest(); -init_assertRequest(); -async function createAccessList(client, args) { - const { account: account_ = client.account, blockNumber, blockTag = "latest", blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, to: to2, value, ...rest } = args; - const account = account_ ? parseAccount(account_) : void 0; - try { - assertRequest(args); - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const block = blockNumberHex || blockTag; - const chainFormat = client.chain?.formatters?.transactionRequest?.format; - const format = chainFormat || formatTransactionRequest; - const request = format({ - // Pick out extra data that might exist on the chain's transaction request type. - ...extract(rest, { format: chainFormat }), - from: account?.address, - blobs, - data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - to: to2, - value +function encodeAddress2(value, options) { + const { checksum: checksum3 = false } = options; + assert2(value, { strict: checksum3 }); + return { + dynamic: false, + encoded: padLeft(value.toLowerCase()) + }; +} +function encodeArray2(value, options) { + const { checksumAddress: checksumAddress2, length, parameter } = options; + const dynamic = length === null; + if (!Array.isArray(value)) + throw new InvalidArrayError2(value); + if (!dynamic && value.length !== length) + throw new ArrayLengthMismatchError({ + expectedLength: length, + givenLength: value.length, + type: `${parameter.type}[${length}]` }); - const response = await client.request({ - method: "eth_createAccessList", - params: [request, block] + let dynamicChild = false; + const preparedParameters = []; + for (let i = 0; i < value.length; i++) { + const preparedParam = prepareParameter({ + checksumAddress: checksumAddress2, + parameter, + value: value[i] }); + if (preparedParam.dynamic) + dynamicChild = true; + preparedParameters.push(preparedParam); + } + if (dynamic || dynamicChild) { + const data = encode(preparedParameters); + if (dynamic) { + const length2 = fromNumber(preparedParameters.length, { size: 32 }); + return { + dynamic: true, + encoded: preparedParameters.length > 0 ? concat2(length2, data) : length2 + }; + } + if (dynamicChild) + return { dynamic: true, encoded: data }; + } + return { + dynamic: false, + encoded: concat2(...preparedParameters.map(({ encoded }) => encoded)) + }; +} +function encodeBytes2(value, { type }) { + const [, parametersize] = type.split("bytes"); + const bytesSize = size4(value); + if (!parametersize) { + let value_ = value; + if (bytesSize % 32 !== 0) + value_ = padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32); return { - accessList: response.accessList, - gasUsed: BigInt(response.gasUsed) + dynamic: true, + encoded: concat2(padLeft(fromNumber(bytesSize, { size: 32 })), value_) }; - } catch (err) { - throw getCallError(err, { - ...args, - account, - chain: client.chain - }); } + if (bytesSize !== Number.parseInt(parametersize)) + throw new BytesSizeMismatchError2({ + expectedSize: Number.parseInt(parametersize), + value + }); + return { dynamic: false, encoded: padRight(value) }; } - -// node_modules/viem/_esm/actions/public/createBlockFilter.js -async function createBlockFilter(client) { - const getRequest = createFilterRequestScope(client, { - method: "eth_newBlockFilter" - }); - const id2 = await client.request({ - method: "eth_newBlockFilter" - }); - return { id: id2, request: getRequest(id2), type: "block" }; +function encodeBoolean(value) { + if (typeof value !== "boolean") + throw new BaseError3(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); + return { dynamic: false, encoded: padLeft(fromBoolean(value)) }; } - -// node_modules/viem/_esm/actions/public/createEventFilter.js -init_toHex(); -async function createEventFilter(client, { address, args, event, events: events_, fromBlock, strict, toBlock } = {}) { - const events = events_ ?? (event ? [event] : void 0); - const getRequest = createFilterRequestScope(client, { - method: "eth_newFilter" - }); - let topics = []; - if (events) { - const encoded = events.flatMap((event2) => encodeEventTopics({ - abi: [event2], - eventName: event2.name, - args - })); - topics = [encoded]; - if (event) - topics = topics[0]; +function encodeNumber2(value, { signed, size: size5 }) { + if (typeof size5 === "number") { + const max = 2n ** (BigInt(size5) - (signed ? 1n : 0n)) - 1n; + const min = signed ? -max - 1n : 0n; + if (value > max || value < min) + throw new IntegerOutOfRangeError2({ + max: max.toString(), + min: min.toString(), + signed, + size: size5 / 8, + value: value.toString() + }); } - const id2 = await client.request({ - method: "eth_newFilter", - params: [ - { - address, - fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, - toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, - ...topics.length ? { topics } : {} - } - ] - }); return { - abi: events, - args, - eventName: event ? event.name : void 0, - fromBlock, - id: id2, - request: getRequest(id2), - strict: Boolean(strict), - toBlock, - type: "event" + dynamic: false, + encoded: fromNumber(value, { + size: 32, + signed + }) }; } - -// node_modules/viem/_esm/actions/public/createPendingTransactionFilter.js -async function createPendingTransactionFilter(client) { - const getRequest = createFilterRequestScope(client, { - method: "eth_newPendingTransactionFilter" - }); - const id2 = await client.request({ - method: "eth_newPendingTransactionFilter" - }); - return { id: id2, request: getRequest(id2), type: "transaction" }; -} - -// node_modules/viem/_esm/actions/public/getBlobBaseFee.js -async function getBlobBaseFee(client) { - const baseFee = await client.request({ - method: "eth_blobBaseFee" - }); - return BigInt(baseFee); -} - -// node_modules/viem/_esm/actions/public/getBlockTransactionCount.js -init_fromHex(); -init_toHex(); -async function getBlockTransactionCount(client, { blockHash, blockNumber, blockTag = "latest" } = {}) { - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - let count; - if (blockHash) { - count = await client.request({ - method: "eth_getBlockTransactionCountByHash", - params: [blockHash] - }, { dedupe: true }); - } else { - count = await client.request({ - method: "eth_getBlockTransactionCountByNumber", - params: [blockNumberHex || blockTag] - }, { dedupe: Boolean(blockNumberHex) }); +function encodeString2(value) { + const hexValue = fromString2(value); + const partsLength = Math.ceil(size4(hexValue) / 32); + const parts = []; + for (let i = 0; i < partsLength; i++) { + parts.push(padRight(slice2(hexValue, i * 32, (i + 1) * 32))); } - return hexToNumber(count); -} - -// node_modules/viem/_esm/actions/public/getCode.js -init_toHex(); -async function getCode(client, { address, blockNumber, blockTag = "latest" }) { - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - const hex = await client.request({ - method: "eth_getCode", - params: [address, blockNumberHex || blockTag] - }, { dedupe: Boolean(blockNumberHex) }); - if (hex === "0x") - return void 0; - return hex; + return { + dynamic: true, + encoded: concat2(padRight(fromNumber(size4(hexValue), { size: 32 })), ...parts) + }; } - -// node_modules/viem/_esm/actions/public/getFeeHistory.js -init_toHex(); - -// node_modules/viem/_esm/utils/formatters/feeHistory.js -function formatFeeHistory(feeHistory) { +function encodeTuple2(value, options) { + const { checksumAddress: checksumAddress2, parameter } = options; + let dynamic = false; + const preparedParameters = []; + for (let i = 0; i < parameter.components.length; i++) { + const param_ = parameter.components[i]; + const index2 = Array.isArray(value) ? i : param_.name; + const preparedParam = prepareParameter({ + checksumAddress: checksumAddress2, + parameter: param_, + value: value[index2] + }); + preparedParameters.push(preparedParam); + if (preparedParam.dynamic) + dynamic = true; + } return { - baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)), - gasUsedRatio: feeHistory.gasUsedRatio, - oldestBlock: BigInt(feeHistory.oldestBlock), - reward: feeHistory.reward?.map((reward) => reward.map((value) => BigInt(value))) + dynamic, + encoded: dynamic ? encode(preparedParameters) : concat2(...preparedParameters.map(({ encoded }) => encoded)) }; } - -// node_modules/viem/_esm/actions/public/getFeeHistory.js -async function getFeeHistory(client, { blockCount, blockNumber, blockTag = "latest", rewardPercentiles }) { - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const feeHistory = await client.request({ - method: "eth_feeHistory", - params: [ - numberToHex(blockCount), - blockNumberHex || blockTag, - rewardPercentiles - ] - }, { dedupe: Boolean(blockNumberHex) }); - return formatFeeHistory(feeHistory); +function getArrayComponents2(type) { + const matches = type.match(/^(.*)\[(\d+)?\]$/); + return matches ? ( + // Return `null` if the array is dynamic. + [matches[2] ? Number(matches[2]) : null, matches[1]] + ) : void 0; } -// node_modules/viem/_esm/actions/public/getFilterLogs.js -async function getFilterLogs(_client, { filter: filter2 }) { - const strict = filter2.strict ?? false; - const logs = await filter2.request({ - method: "eth_getFilterLogs", - params: [filter2.id] - }); - const formattedLogs = logs.map((log) => formatLog(log)); - if (!filter2.abi) - return formattedLogs; - return parseEventLogs({ - abi: filter2.abi, - logs: formattedLogs, - strict +// node_modules/ox/_esm/core/AbiParameters.js +function encode2(parameters, values, options) { + const { checksumAddress: checksumAddress2 = false } = options ?? {}; + if (parameters.length !== values.length) + throw new LengthMismatchError({ + expectedLength: parameters.length, + givenLength: values.length + }); + const preparedParameters = prepareParameters({ + checksumAddress: checksumAddress2, + parameters, + values }); + const data = encode(preparedParameters); + if (data.length === 0) + return "0x"; + return data; } - -// node_modules/viem/_esm/actions/public/getProof.js -init_toHex(); - -// node_modules/viem/_esm/utils/chain/defineChain.js -function defineChain(chain) { - return { - formatters: void 0, - fees: void 0, - serializers: void 0, - ...chain - }; +function encodePacked(types, values) { + if (types.length !== values.length) + throw new LengthMismatchError({ + expectedLength: types.length, + givenLength: values.length + }); + const data = []; + for (let i = 0; i < types.length; i++) { + const type = types[i]; + const value = values[i]; + data.push(encodePacked.encode(type, value)); + } + return concat2(...data); } - -// node_modules/viem/_esm/utils/typedData.js -init_abi(); -init_address(); - -// node_modules/viem/_esm/errors/typedData.js -init_stringify(); -init_base(); -var InvalidDomainError = class extends BaseError2 { - constructor({ domain }) { - super(`Invalid domain "${stringify(domain)}".`, { - metaMessages: ["Must be a valid EIP-712 domain."] +(function(encodePacked2) { + function encode6(type, value, isArray2 = false) { + if (type === "address") { + const address = value; + assert2(address); + return padLeft(address.toLowerCase(), isArray2 ? 32 : 0); + } + if (type === "string") + return fromString2(value); + if (type === "bytes") + return value; + if (type === "bool") + return padLeft(fromBoolean(value), isArray2 ? 32 : 1); + const intMatch = type.match(integerRegex3); + if (intMatch) { + const [_type, baseType, bits = "256"] = intMatch; + const size5 = Number.parseInt(bits) / 8; + return fromNumber(value, { + size: isArray2 ? 32 : size5, + signed: baseType === "int" + }); + } + const bytesMatch = type.match(bytesRegex3); + if (bytesMatch) { + const [_type, size5] = bytesMatch; + if (Number.parseInt(size5) !== (value.length - 2) / 2) + throw new BytesSizeMismatchError2({ + expectedSize: Number.parseInt(size5), + value + }); + return padRight(value, isArray2 ? 32 : 0); + } + const arrayMatch = type.match(arrayRegex); + if (arrayMatch && Array.isArray(value)) { + const [_type, childType] = arrayMatch; + const data = []; + for (let i = 0; i < value.length; i++) { + data.push(encode6(childType, value[i], true)); + } + if (data.length === 0) + return "0x"; + return concat2(...data); + } + throw new InvalidTypeError(type); + } + encodePacked2.encode = encode6; +})(encodePacked || (encodePacked = {})); +var ArrayLengthMismatchError = class extends BaseError3 { + constructor({ expectedLength, givenLength, type }) { + super(`Array length mismatch for type \`${type}\`. Expected: \`${expectedLength}\`. Given: \`${givenLength}\`.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.ArrayLengthMismatchError" }); } }; -var InvalidPrimaryTypeError = class extends BaseError2 { - constructor({ primaryType, types }) { - super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, { - docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror", - metaMessages: ["Check that the primary type is a key in `types`."] +var BytesSizeMismatchError2 = class extends BaseError3 { + constructor({ expectedSize, value }) { + super(`Size of bytes "${value}" (bytes${size4(value)}) does not match expected size (bytes${expectedSize}).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.BytesSizeMismatchError" }); } }; -var InvalidStructTypeError = class extends BaseError2 { - constructor({ type }) { - super(`Struct type "${type}" is invalid.`, { - metaMessages: ["Struct type must not be a Solidity type."], - name: "InvalidStructTypeError" +var LengthMismatchError = class extends BaseError3 { + constructor({ expectedLength, givenLength }) { + super([ + "ABI encoding parameters/values length mismatch.", + `Expected length (parameters): ${expectedLength}`, + `Given length (values): ${givenLength}` + ].join("\n")); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.LengthMismatchError" + }); + } +}; +var InvalidArrayError2 = class extends BaseError3 { + constructor(value) { + super(`Value \`${value}\` is not a valid array.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.InvalidArrayError" + }); + } +}; +var InvalidTypeError = class extends BaseError3 { + constructor(type) { + super(`Type \`${type}\` is not a valid ABI Type.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.InvalidTypeError" }); } }; -// node_modules/viem/_esm/utils/typedData.js -init_isAddress(); -init_size(); -init_toHex(); -init_regex2(); - -// node_modules/viem/_esm/utils/signature/hashTypedData.js -init_encodeAbiParameters(); -init_concat(); -init_toHex(); -init_keccak256(); -function hashTypedData(parameters) { - const { domain = {}, message, primaryType } = parameters; - const types = { - EIP712Domain: getTypesForEIP712Domain({ domain }), - ...parameters.types - }; - validateTypedData({ - domain, - message, - primaryType, - types - }); - const parts = ["0x1901"]; - if (domain) - parts.push(hashDomain({ - domain, - types - })); - if (primaryType !== "EIP712Domain") - parts.push(hashStruct({ - data: message, - primaryType, - types - })); - return keccak256(concat(parts)); -} -function hashDomain({ domain, types }) { - return hashStruct({ - data: domain, - primaryType: "EIP712Domain", - types - }); +// node_modules/ox/_esm/core/AbiConstructor.js +function encode3(abiConstructor, options) { + const { bytecode, args } = options; + return concat2(bytecode, abiConstructor.inputs?.length && args?.length ? encode2(abiConstructor.inputs, args) : "0x"); } -function hashStruct({ data, primaryType, types }) { - const encoded = encodeData({ - data, - primaryType, - types - }); - return keccak256(encoded); +function from3(abiConstructor) { + return from2(abiConstructor); } -function encodeData({ data, primaryType, types }) { - const encodedTypes = [{ type: "bytes32" }]; - const encodedValues = [hashType({ primaryType, types })]; - for (const field of types[primaryType]) { - const [type, value] = encodeField({ - types, - name: field.name, - type: field.type, - value: data[field.name] - }); - encodedTypes.push(type); - encodedValues.push(value); - } - return encodeAbiParameters(encodedTypes, encodedValues); + +// node_modules/ox/_esm/core/AbiFunction.js +function encodeData2(abiFunction, ...args) { + const { overloads } = abiFunction; + const item = overloads ? fromAbi2([abiFunction, ...overloads], abiFunction.name, { + args: args[0] + }) : abiFunction; + const selector = getSelector2(item); + const data = args.length > 0 ? encode2(item.inputs, args[0]) : void 0; + return data ? concat2(selector, data) : selector; } -function hashType({ primaryType, types }) { - const encodedHashType = toHex(encodeType({ primaryType, types })); - return keccak256(encodedHashType); +function from4(abiFunction, options = {}) { + return from2(abiFunction, options); } -function encodeType({ primaryType, types }) { - let result = ""; - const unsortedDeps = findTypeDependencies({ primaryType, types }); - unsortedDeps.delete(primaryType); - const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; - for (const type of deps) { - result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`; - } - return result; +function fromAbi2(abi4, name, options) { + const item = fromAbi(abi4, name, options); + if (item.type !== "function") + throw new NotFoundError2({ name, type: "function" }); + return item; } -function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) { - const match = primaryType_.match(/^\w*/u); - const primaryType = match?.[0]; - if (results.has(primaryType) || types[primaryType] === void 0) { - return results; - } - results.add(primaryType); - for (const field of types[primaryType]) { - findTypeDependencies({ primaryType: field.type, types }, results); - } - return results; +function getSelector2(abiItem) { + return getSelector(abiItem); } -function encodeField({ types, name, type, value }) { - if (types[type] !== void 0) { - return [ - { type: "bytes32" }, - keccak256(encodeData({ data: value, primaryType: type, types })) - ]; - } - if (type === "bytes") { - const prepend = value.length % 2 ? "0" : ""; - value = `0x${prepend + value.slice(2)}`; - return [{ type: "bytes32" }, keccak256(value)]; - } - if (type === "string") - return [{ type: "bytes32" }, keccak256(toHex(value))]; - if (type.lastIndexOf("]") === type.length - 1) { - const parsedType = type.slice(0, type.lastIndexOf("[")); - const typeValuePairs = value.map((item) => encodeField({ - name, - type: parsedType, - types, - value: item - })); - return [ - { type: "bytes32" }, - keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v))) - ]; + +// node_modules/viem/_esm/actions/public/simulateCalls.js +init_parseAccount(); + +// node_modules/viem/_esm/constants/address.js +var ethAddress = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; +var zeroAddress = "0x0000000000000000000000000000000000000000"; + +// node_modules/viem/_esm/actions/public/simulateCalls.js +init_contracts(); +init_base(); +init_encodeFunctionData(); +var getBalanceCode = "0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033"; +async function simulateCalls(client, parameters) { + const { blockNumber, blockTag, calls, stateOverrides, traceAssetChanges, traceTransfers, validation } = parameters; + const account = parameters.account ? parseAccount(parameters.account) : void 0; + if (traceAssetChanges && !account) + throw new BaseError2("`account` is required when `traceAssetChanges` is true"); + const getBalanceData = account ? encode3(from3("constructor(bytes, bytes)"), { + bytecode: deploylessCallViaBytecodeBytecode, + args: [ + getBalanceCode, + encodeData2(from4("function getBalance(address)"), [account.address]) + ] + }) : void 0; + const assetAddresses = traceAssetChanges ? await Promise.all(parameters.calls.map(async (call2) => { + if (!call2.data && !call2.abi) + return; + const { accessList } = await createAccessList(client, { + account: account.address, + ...call2, + data: call2.abi ? encodeFunctionData(call2) : call2.data + }); + return accessList.map(({ address, storageKeys }) => storageKeys.length > 0 ? address : null); + })).then((x2) => x2.flat().filter(Boolean)) : []; + const resultsStateOverrides = stateOverrides?.map((override) => { + if (override.address === account?.address) + return { + ...override, + nonce: 0 + }; + return override; + }); + const blocks = await simulateBlocks(client, { + blockNumber, + blockTag, + blocks: [ + ...traceAssetChanges ? [ + // ETH pre balances + { + calls: [{ data: getBalanceData }], + stateOverrides + }, + // Asset pre balances + { + calls: assetAddresses.map((address, i) => ({ + abi: [ + from4("function balanceOf(address) returns (uint256)") + ], + functionName: "balanceOf", + args: [account.address], + to: address, + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + } + ] : [], + { + calls: [...calls, {}].map((call2, index2) => ({ + ...call2, + from: account?.address, + nonce: index2 + })), + stateOverrides: resultsStateOverrides + }, + ...traceAssetChanges ? [ + // ETH post balances + { + calls: [{ data: getBalanceData }] + }, + // Asset post balances + { + calls: assetAddresses.map((address, i) => ({ + abi: [ + from4("function balanceOf(address) returns (uint256)") + ], + functionName: "balanceOf", + args: [account.address], + to: address, + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + }, + // Decimals + { + calls: assetAddresses.map((address, i) => ({ + to: address, + abi: [ + from4("function decimals() returns (uint256)") + ], + functionName: "decimals", + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + }, + // Token URI + { + calls: assetAddresses.map((address, i) => ({ + to: address, + abi: [ + from4("function tokenURI(uint256) returns (string)") + ], + functionName: "tokenURI", + args: [0n], + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + }, + // Symbols + { + calls: assetAddresses.map((address, i) => ({ + to: address, + abi: [from4("function symbol() returns (string)")], + functionName: "symbol", + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + } + ] : [] + ], + traceTransfers, + validation + }); + const block_results = traceAssetChanges ? blocks[2] : blocks[0]; + const [block_ethPre, block_assetsPre, , block_ethPost, block_assetsPost, block_decimals, block_tokenURI, block_symbols] = traceAssetChanges ? blocks : []; + const { calls: block_calls, ...block } = block_results; + const results = block_calls.slice(0, -1) ?? []; + const ethPre = block_ethPre?.calls ?? []; + const assetsPre = block_assetsPre?.calls ?? []; + const balancesPre = [...ethPre, ...assetsPre].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null); + const ethPost = block_ethPost?.calls ?? []; + const assetsPost = block_assetsPost?.calls ?? []; + const balancesPost = [...ethPost, ...assetsPost].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null); + const decimals = (block_decimals?.calls ?? []).map((x2) => x2.status === "success" ? x2.result : null); + const symbols = (block_symbols?.calls ?? []).map((x2) => x2.status === "success" ? x2.result : null); + const tokenURI = (block_tokenURI?.calls ?? []).map((x2) => x2.status === "success" ? x2.result : null); + const changes = []; + for (const [i, balancePost] of balancesPost.entries()) { + const balancePre = balancesPre[i]; + if (typeof balancePost !== "bigint") + continue; + if (typeof balancePre !== "bigint") + continue; + const decimals_ = decimals[i - 1]; + const symbol_ = symbols[i - 1]; + const tokenURI_ = tokenURI[i - 1]; + const token = (() => { + if (i === 0) + return { + address: ethAddress, + decimals: 18, + symbol: "ETH" + }; + return { + address: assetAddresses[i - 1], + decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : void 0, + symbol: symbol_ ?? void 0 + }; + })(); + if (changes.some((change) => change.token.address === token.address)) + continue; + changes.push({ + token, + value: { + pre: balancePre, + post: balancePost, + diff: balancePost - balancePre + } + }); } - return [{ type }, value]; + return { + assetChanges: changes, + block, + results + }; } -// node_modules/viem/_esm/utils/typedData.js -init_stringify(); -function serializeTypedData(parameters) { - const { domain: domain_, message: message_, primaryType, types } = parameters; - const normalizeData = (struct, data_) => { - const data = { ...data_ }; - for (const param of struct) { - const { name, type } = param; - if (type === "address") - data[name] = data[name].toLowerCase(); - } - return data; - }; - const domain = (() => { - if (!types.EIP712Domain) - return {}; - if (!domain_) - return {}; - return normalizeData(types.EIP712Domain, domain_); - })(); - const message = (() => { - if (primaryType === "EIP712Domain") - return void 0; - return normalizeData(types[primaryType], message_); +// node_modules/viem/_esm/actions/public/verifyHash.js +init_abis(); +init_contracts(); +init_contract(); +init_encodeDeployData(); +init_getAddress(); +init_isAddressEqual(); +init_isHex(); +init_toHex(); + +// node_modules/viem/_esm/utils/signature/serializeSignature.js +init_secp256k1(); +init_fromHex(); +init_toBytes(); +function serializeSignature({ r, s, to: to2 = "hex", v, yParity }) { + const yParity_ = (() => { + if (yParity === 0 || yParity === 1) + return yParity; + if (v && (v === 27n || v === 28n || v >= 35n)) + return v % 2n === 0n ? 1 : 0; + throw new Error("Invalid `v` or `yParity` value"); })(); - return stringify({ domain, message, primaryType, types }); + const signature = `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`; + if (to2 === "hex") + return signature; + return hexToBytes(signature); } -function validateTypedData(parameters) { - const { domain, message, primaryType, types } = parameters; - const validateData = (struct, data) => { - for (const param of struct) { - const { name, type } = param; - const value = data[name]; - const integerMatch = type.match(integerRegex2); - if (integerMatch && (typeof value === "number" || typeof value === "bigint")) { - const [_type, base, size_] = integerMatch; - numberToHex(value, { - signed: base === "int", - size: Number.parseInt(size_) / 8 - }); - } - if (type === "address" && typeof value === "string" && !isAddress(value)) - throw new InvalidAddressError({ address: value }); - const bytesMatch = type.match(bytesRegex2); - if (bytesMatch) { - const [_type, size_] = bytesMatch; - if (size_ && size(value) !== Number.parseInt(size_)) - throw new BytesSizeMismatchError({ - expectedSize: Number.parseInt(size_), - givenSize: size(value) - }); - } - const struct2 = types[type]; - if (struct2) { - validateReference(type); - validateData(struct2, value); - } + +// node_modules/viem/_esm/actions/public/verifyHash.js +init_call(); +async function verifyHash(client, parameters) { + const { address, factory, factoryData, hash: hash2, signature, universalSignatureVerifierAddress = client.chain?.contracts?.universalSignatureVerifier?.address, ...rest } = parameters; + const signatureHex = (() => { + if (isHex(signature)) + return signature; + if (typeof signature === "object" && "r" in signature && "s" in signature) + return serializeSignature(signature); + return bytesToHex(signature); + })(); + const wrappedSignature = await (async () => { + if (!factory && !factoryData) + return signatureHex; + if (isErc6492Signature(signatureHex)) + return signatureHex; + return serializeErc6492Signature({ + address: factory, + data: factoryData, + signature: signatureHex + }); + })(); + try { + const args = universalSignatureVerifierAddress ? { + to: universalSignatureVerifierAddress, + data: encodeFunctionData({ + abi: universalSignatureValidatorAbi, + functionName: "isValidSig", + args: [address, hash2, wrappedSignature] + }), + ...rest + } : { + data: encodeDeployData({ + abi: universalSignatureValidatorAbi, + args: [address, hash2, wrappedSignature], + bytecode: universalSignatureValidatorByteCode + }), + ...rest + }; + const { data } = await getAction(client, call, "call")(args); + return hexToBool(data ?? "0x0"); + } catch (error) { + try { + const verified = isAddressEqual(getAddress(address), await recoverAddress({ hash: hash2, signature })); + if (verified) + return true; + } catch { } - }; - if (types.EIP712Domain && domain) { - if (typeof domain !== "object") - throw new InvalidDomainError({ domain }); - validateData(types.EIP712Domain, domain); - } - if (primaryType !== "EIP712Domain") { - if (types[primaryType]) - validateData(types[primaryType], message); - else - throw new InvalidPrimaryTypeError({ primaryType, types }); + if (error instanceof CallExecutionError) { + return false; + } + throw error; } } -function getTypesForEIP712Domain({ domain }) { - return [ - typeof domain?.name === "string" && { name: "name", type: "string" }, - domain?.version && { name: "version", type: "string" }, - (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && { - name: "chainId", - type: "uint256" - }, - domain?.verifyingContract && { - name: "verifyingContract", - type: "address" - }, - domain?.salt && { name: "salt", type: "bytes32" } - ].filter(Boolean); -} -function validateReference(type) { - if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int")) - throw new InvalidStructTypeError({ type }); -} -// node_modules/viem/_esm/utils/index.js -init_encodeFunctionData(); +// node_modules/viem/_esm/actions/public/verifyMessage.js +async function verifyMessage(client, { address, message, factory, factoryData, signature, ...callRequest }) { + const hash2 = hashMessage(message); + return verifyHash(client, { + address, + factory, + factoryData, + hash: hash2, + signature, + ...callRequest + }); +} -// node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js -init_toHex(); +// node_modules/viem/_esm/actions/public/verifyTypedData.js +async function verifyTypedData(client, parameters) { + const { address, factory, factoryData, signature, message, primaryType, types, domain, ...callRequest } = parameters; + const hash2 = hashTypedData({ message, primaryType, types, domain }); + return verifyHash(client, { + address, + factory, + factoryData, + hash: hash2, + signature, + ...callRequest + }); +} -// node_modules/viem/_esm/utils/transaction/serializeTransaction.js +// node_modules/viem/_esm/actions/public/waitForTransactionReceipt.js init_transaction(); -init_concat(); -init_trim(); -init_toHex(); +init_withResolvers(); +init_stringify(); -// node_modules/viem/_esm/utils/transaction/assertTransaction.js -init_number(); -init_address(); -init_base(); -init_chain(); -init_node(); -init_isAddress(); -init_size(); -init_slice(); +// node_modules/viem/_esm/actions/public/watchBlockNumber.js init_fromHex(); -function assertTransactionEIP7702(transaction) { - const { authorizationList } = transaction; - if (authorizationList) { - for (const authorization of authorizationList) { - const { chainId } = authorization; - const address = authorization.address; - if (!isAddress(address)) - throw new InvalidAddressError({ address }); - if (chainId < 0) - throw new InvalidChainIdError({ chainId }); - } - } - assertTransactionEIP1559(transaction); +init_stringify(); +function watchBlockNumber(client, { emitOnBegin = false, emitMissed = false, onBlockNumber, onError, poll: poll_, pollingInterval = client.pollingInterval }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (client.transport.type === "webSocket") + return false; + if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + let prevBlockNumber; + const pollBlockNumber = () => { + const observerId = stringify([ + "watchBlockNumber", + client.uid, + emitOnBegin, + emitMissed, + pollingInterval + ]); + return observe(observerId, { onBlockNumber, onError }, (emit) => poll(async () => { + try { + const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({ cacheTime: 0 }); + if (prevBlockNumber) { + if (blockNumber === prevBlockNumber) + return; + if (blockNumber - prevBlockNumber > 1 && emitMissed) { + for (let i = prevBlockNumber + 1n; i < blockNumber; i++) { + emit.onBlockNumber(i, prevBlockNumber); + prevBlockNumber = i; + } + } + } + if (!prevBlockNumber || blockNumber > prevBlockNumber) { + emit.onBlockNumber(blockNumber, prevBlockNumber); + prevBlockNumber = blockNumber; + } + } catch (err) { + emit.onError?.(err); + } + }, { + emitOnBegin, + interval: pollingInterval + })); + }; + const subscribeBlockNumber = () => { + const observerId = stringify([ + "watchBlockNumber", + client.uid, + emitOnBegin, + emitMissed + ]); + return observe(observerId, { onBlockNumber, onError }, (emit) => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["newHeads"], + onData(data) { + if (!active) + return; + const blockNumber = hexToBigInt(data.result?.number); + emit.onBlockNumber(blockNumber, prevBlockNumber); + prevBlockNumber = blockNumber; + }, + onError(error) { + emit.onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }); + }; + return enablePolling ? pollBlockNumber() : subscribeBlockNumber(); } -function assertTransactionEIP4844(transaction) { - const { blobVersionedHashes } = transaction; - if (blobVersionedHashes) { - if (blobVersionedHashes.length === 0) - throw new EmptyBlobError(); - for (const hash2 of blobVersionedHashes) { - const size_ = size(hash2); - const version4 = hexToNumber(slice(hash2, 0, 1)); - if (size_ !== 32) - throw new InvalidVersionedHashSizeError({ hash: hash2, size: size_ }); - if (version4 !== versionedHashVersionKzg) - throw new InvalidVersionedHashVersionError({ - hash: hash2, - version: version4 + +// node_modules/viem/_esm/actions/public/waitForTransactionReceipt.js +async function waitForTransactionReceipt(client, { + confirmations = 1, + hash: hash2, + onReplaced, + pollingInterval = client.pollingInterval, + retryCount = 6, + retryDelay = ({ count }) => ~~(1 << count) * 200, + // exponential backoff + timeout = 18e4 +}) { + const observerId = stringify(["waitForTransactionReceipt", client.uid, hash2]); + let transaction; + let replacedTransaction; + let receipt; + let retrying = false; + const { promise, resolve, reject } = withResolvers(); + const timer = timeout ? setTimeout(() => reject(new WaitForTransactionReceiptTimeoutError({ hash: hash2 })), timeout) : void 0; + const _unobserve = observe(observerId, { onReplaced, resolve, reject }, (emit) => { + const _unwatch = getAction(client, watchBlockNumber, "watchBlockNumber")({ + emitMissed: true, + emitOnBegin: true, + poll: true, + pollingInterval, + async onBlockNumber(blockNumber_) { + const done = (fn2) => { + clearTimeout(timer); + _unwatch(); + fn2(); + _unobserve(); + }; + let blockNumber = blockNumber_; + if (retrying) + return; + try { + if (receipt) { + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + done(() => emit.resolve(receipt)); + return; + } + if (!transaction) { + retrying = true; + await withRetry(async () => { + transaction = await getAction(client, getTransaction, "getTransaction")({ hash: hash2 }); + if (transaction.blockNumber) + blockNumber = transaction.blockNumber; + }, { + delay: retryDelay, + retryCount + }); + retrying = false; + } + receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ hash: hash2 }); + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + done(() => emit.resolve(receipt)); + } catch (err) { + if (err instanceof TransactionNotFoundError || err instanceof TransactionReceiptNotFoundError) { + if (!transaction) { + retrying = false; + return; + } + try { + replacedTransaction = transaction; + retrying = true; + const block = await withRetry(() => getAction(client, getBlock, "getBlock")({ + blockNumber, + includeTransactions: true + }), { + delay: retryDelay, + retryCount, + shouldRetry: ({ error }) => error instanceof BlockNotFoundError + }); + retrying = false; + const replacementTransaction = block.transactions.find(({ from: from5, nonce }) => from5 === replacedTransaction.from && nonce === replacedTransaction.nonce); + if (!replacementTransaction) + return; + receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ + hash: replacementTransaction.hash + }); + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + let reason = "replaced"; + if (replacementTransaction.to === replacedTransaction.to && replacementTransaction.value === replacedTransaction.value && replacementTransaction.input === replacedTransaction.input) { + reason = "repriced"; + } else if (replacementTransaction.from === replacementTransaction.to && replacementTransaction.value === 0n) { + reason = "cancelled"; + } + done(() => { + emit.onReplaced?.({ + reason, + replacedTransaction, + transaction: replacementTransaction, + transactionReceipt: receipt + }); + emit.resolve(receipt); + }); + } catch (err_) { + done(() => emit.reject(err_)); + } + } else { + done(() => emit.reject(err)); + } + } + } + }); + }); + return promise; +} + +// node_modules/viem/_esm/actions/public/watchBlocks.js +init_stringify(); +function watchBlocks(client, { blockTag = "latest", emitMissed = false, emitOnBegin = false, onBlock, onError, includeTransactions: includeTransactions_, poll: poll_, pollingInterval = client.pollingInterval }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (client.transport.type === "webSocket") + return false; + if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + const includeTransactions = includeTransactions_ ?? false; + let prevBlock; + const pollBlocks = () => { + const observerId = stringify([ + "watchBlocks", + client.uid, + blockTag, + emitMissed, + emitOnBegin, + includeTransactions, + pollingInterval + ]); + return observe(observerId, { onBlock, onError }, (emit) => poll(async () => { + try { + const block = await getAction(client, getBlock, "getBlock")({ + blockTag, + includeTransactions + }); + if (block.number && prevBlock?.number) { + if (block.number === prevBlock.number) + return; + if (block.number - prevBlock.number > 1 && emitMissed) { + for (let i = prevBlock?.number + 1n; i < block.number; i++) { + const block2 = await getAction(client, getBlock, "getBlock")({ + blockNumber: i, + includeTransactions + }); + emit.onBlock(block2, prevBlock); + prevBlock = block2; + } + } + } + if ( + // If no previous block exists, emit. + !prevBlock?.number || // If the block tag is "pending" with no block number, emit. + blockTag === "pending" && !block?.number || // If the next block number is greater than the previous block number, emit. + // We don't want to emit blocks in the past. + block.number && block.number > prevBlock.number + ) { + emit.onBlock(block, prevBlock); + prevBlock = block; + } + } catch (err) { + emit.onError?.(err); + } + }, { + emitOnBegin, + interval: pollingInterval + })); + }; + const subscribeBlocks = () => { + let active = true; + let emitFetched = true; + let unsubscribe = () => active = false; + (async () => { + try { + if (emitOnBegin) { + getAction(client, getBlock, "getBlock")({ + blockTag, + includeTransactions + }).then((block) => { + if (!active) + return; + if (!emitFetched) + return; + onBlock(block, void 0); + emitFetched = false; + }); + } + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["newHeads"], + async onData(data) { + if (!active) + return; + const block = await getAction(client, getBlock, "getBlock")({ + blockNumber: data.blockNumber, + includeTransactions + }).catch(() => { + }); + if (!active) + return; + onBlock(block, prevBlock); + emitFetched = false; + prevBlock = block; + }, + onError(error) { + onError?.(error); + } }); - } - } - assertTransactionEIP1559(transaction); -} -function assertTransactionEIP1559(transaction) { - const { chainId, maxPriorityFeePerGas, maxFeePerGas, to: to2 } = transaction; - if (chainId <= 0) - throw new InvalidChainIdError({ chainId }); - if (to2 && !isAddress(to2)) - throw new InvalidAddressError({ address: to2 }); - if (maxFeePerGas && maxFeePerGas > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas }); - if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) - throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); -} -function assertTransactionEIP2930(transaction) { - const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to: to2 } = transaction; - if (chainId <= 0) - throw new InvalidChainIdError({ chainId }); - if (to2 && !isAddress(to2)) - throw new InvalidAddressError({ address: to2 }); - if (maxPriorityFeePerGas || maxFeePerGas) - throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute."); - if (gasPrice && gasPrice > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); -} -function assertTransactionLegacy(transaction) { - const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to: to2 } = transaction; - if (to2 && !isAddress(to2)) - throw new InvalidAddressError({ address: to2 }); - if (typeof chainId !== "undefined" && chainId <= 0) - throw new InvalidChainIdError({ chainId }); - if (maxPriorityFeePerGas || maxFeePerGas) - throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute."); - if (gasPrice && gasPrice > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollBlocks() : subscribeBlocks(); } -// node_modules/viem/_esm/utils/transaction/serializeAccessList.js -init_address(); -init_transaction(); -init_isAddress(); -function serializeAccessList(accessList) { - if (!accessList || accessList.length === 0) - return []; - const serializedAccessList = []; - for (let i = 0; i < accessList.length; i++) { - const { address, storageKeys } = accessList[i]; - for (let j2 = 0; j2 < storageKeys.length; j2++) { - if (storageKeys[j2].length - 2 !== 64) { - throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j2] }); +// node_modules/viem/_esm/actions/public/watchEvent.js +init_stringify(); +init_abi(); +init_rpc(); +function watchEvent(client, { address, args, batch = true, event, events, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (typeof fromBlock === "bigint") + return true; + if (client.transport.type === "webSocket") + return false; + if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") + return false; + return true; + })(); + const strict = strict_ ?? false; + const pollEvent = () => { + const observerId = stringify([ + "watchEvent", + address, + args, + batch, + client.uid, + event, + pollingInterval, + fromBlock + ]); + return observe(observerId, { onLogs, onError }, (emit) => { + let previousBlockNumber; + if (fromBlock !== void 0) + previousBlockNumber = fromBlock - 1n; + let filter2; + let initialized = false; + const unwatch = poll(async () => { + if (!initialized) { + try { + filter2 = await getAction(client, createEventFilter, "createEventFilter")({ + address, + args, + event, + events, + strict, + fromBlock + }); + } catch { + } + initialized = true; + return; + } + try { + let logs; + if (filter2) { + logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter: filter2 }); + } else { + const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({}); + if (previousBlockNumber && previousBlockNumber !== blockNumber) { + logs = await getAction(client, getLogs, "getLogs")({ + address, + args, + event, + events, + fromBlock: previousBlockNumber + 1n, + toBlock: blockNumber + }); + } else { + logs = []; + } + previousBlockNumber = blockNumber; + } + if (logs.length === 0) + return; + if (batch) + emit.onLogs(logs); + else + for (const log of logs) + emit.onLogs([log]); + } catch (err) { + if (filter2 && err instanceof InvalidInputRpcError) + initialized = false; + emit.onError?.(err); + } + }, { + emitOnBegin: true, + interval: pollingInterval + }); + return async () => { + if (filter2) + await getAction(client, uninstallFilter, "uninstallFilter")({ filter: filter2 }); + unwatch(); + }; + }); + }; + const subscribeEvent = () => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const events_ = events ?? (event ? [event] : void 0); + let topics = []; + if (events_) { + const encoded = events_.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["logs", { address, topics }], + onData(data) { + if (!active) + return; + const log = data.result; + try { + const { eventName, args: args2 } = decodeEventLog({ + abi: events_ ?? [], + data: log.data, + topics: log.topics, + strict + }); + const formatted = formatLog(log, { args: args2, eventName }); + onLogs([formatted]); + } catch (err) { + let eventName; + let isUnnamed; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict_) + return; + eventName = err.abiItem.name; + isUnnamed = err.abiItem.inputs?.some((x2) => !("name" in x2 && x2.name)); + } + const formatted = formatLog(log, { + args: isUnnamed ? [] : {}, + eventName + }); + onLogs([formatted]); + } + }, + onError(error) { + onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); } - } - if (!isAddress(address, { strict: false })) { - throw new InvalidAddressError({ address }); - } - serializedAccessList.push([address, storageKeys]); - } - return serializedAccessList; + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollEvent() : subscribeEvent(); } -// node_modules/viem/_esm/utils/transaction/serializeTransaction.js -function serializeTransaction(transaction, signature) { - const type = getTransactionType(transaction); - if (type === "eip1559") - return serializeTransactionEIP1559(transaction, signature); - if (type === "eip2930") - return serializeTransactionEIP2930(transaction, signature); - if (type === "eip4844") - return serializeTransactionEIP4844(transaction, signature); - if (type === "eip7702") - return serializeTransactionEIP7702(transaction, signature); - return serializeTransactionLegacy(transaction, signature); -} -function serializeTransactionEIP7702(transaction, signature) { - const { authorizationList, chainId, gas, nonce, to: to2, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; - assertTransactionEIP7702(transaction); - const serializedAccessList = serializeAccessList(accessList); - const serializedAuthorizationList = serializeAuthorizationList(authorizationList); - return concatHex([ - "0x04", - toRlp([ - toHex(chainId), - nonce ? toHex(nonce) : "0x", - maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", - maxFeePerGas ? toHex(maxFeePerGas) : "0x", - gas ? toHex(gas) : "0x", - to2 ?? "0x", - value ? toHex(value) : "0x", - data ?? "0x", - serializedAccessList, - serializedAuthorizationList, - ...toYParitySignatureArray(transaction, signature) - ]) - ]); -} -function serializeTransactionEIP4844(transaction, signature) { - const { chainId, gas, nonce, to: to2, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; - assertTransactionEIP4844(transaction); - let blobVersionedHashes = transaction.blobVersionedHashes; - let sidecars = transaction.sidecars; - if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) { - const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x2) => bytesToHex(x2)); - const kzg = transaction.kzg; - const commitments2 = blobsToCommitments({ - blobs: blobs2, - kzg - }); - if (typeof blobVersionedHashes === "undefined") - blobVersionedHashes = commitmentsToVersionedHashes({ - commitments: commitments2 +// node_modules/viem/_esm/actions/public/watchPendingTransactions.js +init_stringify(); +function watchPendingTransactions(client, { batch = true, onError, onTransactions, poll: poll_, pollingInterval = client.pollingInterval }) { + const enablePolling = typeof poll_ !== "undefined" ? poll_ : client.transport.type !== "webSocket"; + const pollPendingTransactions = () => { + const observerId = stringify([ + "watchPendingTransactions", + client.uid, + batch, + pollingInterval + ]); + return observe(observerId, { onTransactions, onError }, (emit) => { + let filter2; + const unwatch = poll(async () => { + try { + if (!filter2) { + try { + filter2 = await getAction(client, createPendingTransactionFilter, "createPendingTransactionFilter")({}); + return; + } catch (err) { + unwatch(); + throw err; + } + } + const hashes = await getAction(client, getFilterChanges, "getFilterChanges")({ filter: filter2 }); + if (hashes.length === 0) + return; + if (batch) + emit.onTransactions(hashes); + else + for (const hash2 of hashes) + emit.onTransactions([hash2]); + } catch (err) { + emit.onError?.(err); + } + }, { + emitOnBegin: true, + interval: pollingInterval }); - if (typeof sidecars === "undefined") { - const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg }); - sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 }); - } - } - const serializedAccessList = serializeAccessList(accessList); - const serializedTransaction = [ - toHex(chainId), - nonce ? toHex(nonce) : "0x", - maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", - maxFeePerGas ? toHex(maxFeePerGas) : "0x", - gas ? toHex(gas) : "0x", - to2 ?? "0x", - value ? toHex(value) : "0x", - data ?? "0x", - serializedAccessList, - maxFeePerBlobGas ? toHex(maxFeePerBlobGas) : "0x", - blobVersionedHashes ?? [], - ...toYParitySignatureArray(transaction, signature) - ]; - const blobs = []; - const commitments = []; - const proofs = []; - if (sidecars) - for (let i = 0; i < sidecars.length; i++) { - const { blob, commitment, proof } = sidecars[i]; - blobs.push(blob); - commitments.push(commitment); - proofs.push(proof); - } - return concatHex([ - "0x03", - sidecars ? ( - // If sidecars are enabled, envelope turns into a "wrapper": - toRlp([serializedTransaction, blobs, commitments, proofs]) - ) : ( - // If sidecars are disabled, standard envelope is used: - toRlp(serializedTransaction) - ) - ]); -} -function serializeTransactionEIP1559(transaction, signature) { - const { chainId, gas, nonce, to: to2, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; - assertTransactionEIP1559(transaction); - const serializedAccessList = serializeAccessList(accessList); - const serializedTransaction = [ - toHex(chainId), - nonce ? toHex(nonce) : "0x", - maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", - maxFeePerGas ? toHex(maxFeePerGas) : "0x", - gas ? toHex(gas) : "0x", - to2 ?? "0x", - value ? toHex(value) : "0x", - data ?? "0x", - serializedAccessList, - ...toYParitySignatureArray(transaction, signature) - ]; - return concatHex([ - "0x02", - toRlp(serializedTransaction) - ]); -} -function serializeTransactionEIP2930(transaction, signature) { - const { chainId, gas, data, nonce, to: to2, value, accessList, gasPrice } = transaction; - assertTransactionEIP2930(transaction); - const serializedAccessList = serializeAccessList(accessList); - const serializedTransaction = [ - toHex(chainId), - nonce ? toHex(nonce) : "0x", - gasPrice ? toHex(gasPrice) : "0x", - gas ? toHex(gas) : "0x", - to2 ?? "0x", - value ? toHex(value) : "0x", - data ?? "0x", - serializedAccessList, - ...toYParitySignatureArray(transaction, signature) - ]; - return concatHex([ - "0x01", - toRlp(serializedTransaction) - ]); -} -function serializeTransactionLegacy(transaction, signature) { - const { chainId = 0, gas, data, nonce, to: to2, value, gasPrice } = transaction; - assertTransactionLegacy(transaction); - let serializedTransaction = [ - nonce ? toHex(nonce) : "0x", - gasPrice ? toHex(gasPrice) : "0x", - gas ? toHex(gas) : "0x", - to2 ?? "0x", - value ? toHex(value) : "0x", - data ?? "0x" - ]; - if (signature) { - const v = (() => { - if (signature.v >= 35n) { - const inferredChainId = (signature.v - 35n) / 2n; - if (inferredChainId > 0) - return signature.v; - return 27n + (signature.v === 35n ? 0n : 1n); + return async () => { + if (filter2) + await getAction(client, uninstallFilter, "uninstallFilter")({ filter: filter2 }); + unwatch(); + }; + }); + }; + const subscribePendingTransactions = () => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({ + params: ["newPendingTransactions"], + onData(data) { + if (!active) + return; + const transaction = data.result; + onTransactions([transaction]); + }, + onError(error) { + onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); } - if (chainId > 0) - return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n); - const v2 = 27n + (signature.v === 27n ? 0n : 1n); - if (signature.v !== v2) - throw new InvalidLegacyVError({ v: signature.v }); - return v2; - })(); - const r = trim2(signature.r); - const s = trim2(signature.s); - serializedTransaction = [ - ...serializedTransaction, - toHex(v), - r === "0x00" ? "0x" : r, - s === "0x00" ? "0x" : s - ]; - } else if (chainId > 0) { - serializedTransaction = [ - ...serializedTransaction, - toHex(chainId), - "0x", - "0x" - ]; - } - return toRlp(serializedTransaction); + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollPendingTransactions() : subscribePendingTransactions(); } -function toYParitySignatureArray(transaction, signature_) { - const signature = signature_ ?? transaction; - const { v, yParity } = signature; - if (typeof signature.r === "undefined") - return []; - if (typeof signature.s === "undefined") - return []; - if (typeof v === "undefined" && typeof yParity === "undefined") - return []; - const r = trim2(signature.r); - const s = trim2(signature.s); - const yParity_ = (() => { - if (typeof yParity === "number") - return yParity ? toHex(1) : "0x"; - if (v === 0n) - return "0x"; - if (v === 1n) - return toHex(1); - return v === 27n ? "0x" : toHex(1); - })(); - return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s]; + +// node_modules/viem/_esm/utils/siwe/parseSiweMessage.js +function parseSiweMessage(message) { + const { scheme, statement, ...prefix } = message.match(prefixRegex)?.groups ?? {}; + const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = message.match(suffixRegex)?.groups ?? {}; + const resources = message.split("Resources:")[1]?.split("\n- ").slice(1); + return { + ...prefix, + ...suffix, + ...chainId ? { chainId: Number(chainId) } : {}, + ...expirationTime ? { expirationTime: new Date(expirationTime) } : {}, + ...issuedAt ? { issuedAt: new Date(issuedAt) } : {}, + ...notBefore ? { notBefore: new Date(notBefore) } : {}, + ...requestId ? { requestId } : {}, + ...resources ? { resources } : {}, + ...scheme ? { scheme } : {}, + ...statement ? { statement } : {} + }; } +var prefixRegex = /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/; +var suffixRegex = /(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/; -// node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js -function serializeAuthorizationList(authorizationList) { - if (!authorizationList || authorizationList.length === 0) - return []; - const serializedAuthorizationList = []; - for (const authorization of authorizationList) { - const { chainId, nonce, ...signature } = authorization; - const contractAddress = authorization.address; - serializedAuthorizationList.push([ - chainId ? toHex(chainId) : "0x", - contractAddress, - nonce ? toHex(nonce) : "0x", - ...toYParitySignatureArray({}, signature) - ]); +// node_modules/viem/_esm/utils/siwe/validateSiweMessage.js +init_isAddressEqual(); +function validateSiweMessage(parameters) { + const { address, domain, message, nonce, scheme, time = /* @__PURE__ */ new Date() } = parameters; + if (domain && message.domain !== domain) + return false; + if (nonce && message.nonce !== nonce) + return false; + if (scheme && message.scheme !== scheme) + return false; + if (message.expirationTime && time >= message.expirationTime) + return false; + if (message.notBefore && time < message.notBefore) + return false; + try { + if (!message.address) + return false; + if (address && !isAddressEqual(message.address, address)) + return false; + } catch { + return false; } - return serializedAuthorizationList; + return true; } -// node_modules/viem/_esm/utils/formatters/transactionReceipt.js -init_fromHex(); -var receiptStatuses = { - "0x0": "reverted", - "0x1": "success" -}; -function formatTransactionReceipt(transactionReceipt) { - const receipt = { - ...transactionReceipt, - blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null, - contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null, - cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null, - effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null, - gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null, - logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null, - to: transactionReceipt.to ? transactionReceipt.to : null, - transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null, - status: transactionReceipt.status ? receiptStatuses[transactionReceipt.status] : null, - type: transactionReceipt.type ? transactionType[transactionReceipt.type] || transactionReceipt.type : null - }; - if (transactionReceipt.blobGasPrice) - receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice); - if (transactionReceipt.blobGasUsed) - receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed); - return receipt; +// node_modules/viem/_esm/actions/siwe/verifySiweMessage.js +async function verifySiweMessage(client, parameters) { + const { address, domain, message, nonce, scheme, signature, time = /* @__PURE__ */ new Date(), ...callRequest } = parameters; + const parsed = parseSiweMessage(message); + if (!parsed.address) + return false; + const isValid = validateSiweMessage({ + address, + domain, + message: parsed, + nonce, + scheme, + time + }); + if (!isValid) + return false; + const hash2 = hashMessage(message); + return verifyHash(client, { + address: parsed.address, + hash: hash2, + signature, + ...callRequest + }); } -// node_modules/viem/_esm/utils/index.js -init_fromHex(); - -// node_modules/viem/_esm/utils/signature/hashMessage.js -init_keccak256(); +// node_modules/viem/_esm/clients/decorators/public.js +function publicActions(client) { + return { + call: (args) => call(client, args), + createAccessList: (args) => createAccessList(client, args), + createBlockFilter: () => createBlockFilter(client), + createContractEventFilter: (args) => createContractEventFilter(client, args), + createEventFilter: (args) => createEventFilter(client, args), + createPendingTransactionFilter: () => createPendingTransactionFilter(client), + estimateContractGas: (args) => estimateContractGas(client, args), + estimateGas: (args) => estimateGas(client, args), + getBalance: (args) => getBalance(client, args), + getBlobBaseFee: () => getBlobBaseFee(client), + getBlock: (args) => getBlock(client, args), + getBlockNumber: (args) => getBlockNumber(client, args), + getBlockTransactionCount: (args) => getBlockTransactionCount(client, args), + getBytecode: (args) => getCode(client, args), + getChainId: () => getChainId(client), + getCode: (args) => getCode(client, args), + getContractEvents: (args) => getContractEvents(client, args), + getEip712Domain: (args) => getEip712Domain(client, args), + getEnsAddress: (args) => getEnsAddress(client, args), + getEnsAvatar: (args) => getEnsAvatar(client, args), + getEnsName: (args) => getEnsName(client, args), + getEnsResolver: (args) => getEnsResolver(client, args), + getEnsText: (args) => getEnsText(client, args), + getFeeHistory: (args) => getFeeHistory(client, args), + estimateFeesPerGas: (args) => estimateFeesPerGas(client, args), + getFilterChanges: (args) => getFilterChanges(client, args), + getFilterLogs: (args) => getFilterLogs(client, args), + getGasPrice: () => getGasPrice(client), + getLogs: (args) => getLogs(client, args), + getProof: (args) => getProof(client, args), + estimateMaxPriorityFeePerGas: (args) => estimateMaxPriorityFeePerGas(client, args), + getStorageAt: (args) => getStorageAt(client, args), + getTransaction: (args) => getTransaction(client, args), + getTransactionConfirmations: (args) => getTransactionConfirmations(client, args), + getTransactionCount: (args) => getTransactionCount(client, args), + getTransactionReceipt: (args) => getTransactionReceipt(client, args), + multicall: (args) => multicall(client, args), + prepareTransactionRequest: (args) => prepareTransactionRequest(client, args), + readContract: (args) => readContract(client, args), + sendRawTransaction: (args) => sendRawTransaction(client, args), + simulate: (args) => simulateBlocks(client, args), + simulateBlocks: (args) => simulateBlocks(client, args), + simulateCalls: (args) => simulateCalls(client, args), + simulateContract: (args) => simulateContract(client, args), + verifyMessage: (args) => verifyMessage(client, args), + verifySiweMessage: (args) => verifySiweMessage(client, args), + verifyTypedData: (args) => verifyTypedData(client, args), + uninstallFilter: (args) => uninstallFilter(client, args), + waitForTransactionReceipt: (args) => waitForTransactionReceipt(client, args), + watchBlocks: (args) => watchBlocks(client, args), + watchBlockNumber: (args) => watchBlockNumber(client, args), + watchContractEvent: (args) => watchContractEvent(client, args), + watchEvent: (args) => watchEvent(client, args), + watchPendingTransactions: (args) => watchPendingTransactions(client, args) + }; +} -// node_modules/viem/_esm/constants/strings.js -var presignMessagePrefix = "Ethereum Signed Message:\n"; +// node_modules/viem/_esm/clients/createPublicClient.js +function createPublicClient(parameters) { + const { key = "public", name = "Public Client" } = parameters; + const client = createClient({ + ...parameters, + key, + name, + type: "publicClient" + }); + return client.extend(publicActions); +} -// node_modules/viem/_esm/utils/signature/toPrefixedMessage.js -init_concat(); -init_size(); -init_toHex(); -function toPrefixedMessage(message_) { - const message = (() => { - if (typeof message_ === "string") - return stringToHex(message_); - if (typeof message_.raw === "string") - return message_.raw; - return bytesToHex(message_.raw); - })(); - const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`); - return concat([prefix, message]); +// node_modules/viem/_esm/actions/wallet/deployContract.js +init_encodeDeployData(); +function deployContract(walletClient, parameters) { + const { abi: abi4, args, bytecode, ...request } = parameters; + const calldata = encodeDeployData({ abi: abi4, args, bytecode }); + return sendTransaction(walletClient, { + ...request, + ...request.authorizationList ? { to: null } : {}, + data: calldata + }); } -// node_modules/viem/_esm/utils/signature/hashMessage.js -function hashMessage(message, to_) { - return keccak256(toPrefixedMessage(message), to_); +// node_modules/viem/_esm/actions/wallet/getAddresses.js +init_getAddress(); +async function getAddresses(client) { + if (client.account?.type === "local") + return [client.account.address]; + const addresses = await client.request({ method: "eth_accounts" }, { dedupe: true }); + return addresses.map((address) => checksumAddress(address)); } -// node_modules/viem/_esm/constants/bytes.js -var erc6492MagicBytes = "0x6492649264926492649264926492649264926492649264926492649264926492"; +// node_modules/viem/_esm/actions/wallet/getPermissions.js +async function getPermissions(client) { + const permissions = await client.request({ method: "wallet_getPermissions" }, { dedupe: true }); + return permissions; +} -// node_modules/viem/_esm/utils/signature/isErc6492Signature.js -init_slice(); -function isErc6492Signature(signature) { - return sliceHex(signature, -32) === erc6492MagicBytes; +// node_modules/viem/_esm/actions/wallet/prepareAuthorization.js +init_parseAccount(); +init_isAddressEqual(); +async function prepareAuthorization(client, parameters) { + const { account: account_ = client.account, chainId, nonce } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/eip7702/prepareAuthorization" + }); + const account = parseAccount(account_); + const executor = (() => { + if (!parameters.executor) + return void 0; + if (parameters.executor === "self") + return parameters.executor; + return parseAccount(parameters.executor); + })(); + const authorization = { + address: parameters.contractAddress ?? parameters.address, + chainId, + nonce + }; + if (typeof authorization.chainId === "undefined") + authorization.chainId = client.chain?.id ?? await getAction(client, getChainId, "getChainId")({}); + if (typeof authorization.nonce === "undefined") { + authorization.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({ + address: account.address, + blockTag: "pending" + }); + if (executor === "self" || executor?.address && isAddressEqual(executor.address, account.address)) + authorization.nonce += 1; + } + return authorization; } -// node_modules/viem/_esm/utils/signature/serializeErc6492Signature.js -init_encodeAbiParameters(); -init_concat(); -init_toBytes(); -function serializeErc6492Signature(parameters) { - const { address, data, signature, to: to2 = "hex" } = parameters; - const signature_ = concatHex([ - encodeAbiParameters([{ type: "address" }, { type: "bytes" }, { type: "bytes" }], [address, data, signature]), - erc6492MagicBytes - ]); - if (to2 === "hex") - return signature_; - return hexToBytes(signature_); +// node_modules/viem/_esm/actions/wallet/requestAddresses.js +init_getAddress(); +async function requestAddresses(client) { + const addresses = await client.request({ method: "eth_requestAccounts" }, { dedupe: true, retryCount: 0 }); + return addresses.map((address) => getAddress(address)); } -// node_modules/viem/_esm/utils/formatters/proof.js -function formatStorageProof(storageProof) { - return storageProof.map((proof) => ({ - ...proof, - value: BigInt(proof.value) - })); +// node_modules/viem/_esm/actions/wallet/requestPermissions.js +async function requestPermissions(client, permissions) { + return client.request({ + method: "wallet_requestPermissions", + params: [permissions] + }, { retryCount: 0 }); } -function formatProof(proof) { - return { - ...proof, - balance: proof.balance ? BigInt(proof.balance) : void 0, - nonce: proof.nonce ? hexToNumber(proof.nonce) : void 0, - storageProof: proof.storageProof ? formatStorageProof(proof.storageProof) : void 0 - }; + +// node_modules/viem/_esm/actions/wallet/signAuthorization.js +init_parseAccount(); +async function signAuthorization(client, parameters) { + const { account: account_ = client.account } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/eip7702/signAuthorization" + }); + const account = parseAccount(account_); + if (!account.signAuthorization) + throw new AccountTypeNotSupportedError({ + docsPath: "/docs/eip7702/signAuthorization", + metaMessages: [ + "The `signAuthorization` Action does not support JSON-RPC Accounts." + ], + type: account.type + }); + const authorization = await prepareAuthorization(client, parameters); + return account.signAuthorization(authorization); } -// node_modules/viem/_esm/actions/public/getProof.js -async function getProof(client, { address, blockNumber, blockTag: blockTag_, storageKeys }) { - const blockTag = blockTag_ ?? "latest"; - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - const proof = await client.request({ - method: "eth_getProof", - params: [address, storageKeys, blockNumberHex || blockTag] - }); - return formatProof(proof); +// node_modules/viem/_esm/actions/wallet/signMessage.js +init_parseAccount(); +init_toHex(); +async function signMessage(client, { account: account_ = client.account, message }) { + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signMessage" + }); + const account = parseAccount(account_); + if (account.signMessage) + return account.signMessage({ message }); + const message_ = (() => { + if (typeof message === "string") + return stringToHex(message); + if (message.raw instanceof Uint8Array) + return toHex(message.raw); + return message.raw; + })(); + return client.request({ + method: "personal_sign", + params: [message_, account.address] + }, { retryCount: 0 }); } -// node_modules/viem/_esm/actions/public/getStorageAt.js +// node_modules/viem/_esm/actions/wallet/signTransaction.js +init_parseAccount(); init_toHex(); -async function getStorageAt(client, { address, blockNumber, blockTag = "latest", slot }) { - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - const data = await client.request({ - method: "eth_getStorageAt", - params: [address, slot, blockNumberHex || blockTag] +init_transactionRequest(); +init_assertRequest(); +async function signTransaction(client, parameters) { + const { account: account_ = client.account, chain = client.chain, ...transaction } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signTransaction" + }); + const account = parseAccount(account_); + assertRequest({ + account, + ...parameters }); - return data; + const chainId = await getAction(client, getChainId, "getChainId")({}); + if (chain !== null) + assertCurrentChain({ + currentChainId: chainId, + chain + }); + const formatters = chain?.formatters || client.chain?.formatters; + const format = formatters?.transactionRequest?.format || formatTransactionRequest; + if (account.signTransaction) + return account.signTransaction({ + ...transaction, + chainId + }, { serializer: client.chain?.serializers?.transaction }); + return await client.request({ + method: "eth_signTransaction", + params: [ + { + ...format(transaction), + chainId: numberToHex(chainId), + from: account.address + } + ] + }, { retryCount: 0 }); } -// node_modules/viem/_esm/actions/public/getTransaction.js -init_transaction(); -init_toHex(); -async function getTransaction(client, { blockHash, blockNumber, blockTag: blockTag_, hash: hash2, index: index2 }) { - const blockTag = blockTag_ || "latest"; - const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0; - let transaction = null; - if (hash2) { - transaction = await client.request({ - method: "eth_getTransactionByHash", - params: [hash2] - }, { dedupe: true }); - } else if (blockHash) { - transaction = await client.request({ - method: "eth_getTransactionByBlockHashAndIndex", - params: [blockHash, numberToHex(index2)] - }, { dedupe: true }); - } else if (blockNumberHex || blockTag) { - transaction = await client.request({ - method: "eth_getTransactionByBlockNumberAndIndex", - params: [blockNumberHex || blockTag, numberToHex(index2)] - }, { dedupe: Boolean(blockNumberHex) }); - } - if (!transaction) - throw new TransactionNotFoundError({ - blockHash, - blockNumber, - blockTag, - hash: hash2, - index: index2 +// node_modules/viem/_esm/actions/wallet/signTypedData.js +init_parseAccount(); +async function signTypedData(client, parameters) { + const { account: account_ = client.account, domain, message, primaryType } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signTypedData" }); - const format = client.chain?.formatters?.transaction?.format || formatTransaction; - return format(transaction); + const account = parseAccount(account_); + const types = { + EIP712Domain: getTypesForEIP712Domain({ domain }), + ...parameters.types + }; + validateTypedData({ domain, message, primaryType, types }); + if (account.signTypedData) + return account.signTypedData({ domain, message, primaryType, types }); + const typedData = serializeTypedData({ domain, message, primaryType, types }); + return client.request({ + method: "eth_signTypedData_v4", + params: [account.address, typedData] + }, { retryCount: 0 }); } -// node_modules/viem/_esm/actions/public/getTransactionConfirmations.js -async function getTransactionConfirmations(client, { hash: hash2, transactionReceipt }) { - const [blockNumber, transaction] = await Promise.all([ - getAction(client, getBlockNumber, "getBlockNumber")({}), - hash2 ? getAction(client, getTransaction, "getTransaction")({ hash: hash2 }) : void 0 - ]); - const transactionBlockNumber = transactionReceipt?.blockNumber || transaction?.blockNumber; - if (!transactionBlockNumber) - return 0n; - return blockNumber - transactionBlockNumber + 1n; +// node_modules/viem/_esm/actions/wallet/switchChain.js +init_toHex(); +async function switchChain(client, { id: id2 }) { + await client.request({ + method: "wallet_switchEthereumChain", + params: [ + { + chainId: numberToHex(id2) + } + ] + }, { retryCount: 0 }); +} + +// node_modules/viem/_esm/actions/wallet/watchAsset.js +async function watchAsset(client, params) { + const added = await client.request({ + method: "wallet_watchAsset", + params + }, { retryCount: 0 }); + return added; +} + +// node_modules/viem/_esm/clients/decorators/wallet.js +function walletActions(client) { + return { + addChain: (args) => addChain(client, args), + deployContract: (args) => deployContract(client, args), + getAddresses: () => getAddresses(client), + getChainId: () => getChainId(client), + getPermissions: () => getPermissions(client), + prepareAuthorization: (args) => prepareAuthorization(client, args), + prepareTransactionRequest: (args) => prepareTransactionRequest(client, args), + requestAddresses: () => requestAddresses(client), + requestPermissions: (args) => requestPermissions(client, args), + sendRawTransaction: (args) => sendRawTransaction(client, args), + sendTransaction: (args) => sendTransaction(client, args), + signAuthorization: (args) => signAuthorization(client, args), + signMessage: (args) => signMessage(client, args), + signTransaction: (args) => signTransaction(client, args), + signTypedData: (args) => signTypedData(client, args), + switchChain: (args) => switchChain(client, args), + watchAsset: (args) => watchAsset(client, args), + writeContract: (args) => writeContract(client, args) + }; } -// node_modules/viem/_esm/actions/public/getTransactionReceipt.js -init_transaction(); -async function getTransactionReceipt(client, { hash: hash2 }) { - const receipt = await client.request({ - method: "eth_getTransactionReceipt", - params: [hash2] - }, { dedupe: true }); - if (!receipt) - throw new TransactionReceiptNotFoundError({ hash: hash2 }); - const format = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt; - return format(receipt); +// node_modules/viem/_esm/clients/createWalletClient.js +function createWalletClient(parameters) { + const { key = "wallet", name = "Wallet Client", transport } = parameters; + const client = createClient({ + ...parameters, + key, + name, + transport, + type: "walletClient" + }); + return client.extend(walletActions); } -// node_modules/viem/_esm/actions/public/multicall.js -init_abis(); +// node_modules/viem/_esm/index.js init_abi(); -init_base(); init_contract(); -init_decodeFunctionResult(); -init_encodeFunctionData(); -init_getChainContractAddress(); -async function multicall(client, parameters) { - const { allowFailure = true, batchSize: batchSize_, blockNumber, blockTag, multicallAddress: multicallAddress_, stateOverride } = parameters; - const contracts = parameters.contracts; - const batchSize = batchSize_ ?? (typeof client.batch?.multicall === "object" && client.batch.multicall.batchSize || 1024); - let multicallAddress = multicallAddress_; - if (!multicallAddress) { - if (!client.chain) - throw new Error("client chain not configured. multicallAddress is required."); - multicallAddress = getChainContractAddress({ - blockNumber, - chain: client.chain, - contract: "multicall3" +init_rpc(); +init_node(); +init_request(); +init_transaction(); +init_decodeAbiParameters(); +init_encodeAbiParameters(); +init_getAbiItem(); +init_toBytes(); +init_formatUnits(); +init_isHex(); +init_keccak256(); + +// src/common/utils/viemErrorParser.ts +function isNonceError(error) { + return error instanceof ContractFunctionExecutionError && error.cause instanceof TransactionExecutionError && (error.cause.cause instanceof NonceTooHighError || error.cause.cause instanceof NonceTooLowError); +} +function isWaitingForReceiptError(error) { + return error instanceof TransactionNotFoundError || error instanceof WaitForTransactionReceiptTimeoutError; +} + +// src/common/utils/callContract.ts +async function executeTransaction(publicClient, walletClient, params, nonceManager) { + const chainId = publicClient.chain.id; + const address = walletClient.account.address; + let txHash; + if (globalConfig.VIEM.SIMULATE_TX) { + const { request } = await publicClient.simulateContract(params); + txHash = await walletClient.writeContract({ request }); + } else { + const nonce = await nonceManager.consume({ + address, + chainId, + client: publicClient }); + const paramsToSend = { + gas: globalConfig.TX_MANAGER.GAS_LIMIT.DEFAULT, + ...params, + nonce + }; + txHash = await walletClient.writeContract(paramsToSend); } - const chunkedCalls = [[]]; - let currentChunk = 0; - let currentChunkSize = 0; - for (let i = 0; i < contracts.length; i++) { - const { abi: abi4, address, args, functionName } = contracts[i]; - try { - const callData = encodeFunctionData({ abi: abi4, args, functionName }); - currentChunkSize += (callData.length - 2) / 2; - if ( - // Check if batching is enabled. - batchSize > 0 && // Check if the current size of the batch exceeds the size limit. - currentChunkSize > batchSize && // Check if the current chunk is not already empty. - chunkedCalls[currentChunk].length > 0 - ) { - currentChunk++; - currentChunkSize = (callData.length - 2) / 2; - chunkedCalls[currentChunk] = []; + await publicClient.waitForTransactionReceipt({ + hash: txHash, + confirmations: confirmations_default[chainId.toString()] ?? void 0 + }); + return txHash; +} +async function callContract(publicClient, walletClient, params) { + try { + const nonceManager = NonceManager.getInstance(); + const isRetryableError = async (error) => { + if (isNonceError(error) || isWaitingForReceiptError(error)) { + const chainId = publicClient.chain.id; + const address = walletClient.account.address; + nonceManager.reset({ chainId, address }); + return true; } - chunkedCalls[currentChunk] = [ - ...chunkedCalls[currentChunk], - { - allowFailure: true, - callData, - target: address - } - ]; - } catch (err) { - const error = getContractError(err, { - abi: abi4, - address, - args, - docsPath: "/docs/contract/multicall", - functionName - }); - if (!allowFailure) - throw error; - chunkedCalls[currentChunk] = [ - ...chunkedCalls[currentChunk], - { - allowFailure: true, - callData: "0x", - target: address - } - ]; + return false; + }; + return asyncRetry( + () => executeTransaction(publicClient, walletClient, params, nonceManager), + { + maxRetries: 20, + delayMs: 1e3, + isRetryableError + } + ); + } catch (error) { + throw new AppError("ContractCallError" /* ContractCallError */, error); + } +} + +// src/common/utils/checkGas.ts +var import_web_api = __toESM(require_dist4(), 1); +var SAFE_TXS_COUNT_FOR_OPERATOR_BALANCE = 15n; +async function notifyInSlack(message) { + try { + if (!globalConfig.NOTIFICATIONS.SLACK.MONITORING_SYSTEM_CHANNEL_ID || !globalConfig.NOTIFICATIONS.SLACK.BOT_TOKEN) { + return; + } + const webClient = new import_web_api.WebClient(globalConfig.NOTIFICATIONS.SLACK.BOT_TOKEN); + const res = await webClient.chat.postMessage({ + channel: globalConfig.NOTIFICATIONS.SLACK.MONITORING_SYSTEM_CHANNEL_ID, + text: message + }); + if (!res.ok) { + console.error(`Failed to send message to slack: ${res.error}`); } + } catch (error) { + console.error(JSON.stringify(error, null, 2)); } - const aggregate3Results = await Promise.allSettled(chunkedCalls.map((calls) => getAction(client, readContract, "readContract")({ - abi: multicall3Abi, - address: multicallAddress, - args: [calls], - blockNumber, - blockTag, - functionName: "aggregate3", - stateOverride - }))); - const results = []; - for (let i = 0; i < aggregate3Results.length; i++) { - const result = aggregate3Results[i]; - if (result.status === "rejected") { - if (!allowFailure) - throw result.reason; - for (let j2 = 0; j2 < chunkedCalls[i].length; j2++) { - results.push({ - status: "failure", - error: result.reason, - result: void 0 - }); - } - continue; +} +async function getChainOperatorMinBalance(publicClient) { + const currentGasPrice = await publicClient.getGasPrice(); + const averageTxCostInWei = currentGasPrice * globalConfig.TX_MANAGER.GAS_LIMIT.DEFAULT; + return averageTxCostInWei * SAFE_TXS_COUNT_FOR_OPERATOR_BALANCE; +} +async function checkAndNotifyInsufficientGas() { + const operatorAddress = globalConfig.OPERATOR_ADDRESS; + const viemClientManager = ViemClientManager.getInstance(); + const networkManager = NetworkManager.getInstance(); + const logger = Logger.getInstance().getLogger("GasChecker"); + try { + const activeNetworks = networkManager.getActiveNetworks(); + if (activeNetworks.length === 0) { + logger.warn("No active networks found when checking gas balances"); + return; } - const aggregate3Result = result.value; - for (let j2 = 0; j2 < aggregate3Result.length; j2++) { - const { returnData, success } = aggregate3Result[j2]; - const { callData } = chunkedCalls[i][j2]; - const { abi: abi4, address, functionName, args } = contracts[results.length]; - try { - if (callData === "0x") - throw new AbiDecodingZeroDataError(); - if (!success) - throw new RawContractError({ data: returnData }); - const result2 = decodeFunctionResult({ - abi: abi4, - args, - data: returnData, - functionName - }); - results.push(allowFailure ? { result: result2, status: "success" } : result2); - } catch (err) { - const error = getContractError(err, { - abi: abi4, - address, - args, - docsPath: "/docs/contract/multicall", - functionName - }); - if (!allowFailure) - throw error; - results.push({ error, result: void 0, status: "failure" }); + const balancePromises = activeNetworks.map(async (network) => { + const { publicClient } = viemClientManager.getClients(network); + const [balance, operatorMinBalance] = await Promise.all([ + publicClient.getBalance({ + address: operatorAddress + }), + getChainOperatorMinBalance(publicClient) + ]); + return { network, balance, operatorMinBalance }; + }); + const chainsInfo = await Promise.all(balancePromises); + for (const chainInfo of chainsInfo) { + const { balance, operatorMinBalance, network } = chainInfo; + if (balance < operatorMinBalance) { + const message = `Insufficient gas on ${network.name} (chain ID: ${network.id}). Minimum required: ${formatUnits(operatorMinBalance, 18)}, actual: ${formatUnits(balance, 18)}`; + await notifyInSlack(message); + logger.info(message); } } + } catch (error) { + logger.error("Error checking gas balances:", error); } - if (results.length !== contracts.length) - throw new BaseError2("multicall results mismatch"); - return results; } - -// node_modules/ox/_esm/core/version.js -var version3 = "0.1.1"; - -// node_modules/ox/_esm/core/internal/errors.js -function getVersion() { - return version3; +async function checkGas() { + await checkAndNotifyInsufficientGas(); + setInterval(async () => { + await checkAndNotifyInsufficientGas(); + }, globalConfig.NOTIFICATIONS.INTERVAL); } -// node_modules/ox/_esm/core/Errors.js -var BaseError3 = class _BaseError extends Error { - constructor(shortMessage, options = {}) { - const details = (() => { - if (options.cause instanceof _BaseError) { - if (options.cause.details) - return options.cause.details; - if (options.cause.shortMessage) - return options.cause.shortMessage; +// src/common/utils/createViemChain.ts +function createViemChain(chainDefinition) { + return defineChain({ + id: chainDefinition.id, + name: chainDefinition.name, + nativeCurrency: { + decimals: 18, + name: "eth", + symbol: "eth" + }, + rpcUrls: { + default: { http: chainDefinition.rpcUrls } + }, + blockExplorers: chainDefinition.blockExplorer ? { + default: { + name: chainDefinition.blockExplorer.name, + url: chainDefinition.blockExplorer.url } - if (options.cause?.message) - return options.cause.message; - return options.details; - })(); - const docsPath6 = (() => { - if (options.cause instanceof _BaseError) - return options.cause.docsPath || options.docsPath; - return options.docsPath; - })(); - const docsBaseUrl = "https://oxlib.sh"; - const docs = `${docsBaseUrl}${docsPath6 ?? ""}`; - const message = [ - shortMessage || "An error occurred.", - ...options.metaMessages ? ["", ...options.metaMessages] : [], - ...details || docsPath6 ? [ - "", - details ? `Details: ${details}` : void 0, - docsPath6 ? `See: ${docs}` : void 0 - ] : [] - ].filter((x2) => typeof x2 === "string").join("\n"); - super(message, options.cause ? { cause: options.cause } : void 0); - Object.defineProperty(this, "details", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "docs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "docsPath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "shortMessage", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "BaseError" - }); - Object.defineProperty(this, "version", { - enumerable: true, - configurable: true, - writable: true, - value: `ox@${getVersion()}` - }); - this.cause = options.cause; - this.details = details; - this.docs = docs; - this.docsPath = docsPath6; - this.shortMessage = shortMessage; - } - walk(fn2) { - return walk2(this, fn2); - } -}; -function walk2(err, fn2) { - if (fn2?.(err)) - return err; - if (err && typeof err === "object" && "cause" in err && err.cause) - return walk2(err.cause, fn2); - return fn2 ? null : err; + } : void 0, + testnet: chainDefinition.isTestnet + }); } -// node_modules/ox/_esm/core/Json.js -var bigIntSuffix = "#__bigint"; -function stringify2(value, replacer, space) { - return JSON.stringify(value, (key, value2) => { - if (typeof replacer === "function") - return replacer(key, value2); - if (typeof value2 === "bigint") - return value2.toString() + bigIntSuffix; - return value2; - }, space); +// src/common/utils/customHttpTransport.ts +function createCustomHttpTransport(url2) { + const logger = Logger.getInstance().getLogger("ViemTransport"); + return (config3) => { + const transport = http(url2, { + batch: true + })(config3); + return transport; + }; } -// node_modules/ox/_esm/core/internal/bytes.js -function assertSize2(bytes, size_) { - if (size3(bytes) > size_) - throw new SizeOverflowError2({ - givenSize: size3(bytes), - maxSize: size_ - }); -} -var charCodeMap2 = { - zero: 48, - nine: 57, - A: 65, - F: 70, - a: 97, - f: 102 -}; -function charCodeToBase162(char) { - if (char >= charCodeMap2.zero && char <= charCodeMap2.nine) - return char - charCodeMap2.zero; - if (char >= charCodeMap2.A && char <= charCodeMap2.F) - return char - (charCodeMap2.A - 10); - if (char >= charCodeMap2.a && char <= charCodeMap2.f) - return char - (charCodeMap2.a - 10); - return void 0; +// src/common/utils/decoders/decodeCLFReport.ts +var clfReportSubmissionAbi = parseAbiParameters([ + "bytes32[3] reportContext", + "bytes report", + "bytes32[] rs", + "bytes32[] ss", + "bytes32 rawVs" +]); +var clfReportAbi = parseAbiParameters([ + "bytes32[] requestIds", + "bytes[] results", + "bytes[] errors", + "bytes[] onchainMetadata", + "bytes[] offchainMetadata" +]); +function decodeCLFReport(tx) { + const inputData = tx.input.slice(10); + const decodedData = decodeAbiParameters(clfReportSubmissionAbi, `0x${inputData}`); + const reportBytes = decodedData[1]; + const decodedReport = decodeAbiParameters(clfReportAbi, reportBytes); + const report = { + reportContext: decodedData[0], + report: { + requestIds: decodedReport[0], + results: decodedReport[1], + errors: decodedReport[2], + onchainMetadata: decodedReport[3], + offchainMetadata: decodedReport[4] + }, + rs: decodedData[2], + ss: decodedData[3], + rawVs: decodedData[4], + reportBytes + }; + return report; } -function pad2(bytes, options = {}) { - const { dir, size: size5 = 32 } = options; - if (size5 === 0) - return bytes; - if (bytes.length > size5) - throw new SizeExceedsPaddingSizeError2({ - size: bytes.length, - targetSize: size5, - type: "Bytes" - }); - const paddedBytes = new Uint8Array(size5); - for (let i = 0; i < size5; i++) { - const padEnd = dir === "right"; - paddedBytes[padEnd ? i : size5 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; + +// src/common/utils/decoders/decodeMessageReportResult.ts +function decodeMessageReportResult(resultBytes) { + try { + const decodedClfResult = decodeAbiParameters( + [ + { + type: "tuple", + name: "reportConfig", + components: [ + { type: "uint8", name: "type" }, + { type: "uint8", name: "payloadVersion" }, + { type: "address", name: "requester" } + ] + }, + { type: "bytes", name: "payload" } + ], + resultBytes + ); + const decodedPayload = decodeAbiParameters( + [ + { + type: "tuple", + components: [ + { type: "bytes32", name: "messageId" }, + { type: "bytes32", name: "messageHashSum" }, + { type: "bytes", name: "messageSender" }, + { type: "uint24", name: "srcChainSelector" }, + { type: "uint24", name: "dstChainSelector" }, + { type: "uint256", name: "srcBlockNumber" }, + { + type: "tuple", + name: "dstChainData", + components: [ + { type: "address", name: "receiver" }, + { type: "uint256", name: "gasLimit" } + ] + }, + { type: "bytes[]", name: "allowedOperators" } + ] + } + ], + hexToBytes(decodedClfResult[1]) + ); + return { + reportConfig: decodedClfResult[0], + ...decodedPayload[0] + }; + } catch (error) { + console.error("Error decoding CLF message report response:", error); + throw new Error("Failed to decode CLF message report response"); } - return paddedBytes; } -// node_modules/ox/_esm/core/internal/hex.js -function assertSize3(hex, size_) { - if (size4(hex) > size_) - throw new SizeOverflowError3({ - givenSize: size4(hex), - maxSize: size_ - }); -} -function assertStartOffset2(value, start) { - if (typeof start === "number" && start > 0 && start > size4(value) - 1) - throw new SliceOffsetOutOfBoundsError3({ - offset: start, - position: "start", - size: size4(value) - }); -} -function assertEndOffset2(value, start, end) { - if (typeof start === "number" && typeof end === "number" && size4(value) !== end - start) { - throw new SliceOffsetOutOfBoundsError3({ - offset: end, - position: "end", - size: size4(value) - }); - } -} -function pad3(hex_, options = {}) { - const { dir, size: size5 = 32 } = options; - if (size5 === 0) - return hex_; - const hex = hex_.replace("0x", ""); - if (hex.length > size5 * 2) - throw new SizeExceedsPaddingSizeError3({ - size: Math.ceil(hex.length / 2), - targetSize: size5, - type: "Hex" - }); - return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`; +// node_modules/axios/lib/helpers/bind.js +function bind(fn2, thisArg) { + return function wrap() { + return fn2.apply(thisArg, arguments); + }; } -// node_modules/ox/_esm/core/Bytes.js -var encoder3 = /* @__PURE__ */ new TextEncoder(); -function from(value) { - if (value instanceof Uint8Array) - return value; - if (typeof value === "string") - return fromHex2(value); - return fromArray(value); -} -function fromArray(value) { - return value instanceof Uint8Array ? value : new Uint8Array(value); -} -function fromHex2(value, options = {}) { - const { size: size5 } = options; - let hex = value; - if (size5) { - assertSize3(value, size5); - hex = padRight(value, size5); - } - let hexString = hex.slice(2); - if (hexString.length % 2) - hexString = `0${hexString}`; - const length = hexString.length / 2; - const bytes = new Uint8Array(length); - for (let index2 = 0, j2 = 0; index2 < length; index2++) { - const nibbleLeft = charCodeToBase162(hexString.charCodeAt(j2++)); - const nibbleRight = charCodeToBase162(hexString.charCodeAt(j2++)); - if (nibbleLeft === void 0 || nibbleRight === void 0) { - throw new BaseError3(`Invalid byte sequence ("${hexString[j2 - 2]}${hexString[j2 - 1]}" in "${hexString}").`); - } - bytes[index2] = nibbleLeft * 16 + nibbleRight; - } - return bytes; +// node_modules/axios/lib/utils.js +var { toString } = Object.prototype; +var { getPrototypeOf } = Object; +var { iterator, toStringTag } = Symbol; +var kindOf = /* @__PURE__ */ ((cache) => (thing) => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(/* @__PURE__ */ Object.create(null)); +var kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type; +}; +var typeOfTest = (type) => (thing) => typeof thing === type; +var { isArray } = Array; +var isUndefined = typeOfTest("undefined"); +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); } -function fromString(value, options = {}) { - const { size: size5 } = options; - const bytes = encoder3.encode(value); - if (typeof size5 === "number") { - assertSize2(bytes, size5); - return padRight2(bytes, size5); +var isArrayBuffer = kindOfTest("ArrayBuffer"); +function isArrayBufferView(val) { + let result; + if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { + result = ArrayBuffer.isView(val); + } else { + result = val && val.buffer && isArrayBuffer(val.buffer); } - return bytes; -} -function padRight2(value, size5) { - return pad2(value, { dir: "right", size: size5 }); -} -function size3(value) { - return value.length; + return result; } -var SizeOverflowError2 = class extends BaseError3 { - constructor({ givenSize, maxSize }) { - super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Bytes.SizeOverflowError" - }); +var isString = typeOfTest("string"); +var isFunction = typeOfTest("function"); +var isNumber = typeOfTest("number"); +var isObject = (thing) => thing !== null && typeof thing === "object"; +var isBoolean = (thing) => thing === true || thing === false; +var isPlainObject = (val) => { + if (kindOf(val) !== "object") { + return false; } + const prototype3 = getPrototypeOf(val); + return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(toStringTag in val) && !(iterator in val); }; -var SizeExceedsPaddingSizeError2 = class extends BaseError3 { - constructor({ size: size5, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Bytes.SizeExceedsPaddingSizeError" - }); - } +var isDate = kindOfTest("Date"); +var isFile = kindOfTest("File"); +var isBlob = kindOfTest("Blob"); +var isFileList = kindOfTest("FileList"); +var isStream = (val) => isObject(val) && isFunction(val.pipe); +var isFormData = (thing) => { + let kind; + return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance + kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]")); }; - -// node_modules/ox/_esm/core/Hex.js -var encoder4 = /* @__PURE__ */ new TextEncoder(); -var hexes3 = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); -function assert(value, options = {}) { - const { strict = false } = options; - if (!value) - throw new InvalidHexTypeError(value); - if (typeof value !== "string") - throw new InvalidHexTypeError(value); - if (strict) { - if (!/^0x[0-9a-fA-F]*$/.test(value)) - throw new InvalidHexValueError(value); +var isURLSearchParams = kindOfTest("URLSearchParams"); +var [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest); +var trim4 = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); +function forEach(obj, fn2, { allOwnKeys = false } = {}) { + if (obj === null || typeof obj === "undefined") { + return; } - if (!value.startsWith("0x")) - throw new InvalidHexValueError(value); -} -function concat2(...values) { - return `0x${values.reduce((acc, x2) => acc + x2.replace("0x", ""), "")}`; -} -function fromBoolean(value, options = {}) { - const hex = `0x${Number(value)}`; - if (typeof options.size === "number") { - assertSize3(hex, options.size); - return padLeft(hex, options.size); + let i; + let l; + if (typeof obj !== "object") { + obj = [obj]; } - return hex; -} -function fromBytes(value, options = {}) { - let string = ""; - for (let i = 0; i < value.length; i++) - string += hexes3[value[i]]; - const hex = `0x${string}`; - if (typeof options.size === "number") { - assertSize3(hex, options.size); - return padRight(hex, options.size); + if (isArray(obj)) { + for (i = 0, l = obj.length; i < l; i++) { + fn2.call(null, obj[i], i, obj); + } + } else { + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + fn2.call(null, obj[key], key, obj); + } } - return hex; } -function fromNumber(value, options = {}) { - const { signed, size: size5 } = options; - const value_ = BigInt(value); - let maxValue; - if (size5) { - if (signed) - maxValue = (1n << BigInt(size5) * 8n - 1n) - 1n; - else - maxValue = 2n ** (BigInt(size5) * 8n) - 1n; - } else if (typeof value === "number") { - maxValue = BigInt(Number.MAX_SAFE_INTEGER); - } - const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0; - if (maxValue && value_ > maxValue || value_ < minValue) { - const suffix = typeof value === "bigint" ? "n" : ""; - throw new IntegerOutOfRangeError2({ - max: maxValue ? `${maxValue}${suffix}` : void 0, - min: `${minValue}${suffix}`, - signed, - size: size5, - value: `${value}${suffix}` - }); +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; + } } - const stringValue = (signed && value_ < 0 ? (1n << BigInt(size5 * 8)) + BigInt(value_) : value_).toString(16); - const hex = `0x${stringValue}`; - if (size5) - return padLeft(hex, size5); - return hex; -} -function fromString2(value, options = {}) { - return fromBytes(encoder4.encode(value), options); -} -function padLeft(value, size5) { - return pad3(value, { dir: "left", size: size5 }); -} -function padRight(value, size5) { - return pad3(value, { dir: "right", size: size5 }); -} -function slice2(value, start, end, options = {}) { - const { strict } = options; - assertStartOffset2(value, start); - const value_ = `0x${value.replace("0x", "").slice((start ?? 0) * 2, (end ?? value.length) * 2)}`; - if (strict) - assertEndOffset2(value_, start, end); - return value_; -} -function size4(value) { - return Math.ceil((value.length - 2) / 2); + return null; } -function validate(value, options = {}) { - const { strict = false } = options; - try { - assert(value, { strict }); - return true; - } catch { - return false; +var _global = (() => { + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; +})(); +var isContextDefined = (context) => !isUndefined(context) && context !== _global; +function merge() { + const { caseless } = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; + } + }; + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); } + return result; } -var IntegerOutOfRangeError2 = class extends BaseError3 { - constructor({ max, min, signed, size: size5, value }) { - super(`Number \`${value}\` is not in safe${size5 ? ` ${size5 * 8}-bit` : ""}${signed ? " signed" : " unsigned"} integer range ${max ? `(\`${min}\` to \`${max}\`)` : `(above \`${min}\`)`}`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.IntegerOutOfRangeError" - }); - } +var extend = (a, b2, thisArg, { allOwnKeys } = {}) => { + forEach(b2, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }, { allOwnKeys }); + return a; }; -var InvalidHexTypeError = class extends BaseError3 { - constructor(value) { - super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid hex type.`, { - metaMessages: ['Hex types must be represented as `"0x${string}"`.'] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.InvalidHexTypeError" - }); +var stripBOM = (content) => { + if (content.charCodeAt(0) === 65279) { + content = content.slice(1); } + return content; }; -var InvalidHexValueError = class extends BaseError3 { - constructor(value) { - super(`Value \`${value}\` is an invalid hex value.`, { - metaMessages: [ - 'Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).' - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.InvalidHexValueError" - }); +var inherits = (constructor, superConstructor, props, descriptors2) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors2); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, "super", { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +}; +var toFlatObject = (sourceObj, destObj, filter2, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + destObj = destObj || {}; + if (sourceObj == null) return destObj; + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = filter2 !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype); + return destObj; +}; +var endsWith = (str, searchString, position) => { + str = String(str); + if (position === void 0 || position > str.length) { + position = str.length; } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; }; -var SizeOverflowError3 = class extends BaseError3 { - constructor({ givenSize, maxSize }) { - super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.SizeOverflowError" - }); +var toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; } + return arr; }; -var SliceOffsetOutOfBoundsError3 = class extends BaseError3 { - constructor({ offset, position, size: size5 }) { - super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size5}\`).`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.SliceOffsetOutOfBoundsError" - }); +var isTypedArray = /* @__PURE__ */ ((TypedArray) => { + return (thing) => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); +var forEachEntry = (obj, fn2) => { + const generator = obj && obj[iterator]; + const _iterator = generator.call(obj); + let result; + while ((result = _iterator.next()) && !result.done) { + const pair = result.value; + fn2.call(obj, pair[0], pair[1]); } }; -var SizeExceedsPaddingSizeError3 = class extends BaseError3 { - constructor({ size: size5, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.SizeExceedsPaddingSizeError" - }); +var matchAll = (regExp, str) => { + let matches; + const arr = []; + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); } + return arr; }; - -// node_modules/ox/_esm/core/Withdrawal.js -function toRpc(withdrawal) { - return { - address: withdrawal.address, - amount: fromNumber(withdrawal.amount), - index: fromNumber(withdrawal.index), - validatorIndex: fromNumber(withdrawal.validatorIndex) - }; -} - -// node_modules/ox/_esm/core/BlockOverrides.js -function toRpc2(blockOverrides) { - return { - ...typeof blockOverrides.baseFeePerGas === "bigint" && { - baseFeePerGas: fromNumber(blockOverrides.baseFeePerGas) - }, - ...typeof blockOverrides.blobBaseFee === "bigint" && { - blobBaseFee: fromNumber(blockOverrides.blobBaseFee) - }, - ...typeof blockOverrides.feeRecipient === "string" && { - feeRecipient: blockOverrides.feeRecipient - }, - ...typeof blockOverrides.gasLimit === "bigint" && { - gasLimit: fromNumber(blockOverrides.gasLimit) - }, - ...typeof blockOverrides.number === "bigint" && { - number: fromNumber(blockOverrides.number) - }, - ...typeof blockOverrides.prevRandao === "bigint" && { - prevRandao: fromNumber(blockOverrides.prevRandao) - }, - ...typeof blockOverrides.time === "bigint" && { - time: fromNumber(blockOverrides.time) - }, - ...blockOverrides.withdrawals && { - withdrawals: blockOverrides.withdrawals.map(toRpc) +var isHTMLForm = kindOfTest("HTMLFormElement"); +var toCamelCase = (str) => { + return str.toLowerCase().replace( + /[-_\s]([a-z\d])(\w*)/g, + function replacer(m2, p1, p2) { + return p1.toUpperCase() + p2; + } + ); +}; +var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype); +var isRegExp = kindOfTest("RegExp"); +var reduceDescriptors = (obj, reducer) => { + const descriptors2 = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + forEach(descriptors2, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; + } + }); + Object.defineProperties(obj, reducedDescriptors); +}; +var freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) { + return false; + } + const value = obj[name]; + if (!isFunction(value)) return; + descriptor.enumerable = false; + if ("writable" in descriptor) { + descriptor.writable = false; + return; + } + if (!descriptor.set) { + descriptor.set = () => { + throw Error("Can not rewrite read-only method '" + name + "'"); + }; } + }); +}; +var toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + const define2 = (arr) => { + arr.forEach((value) => { + obj[value] = true; + }); }; + isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); + return obj; +}; +var noop = () => { +}; +var toFiniteNumber = (value, defaultValue) => { + return value != null && Number.isFinite(value = +value) ? value : defaultValue; +}; +function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]); } - -// node_modules/viem/_esm/actions/public/simulateBlocks.js -init_parseAccount(); -init_abi(); -init_contract(); -init_node(); -init_decodeFunctionResult(); -init_encodeFunctionData(); -init_toHex(); -init_getNodeError(); -init_transactionRequest(); -init_stateOverride2(); -init_assertRequest(); -async function simulateBlocks(client, parameters) { - const { blockNumber, blockTag = "latest", blocks, returnFullTransactions, traceTransfers, validation } = parameters; - try { - const blockStateCalls = []; - for (const block2 of blocks) { - const blockOverrides = block2.blockOverrides ? toRpc2(block2.blockOverrides) : void 0; - const calls = block2.calls.map((call_) => { - const call2 = call_; - const account = call2.account ? parseAccount(call2.account) : void 0; - const request = { - ...call2, - data: call2.abi ? encodeFunctionData(call2) : call2.data, - from: call2.from ?? account?.address - }; - assertRequest(request); - return formatTransactionRequest(request); - }); - const stateOverrides = block2.stateOverrides ? serializeStateOverride(block2.stateOverrides) : void 0; - blockStateCalls.push({ - blockOverrides, - calls, - stateOverrides - }); +var toJSONObject = (obj) => { + const stack = new Array(10); + const visit = (source, i) => { + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + if (!("toJSON" in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + stack[i] = void 0; + return target; + } } - const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; - const block = blockNumberHex || blockTag; - const result = await client.request({ - method: "eth_simulateV1", - params: [ - { blockStateCalls, returnFullTransactions, traceTransfers, validation }, - block - ] - }); - return result.map((block2, i) => ({ - ...formatBlock(block2), - calls: block2.calls.map((call2, j2) => { - const { abi: abi4, args, functionName, to: to2 } = blocks[i].calls[j2]; - const data = call2.error?.data ?? call2.returnData; - const gasUsed = BigInt(call2.gasUsed); - const logs = call2.logs?.map((log) => formatLog(log)); - const status = call2.status === "0x1" ? "success" : "failure"; - const result2 = abi4 && status === "success" && data !== "0x" ? decodeFunctionResult({ - abi: abi4, - data, - functionName - }) : null; - const error = (() => { - if (status === "success") - return void 0; - let error2 = void 0; - if (call2.error?.data === "0x") - error2 = new AbiDecodingZeroDataError(); - else if (call2.error) - error2 = new RawContractError(call2.error); - if (!error2) - return void 0; - return getContractError(error2, { - abi: abi4 ?? [], - address: to2, - args, - functionName: functionName ?? "" - }); - })(); - return { - data, - gasUsed, - logs, - status, - ...status === "success" ? { - result: result2 - } : { - error - } - }; - }) - })); - } catch (e) { - const cause = e; - const error = getNodeError(cause, {}); - if (error instanceof UnknownNodeError) - throw cause; - throw error; + return source; + }; + return visit(obj, 0); +}; +var isAsyncFn = kindOfTest("AsyncFunction"); +var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); +var _setImmediate = ((setImmediateSupported, postMessageSupported) => { + if (setImmediateSupported) { + return setImmediate; } -} - -// node_modules/ox/_esm/core/AbiItem.js -init_exports(); + return postMessageSupported ? ((token, callbacks) => { + _global.addEventListener("message", ({ source, data }) => { + if (source === _global && data === token) { + callbacks.length && callbacks.shift()(); + } + }, false); + return (cb) => { + callbacks.push(cb); + _global.postMessage(token, "*"); + }; + })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); +})( + typeof setImmediate === "function", + isFunction(_global.postMessage) +); +var asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate; +var isIterable = (thing) => thing != null && isFunction(thing[iterator]); +var utils_default = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isReadableStream, + isRequest, + isResponse, + isHeaders, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim: trim4, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, + // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable, + setImmediate: _setImmediate, + asap, + isIterable +}; -// node_modules/ox/node_modules/@noble/hashes/esm/_assert.js -function anumber2(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error("positive integer expected, got " + n); -} -function isBytes3(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; -} -function abytes3(b2, ...lengths) { - if (!isBytes3(b2)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b2.length)) - throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b2.length); -} -function aexists2(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); -} -function aoutput2(out, instance) { - abytes3(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error("digestInto() expects output buffer of length at least " + min); +// node_modules/axios/lib/core/AxiosError.js +function AxiosError(message, code, config3, request, response) { + Error.call(this); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack; } -} - -// node_modules/ox/node_modules/@noble/hashes/esm/utils.js -function u322(arr) { - return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -} -var isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); -function byteSwap2(word) { - return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; -} -function byteSwap322(arr) { - for (let i = 0; i < arr.length; i++) { - arr[i] = byteSwap2(arr[i]); + this.message = message; + this.name = "AxiosError"; + code && (this.code = code); + config3 && (this.config = config3); + request && (this.request = request); + if (response) { + this.response = response; + this.status = response.status ? response.status : null; } } -function utf8ToBytes3(str) { - if (typeof str !== "string") - throw new Error("utf8ToBytes expected string, got " + typeof str); - return new Uint8Array(new TextEncoder().encode(str)); -} -function toBytes3(data) { - if (typeof data === "string") - data = utf8ToBytes3(data); - abytes3(data); - return data; -} -var Hash2 = class { - // Safe version that clones internal state - clone() { - return this._cloneInto(); +utils_default.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils_default.toJSONObject(this.config), + code: this.code, + status: this.status + }; } +}); +var prototype = AxiosError.prototype; +var descriptors = {}; +[ + "ERR_BAD_OPTION_VALUE", + "ERR_BAD_OPTION", + "ECONNABORTED", + "ETIMEDOUT", + "ERR_NETWORK", + "ERR_FR_TOO_MANY_REDIRECTS", + "ERR_DEPRECATED", + "ERR_BAD_RESPONSE", + "ERR_BAD_REQUEST", + "ERR_CANCELED", + "ERR_NOT_SUPPORT", + "ERR_INVALID_URL" + // eslint-disable-next-line func-names +].forEach((code) => { + descriptors[code] = { value: code }; +}); +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(prototype, "isAxiosError", { value: true }); +AxiosError.from = (error, code, config3, request, response, customProps) => { + const axiosError = Object.create(prototype); + utils_default.toFlatObject(error, axiosError, function filter2(obj) { + return obj !== Error.prototype; + }, (prop) => { + return prop !== "isAxiosError"; + }); + AxiosError.call(axiosError, error.message, code, config3, request, response); + axiosError.cause = error; + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; }; -function wrapConstructor2(hashCons) { - const hashC = (msg) => hashCons().update(toBytes3(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; -} -function wrapXOFConstructorWithOpts2(hashCons) { - const hashC = (msg, opts) => hashCons(opts).update(toBytes3(msg)).digest(); - const tmp = hashCons({}); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = (opts) => hashCons(opts); - return hashC; -} +var AxiosError_default = AxiosError; -// node_modules/ox/node_modules/@noble/hashes/esm/_u64.js -var U32_MASK642 = /* @__PURE__ */ BigInt(2 ** 32 - 1); -var _32n2 = /* @__PURE__ */ BigInt(32); -function fromBig2(n, le2 = false) { - if (le2) - return { h: Number(n & U32_MASK642), l: Number(n >> _32n2 & U32_MASK642) }; - return { h: Number(n >> _32n2 & U32_MASK642) | 0, l: Number(n & U32_MASK642) | 0 }; +// node_modules/axios/lib/platform/node/classes/FormData.js +var import_form_data = __toESM(require_form_data(), 1); +var FormData_default = import_form_data.default; + +// node_modules/axios/lib/helpers/toFormData.js +function isVisitable(thing) { + return utils_default.isPlainObject(thing) || utils_default.isArray(thing); } -function split2(lst, le2 = false) { - let Ah = new Uint32Array(lst.length); - let Al2 = new Uint32Array(lst.length); - for (let i = 0; i < lst.length; i++) { - const { h, l } = fromBig2(lst[i], le2); - [Ah[i], Al2[i]] = [h, l]; - } - return [Ah, Al2]; +function removeBrackets(key) { + return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key; } -var rotlSH2 = (h, l, s) => h << s | l >>> 32 - s; -var rotlSL2 = (h, l, s) => l << s | h >>> 32 - s; -var rotlBH2 = (h, l, s) => l << s - 32 | h >>> 64 - s; -var rotlBL2 = (h, l, s) => h << s - 32 | l >>> 64 - s; - -// node_modules/ox/node_modules/@noble/hashes/esm/sha3.js -var SHA3_PI2 = []; -var SHA3_ROTL2 = []; -var _SHA3_IOTA2 = []; -var _0n7 = /* @__PURE__ */ BigInt(0); -var _1n7 = /* @__PURE__ */ BigInt(1); -var _2n6 = /* @__PURE__ */ BigInt(2); -var _7n2 = /* @__PURE__ */ BigInt(7); -var _256n2 = /* @__PURE__ */ BigInt(256); -var _0x71n2 = /* @__PURE__ */ BigInt(113); -for (let round = 0, R2 = _1n7, x2 = 1, y2 = 0; round < 24; round++) { - [x2, y2] = [y2, (2 * x2 + 3 * y2) % 5]; - SHA3_PI2.push(2 * (5 * y2 + x2)); - SHA3_ROTL2.push((round + 1) * (round + 2) / 2 % 64); - let t = _0n7; - for (let j2 = 0; j2 < 7; j2++) { - R2 = (R2 << _1n7 ^ (R2 >> _7n2) * _0x71n2) % _256n2; - if (R2 & _2n6) - t ^= _1n7 << (_1n7 << /* @__PURE__ */ BigInt(j2)) - _1n7; - } - _SHA3_IOTA2.push(t); +function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + token = removeBrackets(token); + return !dots && i ? "[" + token + "]" : token; + }).join(dots ? "." : ""); } -var [SHA3_IOTA_H2, SHA3_IOTA_L2] = /* @__PURE__ */ split2(_SHA3_IOTA2, true); -var rotlH2 = (h, l, s) => s > 32 ? rotlBH2(h, l, s) : rotlSH2(h, l, s); -var rotlL2 = (h, l, s) => s > 32 ? rotlBL2(h, l, s) : rotlSL2(h, l, s); -function keccakP2(s, rounds = 24) { - const B2 = new Uint32Array(5 * 2); - for (let round = 24 - rounds; round < 24; round++) { - for (let x2 = 0; x2 < 10; x2++) - B2[x2] = s[x2] ^ s[x2 + 10] ^ s[x2 + 20] ^ s[x2 + 30] ^ s[x2 + 40]; - for (let x2 = 0; x2 < 10; x2 += 2) { - const idx1 = (x2 + 8) % 10; - const idx0 = (x2 + 2) % 10; - const B0 = B2[idx0]; - const B1 = B2[idx0 + 1]; - const Th = rotlH2(B0, B1, 1) ^ B2[idx1]; - const Tl2 = rotlL2(B0, B1, 1) ^ B2[idx1 + 1]; - for (let y2 = 0; y2 < 50; y2 += 10) { - s[x2 + y2] ^= Th; - s[x2 + y2 + 1] ^= Tl2; - } - } - let curH = s[2]; - let curL = s[3]; - for (let t = 0; t < 24; t++) { - const shift = SHA3_ROTL2[t]; - const Th = rotlH2(curH, curL, shift); - const Tl2 = rotlL2(curH, curL, shift); - const PI = SHA3_PI2[t]; - curH = s[PI]; - curL = s[PI + 1]; - s[PI] = Th; - s[PI + 1] = Tl2; - } - for (let y2 = 0; y2 < 50; y2 += 10) { - for (let x2 = 0; x2 < 10; x2++) - B2[x2] = s[y2 + x2]; - for (let x2 = 0; x2 < 10; x2++) - s[y2 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10]; - } - s[0] ^= SHA3_IOTA_H2[round]; - s[1] ^= SHA3_IOTA_L2[round]; - } - B2.fill(0); +function isFlatArray(arr) { + return utils_default.isArray(arr) && !arr.some(isVisitable); } -var Keccak2 = class _Keccak extends Hash2 { - // NOTE: we accept arguments in bytes instead of bits here. - constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { - super(); - this.blockLen = blockLen; - this.suffix = suffix; - this.outputLen = outputLen; - this.enableXOF = enableXOF; - this.rounds = rounds; - this.pos = 0; - this.posOut = 0; - this.finished = false; - this.destroyed = false; - anumber2(outputLen); - if (0 >= this.blockLen || this.blockLen >= 200) - throw new Error("Sha3 supports only keccak-f1600 function"); - this.state = new Uint8Array(200); - this.state32 = u322(this.state); - } - keccak() { - if (!isLE2) - byteSwap322(this.state32); - keccakP2(this.state32, this.rounds); - if (!isLE2) - byteSwap322(this.state32); - this.posOut = 0; - this.pos = 0; +var predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); +function toFormData(obj, formData, options) { + if (!utils_default.isObject(obj)) { + throw new TypeError("target must be an object"); } - update(data) { - aexists2(this); - const { blockLen, state } = this; - data = toBytes3(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - for (let i = 0; i < take; i++) - state[this.pos++] ^= data[pos++]; - if (this.pos === blockLen) - this.keccak(); - } - return this; + formData = formData || new (FormData_default || FormData)(); + options = utils_default.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + return !utils_default.isUndefined(source[option]); + }); + const metaTokens = options.metaTokens; + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; + const useBlob = _Blob && utils_default.isSpecCompliantForm(formData); + if (!utils_default.isFunction(visitor)) { + throw new TypeError("visitor must be a function"); } - finish() { - if (this.finished) - return; - this.finished = true; - const { state, suffix, pos, blockLen } = this; - state[pos] ^= suffix; - if ((suffix & 128) !== 0 && pos === blockLen - 1) - this.keccak(); - state[blockLen - 1] ^= 128; - this.keccak(); + function convertValue(value) { + if (value === null) return ""; + if (utils_default.isDate(value)) { + return value.toISOString(); + } + if (!useBlob && utils_default.isBlob(value)) { + throw new AxiosError_default("Blob is not supported. Use a Buffer instead."); + } + if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) { + return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); + } + return value; } - writeInto(out) { - aexists2(this, false); - abytes3(out); - this.finish(); - const bufferOut = this.state; - const { blockLen } = this; - for (let pos = 0, len = out.length; pos < len; ) { - if (this.posOut >= blockLen) - this.keccak(); - const take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; + function defaultVisitor(value, key, path) { + let arr = value; + if (value && !path && typeof value === "object") { + if (utils_default.endsWith(key, "{}")) { + key = metaTokens ? key : key.slice(0, -2); + value = JSON.stringify(value); + } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) { + key = removeBrackets(key); + arr.forEach(function each(el2, index2) { + !(utils_default.isUndefined(el2) || el2 === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index2, dots) : indexes === null ? key : key + "[]", + convertValue(el2) + ); + }); + return false; + } } - return out; + if (isVisitable(value)) { + return true; + } + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; } - xofInto(out) { - if (!this.enableXOF) - throw new Error("XOF is not possible for this instance"); - return this.writeInto(out); + const stack = []; + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + function build(value, path) { + if (utils_default.isUndefined(value)) return; + if (stack.indexOf(value) !== -1) { + throw Error("Circular reference detected in " + path.join(".")); + } + stack.push(value); + utils_default.forEach(value, function each(el2, key) { + const result = !(utils_default.isUndefined(el2) || el2 === null) && visitor.call( + formData, + el2, + utils_default.isString(key) ? key.trim() : key, + path, + exposedHelpers + ); + if (result === true) { + build(el2, path ? path.concat(key) : [key]); + } + }); + stack.pop(); } - xof(bytes) { - anumber2(bytes); - return this.xofInto(new Uint8Array(bytes)); + if (!utils_default.isObject(obj)) { + throw new TypeError("data must be an object"); } - digestInto(out) { - aoutput2(out, this); - if (this.finished) - throw new Error("digest() was already called"); - this.writeInto(out); - this.destroy(); - return out; + build(obj); + return formData; +} +var toFormData_default = toFormData; + +// node_modules/axios/lib/helpers/AxiosURLSearchParams.js +function encode4(str) { + const charMap = { + "!": "%21", + "'": "%27", + "(": "%28", + ")": "%29", + "~": "%7E", + "%20": "+", + "%00": "\0" + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); +} +function AxiosURLSearchParams(params, options) { + this._pairs = []; + params && toFormData_default(params, this, options); +} +var prototype2 = AxiosURLSearchParams.prototype; +prototype2.append = function append(name, value) { + this._pairs.push([name, value]); +}; +prototype2.toString = function toString2(encoder5) { + const _encode = encoder5 ? function(value) { + return encoder5.call(this, value, encode4); + } : encode4; + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + "=" + _encode(pair[1]); + }, "").join("&"); +}; +var AxiosURLSearchParams_default = AxiosURLSearchParams; + +// node_modules/axios/lib/helpers/buildURL.js +function encode5(val) { + return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); +} +function buildURL(url2, params, options) { + if (!params) { + return url2; } - digest() { - return this.digestInto(new Uint8Array(this.outputLen)); + const _encode = options && options.encode || encode5; + if (utils_default.isFunction(options)) { + options = { + serialize: options + }; } - destroy() { - this.destroyed = true; - this.state.fill(0); + const serializeFn = options && options.serialize; + let serializedParams; + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, options).toString(_encode); } - _cloneInto(to2) { - const { blockLen, suffix, outputLen, rounds, enableXOF } = this; - to2 || (to2 = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); - to2.state32.set(this.state32); - to2.pos = this.pos; - to2.posOut = this.posOut; - to2.finished = this.finished; - to2.rounds = rounds; - to2.suffix = suffix; - to2.outputLen = outputLen; - to2.enableXOF = enableXOF; - to2.destroyed = this.destroyed; - return to2; + if (serializedParams) { + const hashmarkIndex = url2.indexOf("#"); + if (hashmarkIndex !== -1) { + url2 = url2.slice(0, hashmarkIndex); + } + url2 += (url2.indexOf("?") === -1 ? "?" : "&") + serializedParams; } -}; -var gen2 = (suffix, blockLen, outputLen) => wrapConstructor2(() => new Keccak2(blockLen, suffix, outputLen)); -var sha3_2242 = /* @__PURE__ */ gen2(6, 144, 224 / 8); -var sha3_2562 = /* @__PURE__ */ gen2(6, 136, 256 / 8); -var sha3_3842 = /* @__PURE__ */ gen2(6, 104, 384 / 8); -var sha3_5122 = /* @__PURE__ */ gen2(6, 72, 512 / 8); -var keccak_2242 = /* @__PURE__ */ gen2(1, 144, 224 / 8); -var keccak_2562 = /* @__PURE__ */ gen2(1, 136, 256 / 8); -var keccak_3842 = /* @__PURE__ */ gen2(1, 104, 384 / 8); -var keccak_5122 = /* @__PURE__ */ gen2(1, 72, 512 / 8); -var genShake2 = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts2((opts = {}) => new Keccak2(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true)); -var shake1282 = /* @__PURE__ */ genShake2(31, 168, 128 / 8); -var shake2562 = /* @__PURE__ */ genShake2(31, 136, 256 / 8); - -// node_modules/ox/_esm/core/Hash.js -function keccak2562(value, options = {}) { - const { as: as2 = typeof value === "string" ? "Hex" : "Bytes" } = options; - const bytes = keccak_2562(from(value)); - if (as2 === "Bytes") - return bytes; - return fromBytes(bytes); + return url2; } -// node_modules/ox/_esm/core/internal/lru.js -var LruMap2 = class extends Map { - constructor(size5) { - super(); - Object.defineProperty(this, "maxSize", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 +// node_modules/axios/lib/core/InterceptorManager.js +var InterceptorManager = class { + constructor() { + this.handlers = []; + } + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null }); - this.maxSize = size5; + return this.handlers.length - 1; } - get(key) { - const value = super.get(key); - if (super.has(key) && value !== void 0) { - this.delete(key); - super.set(key, value); + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id2) { + if (this.handlers[id2]) { + this.handlers[id2] = null; } - return value; } - set(key, value) { - super.set(key, value); - if (this.maxSize && this.size > this.maxSize) { - const firstKey = this.keys().next().value; - if (firstKey) - this.delete(firstKey); + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; } - return this; + } + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn2) { + utils_default.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn2(h); + } + }); } }; +var InterceptorManager_default = InterceptorManager; -// node_modules/ox/_esm/core/Caches.js -var caches = { - checksum: /* @__PURE__ */ new LruMap2(8192) +// node_modules/axios/lib/defaults/transitional.js +var transitional_default = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false }; -var checksum = caches.checksum; -// node_modules/ox/_esm/core/Address.js -var addressRegex2 = /^0x[a-fA-F0-9]{40}$/; -function assert2(value, options = {}) { - const { strict = true } = options; - if (!addressRegex2.test(value)) - throw new InvalidAddressError2({ - address: value, - cause: new InvalidInputError() - }); - if (strict) { - if (value.toLowerCase() === value) - return; - if (checksum2(value) !== value) - throw new InvalidAddressError2({ - address: value, - cause: new InvalidChecksumError() - }); - } -} -function checksum2(address) { - if (checksum.has(address)) - return checksum.get(address); - assert2(address, { strict: false }); - const hexAddress = address.substring(2).toLowerCase(); - const hash2 = keccak2562(fromString(hexAddress), { as: "Bytes" }); - const characters = hexAddress.split(""); - for (let i = 0; i < 40; i += 2) { - if (hash2[i >> 1] >> 4 >= 8 && characters[i]) { - characters[i] = characters[i].toUpperCase(); - } - if ((hash2[i >> 1] & 15) >= 8 && characters[i + 1]) { - characters[i + 1] = characters[i + 1].toUpperCase(); - } - } - const result = `0x${characters.join("")}`; - checksum.set(address, result); - return result; -} -function validate2(address, options = {}) { - const { strict = true } = options ?? {}; - try { - assert2(address, { strict }); - return true; - } catch { - return false; - } -} -var InvalidAddressError2 = class extends BaseError3 { - constructor({ address, cause }) { - super(`Address "${address}" is invalid.`, { - cause - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Address.InvalidAddressError" - }); - } +// node_modules/axios/lib/platform/node/index.js +import crypto3 from "crypto"; + +// node_modules/axios/lib/platform/node/classes/URLSearchParams.js +import url from "url"; +var URLSearchParams_default = url.URLSearchParams; + +// node_modules/axios/lib/platform/node/index.js +var ALPHA = "abcdefghijklmnopqrstuvwxyz"; +var DIGIT = "0123456789"; +var ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT }; -var InvalidInputError = class extends BaseError3 { - constructor() { - super("Address is not a 20 byte (40 hexadecimal character) value."); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Address.InvalidInputError" - }); +var generateString = (size5 = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ""; + const { length } = alphabet; + const randomValues = new Uint32Array(size5); + crypto3.randomFillSync(randomValues); + for (let i = 0; i < size5; i++) { + str += alphabet[randomValues[i] % length]; } + return str; }; -var InvalidChecksumError = class extends BaseError3 { - constructor() { - super("Address does not match its checksum counterpart."); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Address.InvalidChecksumError" - }); - } +var node_default = { + isNode: true, + classes: { + URLSearchParams: URLSearchParams_default, + FormData: FormData_default, + Blob: typeof Blob !== "undefined" && Blob || null + }, + ALPHABET, + generateString, + protocols: ["http", "https", "file", "data"] }; -// node_modules/ox/_esm/core/internal/abiItem.js -function normalizeSignature2(signature) { - let active = true; - let current = ""; - let level = 0; - let result = ""; - let valid = false; - for (let i = 0; i < signature.length; i++) { - const char = signature[i]; - if (["(", ")", ","].includes(char)) - active = true; - if (char === "(") - level++; - if (char === ")") - level--; - if (!active) - continue; - if (level === 0) { - if (char === " " && ["event", "function", "error", ""].includes(result)) - result = ""; - else { - result += char; - if (char === ")") { - valid = true; - break; - } - } - continue; - } - if (char === " ") { - if (signature[i - 1] !== "," && current !== "," && current !== ",(") { - current = ""; - active = false; +// node_modules/axios/lib/platform/common/utils.js +var utils_exports2 = {}; +__export(utils_exports2, { + hasBrowserEnv: () => hasBrowserEnv, + hasStandardBrowserEnv: () => hasStandardBrowserEnv, + hasStandardBrowserWebWorkerEnv: () => hasStandardBrowserWebWorkerEnv, + navigator: () => _navigator, + origin: () => origin +}); +var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; +var _navigator = typeof navigator === "object" && navigator || void 0; +var hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0); +var hasStandardBrowserWebWorkerEnv = (() => { + return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef + self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; +})(); +var origin = hasBrowserEnv && window.location.href || "http://localhost"; + +// node_modules/axios/lib/platform/index.js +var platform_default = { + ...utils_exports2, + ...node_default +}; + +// node_modules/axios/lib/helpers/toURLEncodedForm.js +function toURLEncodedForm(data, options) { + return toFormData_default(data, new platform_default.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (platform_default.isNode && utils_default.isBuffer(value)) { + this.append(key, value.toString("base64")); + return false; } - continue; + return helpers.defaultVisitor.apply(this, arguments); } - result += char; - current += char; - } - if (!valid) - throw new BaseError3("Unable to normalize signature."); - return result; + }, options)); } -function isArgOfType2(arg, abiParameter) { - const argType = typeof arg; - const abiParameterType = abiParameter.type; - switch (abiParameterType) { - case "address": - return validate2(arg, { strict: false }); - case "bool": - return argType === "boolean"; - case "function": - return argType === "string"; - case "string": - return argType === "string"; - default: { - if (abiParameterType === "tuple" && "components" in abiParameter) - return Object.values(abiParameter.components).every((component, index2) => { - return isArgOfType2(Object.values(arg)[index2], component); - }); - if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) - return argType === "number" || argType === "bigint"; - if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) - return argType === "string" || arg instanceof Uint8Array; - if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { - return Array.isArray(arg) && arg.every((x2) => isArgOfType2(x2, { - ...abiParameter, - // Pop off `[]` or `[M]` from end of type - type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") - })); + +// node_modules/axios/lib/helpers/formDataToJSON.js +function parsePropPath(name) { + return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match) => { + return match[0] === "[]" ? "" : match[1] || match[0]; + }); +} +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} +function formDataToJSON(formData) { + function buildPath(path, value, target, index2) { + let name = path[index2++]; + if (name === "__proto__") return true; + const isNumericKey = Number.isFinite(+name); + const isLast = index2 >= path.length; + name = !name && utils_default.isArray(target) ? target.length : name; + if (isLast) { + if (utils_default.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; } - return false; + return !isNumericKey; + } + if (!target[name] || !utils_default.isObject(target[name])) { + target[name] = []; + } + const result = buildPath(path, value, target[name], index2); + if (result && utils_default.isArray(target[name])) { + target[name] = arrayToObject(target[name]); } + return !isNumericKey; } -} -function getAmbiguousTypes2(sourceParameters, targetParameters, args) { - for (const parameterIndex in sourceParameters) { - const sourceParameter = sourceParameters[parameterIndex]; - const targetParameter = targetParameters[parameterIndex]; - if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) - return getAmbiguousTypes2(sourceParameter.components, targetParameter.components, args[parameterIndex]); - const types = [sourceParameter.type, targetParameter.type]; - const ambiguous = (() => { - if (types.includes("address") && types.includes("bytes20")) - return true; - if (types.includes("address") && types.includes("string")) - return validate2(args[parameterIndex], { - strict: false - }); - if (types.includes("address") && types.includes("bytes")) - return validate2(args[parameterIndex], { - strict: false - }); - return false; - })(); - if (ambiguous) - return types; + if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) { + const obj = {}; + utils_default.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + return obj; } - return; + return null; } +var formDataToJSON_default = formDataToJSON; -// node_modules/ox/_esm/core/AbiItem.js -function from2(abiItem, options = {}) { - const { prepare = true } = options; - const item = (() => { - if (Array.isArray(abiItem)) - return parseAbiItem(abiItem); - if (typeof abiItem === "string") - return parseAbiItem(abiItem); - return abiItem; - })(); - return { - ...item, - ...prepare ? { hash: getSignatureHash(item) } : {} - }; +// node_modules/axios/lib/defaults/index.js +function stringifySafely(rawValue, parser, encoder5) { + if (utils_default.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils_default.trim(rawValue); + } catch (e) { + if (e.name !== "SyntaxError") { + throw e; + } + } + } + return (encoder5 || JSON.stringify)(rawValue); } -function fromAbi(abi4, name, options) { - const { args = [], prepare = true } = options ?? {}; - const isSelector = validate(name, { strict: false }); - const abiItems = abi4.filter((abiItem2) => { - if (isSelector) { - if (abiItem2.type === "function" || abiItem2.type === "error") - return getSelector(abiItem2) === slice2(name, 0, 4); - if (abiItem2.type === "event") - return getSignatureHash(abiItem2) === name; - return false; +var defaults = { + transitional: transitional_default, + adapter: ["xhr", "http", "fetch"], + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ""; + const hasJSONContentType = contentType.indexOf("application/json") > -1; + const isObjectPayload = utils_default.isObject(data); + if (isObjectPayload && utils_default.isHTMLForm(data)) { + data = new FormData(data); } - return "name" in abiItem2 && abiItem2.name === name; - }); - if (abiItems.length === 0) - throw new NotFoundError2({ name }); - if (abiItems.length === 1) - return { - ...abiItems[0], - ...prepare ? { hash: getSignatureHash(abiItems[0]) } : {} - }; - let matchedAbiItem = void 0; - for (const abiItem2 of abiItems) { - if (!("inputs" in abiItem2)) - continue; - if (!args || args.length === 0) { - if (!abiItem2.inputs || abiItem2.inputs.length === 0) - return { - ...abiItem2, - ...prepare ? { hash: getSignatureHash(abiItem2) } : {} - }; - continue; + const isFormData2 = utils_default.isFormData(data); + if (isFormData2) { + return hasJSONContentType ? JSON.stringify(formDataToJSON_default(data)) : data; } - if (!abiItem2.inputs) - continue; - if (abiItem2.inputs.length === 0) - continue; - if (abiItem2.inputs.length !== args.length) - continue; - const matched = args.every((arg, index2) => { - const abiParameter = "inputs" in abiItem2 && abiItem2.inputs[index2]; - if (!abiParameter) - return false; - return isArgOfType2(arg, abiParameter); - }); - if (matched) { - if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { - const ambiguousTypes = getAmbiguousTypes2(abiItem2.inputs, matchedAbiItem.inputs, args); - if (ambiguousTypes) - throw new AmbiguityError({ - abiItem: abiItem2, - type: ambiguousTypes[0] - }, { - abiItem: matchedAbiItem, - type: ambiguousTypes[1] - }); + if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data) || utils_default.isReadableStream(data)) { + return data; + } + if (utils_default.isArrayBufferView(data)) { + return data.buffer; + } + if (utils_default.isURLSearchParams(data)) { + headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); + return data.toString(); + } + let isFileList2; + if (isObjectPayload) { + if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); } - matchedAbiItem = abiItem2; + if ((isFileList2 = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { + const _FormData = this.env && this.env.FormData; + return toFormData_default( + isFileList2 ? { "files[]": data } : data, + _FormData && new _FormData(), + this.formSerializer + ); + } + } + if (isObjectPayload || hasJSONContentType) { + headers.setContentType("application/json", false); + return stringifySafely(data); + } + return data; + }], + transformResponse: [function transformResponse(data) { + const transitional2 = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing; + const JSONRequested = this.responseType === "json"; + if (utils_default.isResponse(data) || utils_default.isReadableStream(data)) { + return data; + } + if (data && utils_default.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { + const silentJSONParsing = transitional2 && transitional2.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === "SyntaxError") { + throw AxiosError_default.from(e, AxiosError_default.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + return data; + }], + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + xsrfCookieName: "XSRF-TOKEN", + xsrfHeaderName: "X-XSRF-TOKEN", + maxContentLength: -1, + maxBodyLength: -1, + env: { + FormData: platform_default.classes.FormData, + Blob: platform_default.classes.Blob + }, + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + headers: { + common: { + "Accept": "application/json, text/plain, */*", + "Content-Type": void 0 } } - const abiItem = (() => { - if (matchedAbiItem) - return matchedAbiItem; - const [abiItem2, ...overloads] = abiItems; - return { ...abiItem2, overloads }; - })(); - if (!abiItem) - throw new NotFoundError2({ name }); - return { - ...abiItem, - ...prepare ? { hash: getSignatureHash(abiItem) } : {} - }; -} -function getSelector(abiItem) { - return slice2(getSignatureHash(abiItem), 0, 4); +}; +utils_default.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => { + defaults.headers[method] = {}; +}); +var defaults_default = defaults; + +// node_modules/axios/lib/helpers/parseHeaders.js +var ignoreDuplicateOf = utils_default.toObjectSet([ + "age", + "authorization", + "content-length", + "content-type", + "etag", + "expires", + "from", + "host", + "if-modified-since", + "if-unmodified-since", + "last-modified", + "location", + "max-forwards", + "proxy-authorization", + "referer", + "retry-after", + "user-agent" +]); +var parseHeaders_default = (rawHeaders) => { + const parsed = {}; + let key; + let val; + let i; + rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { + i = line.indexOf(":"); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + if (!key || parsed[key] && ignoreDuplicateOf[key]) { + return; + } + if (key === "set-cookie") { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; + } + }); + return parsed; +}; + +// node_modules/axios/lib/core/AxiosHeaders.js +var $internals = Symbol("internals"); +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); } -function getSignature(abiItem) { - const signature = (() => { - if (typeof abiItem === "string") - return abiItem; - return formatAbiItem(abiItem); - })(); - return normalizeSignature2(signature); +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + return utils_default.isArray(value) ? value.map(normalizeValue) : String(value); } -function getSignatureHash(abiItem) { - if (typeof abiItem !== "string" && "hash" in abiItem && abiItem.hash) - return abiItem.hash; - return keccak2562(fromString2(getSignature(abiItem))); +function parseTokens(str) { + const tokens = /* @__PURE__ */ Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + while (match = tokensRE.exec(str)) { + tokens[match[1]] = match[2]; + } + return tokens; } -var AmbiguityError = class extends BaseError3 { - constructor(x2, y2) { - super("Found ambiguous types in overloaded ABI Items.", { - metaMessages: [ - // TODO: abitype to add support for signature-formatted ABI items. - `\`${x2.type}\` in \`${normalizeSignature2(formatAbiItem(x2.abiItem))}\`, and`, - `\`${y2.type}\` in \`${normalizeSignature2(formatAbiItem(y2.abiItem))}\``, - "", - "These types encode differently and cannot be distinguished at runtime.", - "Remove one of the ambiguous items in the ABI." - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiItem.AmbiguityError" - }); +var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); +function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) { + if (utils_default.isFunction(filter2)) { + return filter2.call(this, value, header); } -}; -var NotFoundError2 = class extends BaseError3 { - constructor({ name, data, type = "item" }) { - const selector = (() => { - if (name) - return ` with name "${name}"`; - if (data) - return ` with data "${data}"`; - return ""; - })(); - super(`ABI ${type}${selector} not found.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiItem.NotFoundError" + if (isHeaderNameFilter) { + value = header; + } + if (!utils_default.isString(value)) return; + if (utils_default.isString(filter2)) { + return value.indexOf(filter2) !== -1; + } + if (utils_default.isRegExp(filter2)) { + return filter2.test(value); + } +} +function formatHeader(header) { + return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str) => { + return char.toUpperCase() + str; + }); +} +function buildAccessors(obj, header) { + const accessorName = utils_default.toCamelCase(" " + header); + ["get", "set", "has"].forEach((methodName) => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true }); + }); +} +var AxiosHeaders = class { + constructor(headers) { + headers && this.set(headers); } -}; - -// node_modules/ox/_esm/core/Solidity.js -var arrayRegex = /^(.*)\[([0-9]*)\]$/; -var bytesRegex3 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; -var integerRegex3 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; -var maxInt82 = 2n ** (8n - 1n) - 1n; -var maxInt162 = 2n ** (16n - 1n) - 1n; -var maxInt242 = 2n ** (24n - 1n) - 1n; -var maxInt322 = 2n ** (32n - 1n) - 1n; -var maxInt402 = 2n ** (40n - 1n) - 1n; -var maxInt482 = 2n ** (48n - 1n) - 1n; -var maxInt562 = 2n ** (56n - 1n) - 1n; -var maxInt642 = 2n ** (64n - 1n) - 1n; -var maxInt722 = 2n ** (72n - 1n) - 1n; -var maxInt802 = 2n ** (80n - 1n) - 1n; -var maxInt882 = 2n ** (88n - 1n) - 1n; -var maxInt962 = 2n ** (96n - 1n) - 1n; -var maxInt1042 = 2n ** (104n - 1n) - 1n; -var maxInt1122 = 2n ** (112n - 1n) - 1n; -var maxInt1202 = 2n ** (120n - 1n) - 1n; -var maxInt1282 = 2n ** (128n - 1n) - 1n; -var maxInt1362 = 2n ** (136n - 1n) - 1n; -var maxInt1442 = 2n ** (144n - 1n) - 1n; -var maxInt1522 = 2n ** (152n - 1n) - 1n; -var maxInt1602 = 2n ** (160n - 1n) - 1n; -var maxInt1682 = 2n ** (168n - 1n) - 1n; -var maxInt1762 = 2n ** (176n - 1n) - 1n; -var maxInt1842 = 2n ** (184n - 1n) - 1n; -var maxInt1922 = 2n ** (192n - 1n) - 1n; -var maxInt2002 = 2n ** (200n - 1n) - 1n; -var maxInt2082 = 2n ** (208n - 1n) - 1n; -var maxInt2162 = 2n ** (216n - 1n) - 1n; -var maxInt2242 = 2n ** (224n - 1n) - 1n; -var maxInt2322 = 2n ** (232n - 1n) - 1n; -var maxInt2402 = 2n ** (240n - 1n) - 1n; -var maxInt2482 = 2n ** (248n - 1n) - 1n; -var maxInt2562 = 2n ** (256n - 1n) - 1n; -var minInt82 = -(2n ** (8n - 1n)); -var minInt162 = -(2n ** (16n - 1n)); -var minInt242 = -(2n ** (24n - 1n)); -var minInt322 = -(2n ** (32n - 1n)); -var minInt402 = -(2n ** (40n - 1n)); -var minInt482 = -(2n ** (48n - 1n)); -var minInt562 = -(2n ** (56n - 1n)); -var minInt642 = -(2n ** (64n - 1n)); -var minInt722 = -(2n ** (72n - 1n)); -var minInt802 = -(2n ** (80n - 1n)); -var minInt882 = -(2n ** (88n - 1n)); -var minInt962 = -(2n ** (96n - 1n)); -var minInt1042 = -(2n ** (104n - 1n)); -var minInt1122 = -(2n ** (112n - 1n)); -var minInt1202 = -(2n ** (120n - 1n)); -var minInt1282 = -(2n ** (128n - 1n)); -var minInt1362 = -(2n ** (136n - 1n)); -var minInt1442 = -(2n ** (144n - 1n)); -var minInt1522 = -(2n ** (152n - 1n)); -var minInt1602 = -(2n ** (160n - 1n)); -var minInt1682 = -(2n ** (168n - 1n)); -var minInt1762 = -(2n ** (176n - 1n)); -var minInt1842 = -(2n ** (184n - 1n)); -var minInt1922 = -(2n ** (192n - 1n)); -var minInt2002 = -(2n ** (200n - 1n)); -var minInt2082 = -(2n ** (208n - 1n)); -var minInt2162 = -(2n ** (216n - 1n)); -var minInt2242 = -(2n ** (224n - 1n)); -var minInt2322 = -(2n ** (232n - 1n)); -var minInt2402 = -(2n ** (240n - 1n)); -var minInt2482 = -(2n ** (248n - 1n)); -var minInt2562 = -(2n ** (256n - 1n)); -var maxUint82 = 2n ** 8n - 1n; -var maxUint162 = 2n ** 16n - 1n; -var maxUint242 = 2n ** 24n - 1n; -var maxUint322 = 2n ** 32n - 1n; -var maxUint402 = 2n ** 40n - 1n; -var maxUint482 = 2n ** 48n - 1n; -var maxUint562 = 2n ** 56n - 1n; -var maxUint642 = 2n ** 64n - 1n; -var maxUint722 = 2n ** 72n - 1n; -var maxUint802 = 2n ** 80n - 1n; -var maxUint882 = 2n ** 88n - 1n; -var maxUint962 = 2n ** 96n - 1n; -var maxUint1042 = 2n ** 104n - 1n; -var maxUint1122 = 2n ** 112n - 1n; -var maxUint1202 = 2n ** 120n - 1n; -var maxUint1282 = 2n ** 128n - 1n; -var maxUint1362 = 2n ** 136n - 1n; -var maxUint1442 = 2n ** 144n - 1n; -var maxUint1522 = 2n ** 152n - 1n; -var maxUint1602 = 2n ** 160n - 1n; -var maxUint1682 = 2n ** 168n - 1n; -var maxUint1762 = 2n ** 176n - 1n; -var maxUint1842 = 2n ** 184n - 1n; -var maxUint1922 = 2n ** 192n - 1n; -var maxUint2002 = 2n ** 200n - 1n; -var maxUint2082 = 2n ** 208n - 1n; -var maxUint2162 = 2n ** 216n - 1n; -var maxUint2242 = 2n ** 224n - 1n; -var maxUint2322 = 2n ** 232n - 1n; -var maxUint2402 = 2n ** 240n - 1n; -var maxUint2482 = 2n ** 248n - 1n; -var maxUint2562 = 2n ** 256n - 1n; - -// node_modules/ox/_esm/core/internal/abiParameters.js -function prepareParameters({ checksumAddress: checksumAddress2, parameters, values }) { - const preparedParameters = []; - for (let i = 0; i < parameters.length; i++) { - preparedParameters.push(prepareParameter({ - checksumAddress: checksumAddress2, - parameter: parameters[i], - value: values[i] - })); + set(header, valueOrRewrite, rewrite) { + const self2 = this; + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + if (!lHeader) { + throw new Error("header name must be a non-empty string"); + } + const key = utils_default.findKey(self2, lHeader); + if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { + self2[key || _header] = normalizeValue(_value); + } + } + const setHeaders = (headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + if (utils_default.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders_default(header), valueOrRewrite); + } else if (utils_default.isObject(header) && utils_default.isIterable(header)) { + let obj = {}, dest, key; + for (const entry of header) { + if (!utils_default.isArray(entry)) { + throw TypeError("Object iterator must return a key-value pair"); + } + obj[key = entry[0]] = (dest = obj[key]) ? utils_default.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1]; + } + setHeaders(obj, valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); + } + return this; } - return preparedParameters; -} -function prepareParameter({ checksumAddress: checksumAddress2 = false, parameter: parameter_, value }) { - const parameter = parameter_; - const arrayComponents = getArrayComponents2(parameter.type); - if (arrayComponents) { - const [length, type] = arrayComponents; - return encodeArray2(value, { - checksumAddress: checksumAddress2, - length, - parameter: { - ...parameter, - type + get(header, parser) { + header = normalizeHeader(header); + if (header) { + const key = utils_default.findKey(this, header); + if (key) { + const value = this[key]; + if (!parser) { + return value; + } + if (parser === true) { + return parseTokens(value); + } + if (utils_default.isFunction(parser)) { + return parser.call(this, value, key); + } + if (utils_default.isRegExp(parser)) { + return parser.exec(value); + } + throw new TypeError("parser must be boolean|regexp|function"); } - }); + } } - if (parameter.type === "tuple") { - return encodeTuple2(value, { - checksumAddress: checksumAddress2, - parameter - }); + has(header, matcher) { + header = normalizeHeader(header); + if (header) { + const key = utils_default.findKey(this, header); + return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + } + return false; } - if (parameter.type === "address") { - return encodeAddress2(value, { - checksum: checksumAddress2 + delete(header, matcher) { + const self2 = this; + let deleted = false; + function deleteHeader(_header) { + _header = normalizeHeader(_header); + if (_header) { + const key = utils_default.findKey(self2, _header); + if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { + delete self2[key]; + deleted = true; + } + } + } + if (utils_default.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); + } + return deleted; + } + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + while (i--) { + const key = keys[i]; + if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } + } + return deleted; + } + normalize(format) { + const self2 = this; + const headers = {}; + utils_default.forEach(this, (value, header) => { + const key = utils_default.findKey(headers, header); + if (key) { + self2[key] = normalizeValue(value); + delete self2[header]; + return; + } + const normalized = format ? formatHeader(header) : String(header).trim(); + if (normalized !== header) { + delete self2[header]; + } + self2[normalized] = normalizeValue(value); + headers[normalized] = true; }); + return this; } - if (parameter.type === "bool") { - return encodeBoolean(value); + concat(...targets) { + return this.constructor.concat(this, ...targets); } - if (parameter.type.startsWith("uint") || parameter.type.startsWith("int")) { - const signed = parameter.type.startsWith("int"); - const [, , size5 = "256"] = integerRegex3.exec(parameter.type) ?? []; - return encodeNumber2(value, { - signed, - size: Number(size5) + toJSON(asStrings) { + const obj = /* @__PURE__ */ Object.create(null); + utils_default.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value); }); + return obj; } - if (parameter.type.startsWith("bytes")) { - return encodeBytes2(value, { type: parameter.type }); + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); } - if (parameter.type === "string") { - return encodeString2(value); + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); } - throw new InvalidTypeError(parameter.type); -} -function encode3(preparedParameters) { - let staticSize = 0; - for (let i = 0; i < preparedParameters.length; i++) { - const { dynamic, encoded } = preparedParameters[i]; - if (dynamic) - staticSize += 32; - else - staticSize += size4(encoded); + getSetCookie() { + return this.get("set-cookie") || []; } - const staticParameters = []; - const dynamicParameters = []; - let dynamicSize = 0; - for (let i = 0; i < preparedParameters.length; i++) { - const { dynamic, encoded } = preparedParameters[i]; - if (dynamic) { - staticParameters.push(fromNumber(staticSize + dynamicSize, { size: 32 })); - dynamicParameters.push(encoded); - dynamicSize += size4(encoded); - } else { - staticParameters.push(encoded); - } + get [Symbol.toStringTag]() { + return "AxiosHeaders"; } - return concat2(...staticParameters, ...dynamicParameters); -} -function encodeAddress2(value, options) { - const { checksum: checksum3 = false } = options; - assert2(value, { strict: checksum3 }); - return { - dynamic: false, - encoded: padLeft(value.toLowerCase()) - }; -} -function encodeArray2(value, options) { - const { checksumAddress: checksumAddress2, length, parameter } = options; - const dynamic = length === null; - if (!Array.isArray(value)) - throw new InvalidArrayError2(value); - if (!dynamic && value.length !== length) - throw new ArrayLengthMismatchError({ - expectedLength: length, - givenLength: value.length, - type: `${parameter.type}[${length}]` - }); - let dynamicChild = false; - const preparedParameters = []; - for (let i = 0; i < value.length; i++) { - const preparedParam = prepareParameter({ - checksumAddress: checksumAddress2, - parameter, - value: value[i] - }); - if (preparedParam.dynamic) - dynamicChild = true; - preparedParameters.push(preparedParam); + static from(thing) { + return thing instanceof this ? thing : new this(thing); } - if (dynamic || dynamicChild) { - const data = encode3(preparedParameters); - if (dynamic) { - const length2 = fromNumber(preparedParameters.length, { size: 32 }); - return { - dynamic: true, - encoded: preparedParameters.length > 0 ? concat2(length2, data) : length2 - }; + static concat(first, ...targets) { + const computed = new this(first); + targets.forEach((target) => computed.set(target)); + return computed; + } + static accessor(header) { + const internals = this[$internals] = this[$internals] = { + accessors: {} + }; + const accessors = internals.accessors; + const prototype3 = this.prototype; + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + if (!accessors[lHeader]) { + buildAccessors(prototype3, _header); + accessors[lHeader] = true; + } } - if (dynamicChild) - return { dynamic: true, encoded: data }; + utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + return this; } +}; +AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); +utils_default.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); return { - dynamic: false, - encoded: concat2(...preparedParameters.map(({ encoded }) => encoded)) + get: () => value, + set(headerValue) { + this[mapped] = headerValue; + } }; +}); +utils_default.freezeMethods(AxiosHeaders); +var AxiosHeaders_default = AxiosHeaders; + +// node_modules/axios/lib/core/transformData.js +function transformData(fns, response) { + const config3 = this || defaults_default; + const context = response || config3; + const headers = AxiosHeaders_default.from(context.headers); + let data = context.data; + utils_default.forEach(fns, function transform(fn2) { + data = fn2.call(config3, data, headers.normalize(), response ? response.status : void 0); + }); + headers.normalize(); + return data; } -function encodeBytes2(value, { type }) { - const [, parametersize] = type.split("bytes"); - const bytesSize = size4(value); - if (!parametersize) { - let value_ = value; - if (bytesSize % 32 !== 0) - value_ = padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32); - return { - dynamic: true, - encoded: concat2(padLeft(fromNumber(bytesSize, { size: 32 })), value_) - }; - } - if (bytesSize !== Number.parseInt(parametersize)) - throw new BytesSizeMismatchError2({ - expectedSize: Number.parseInt(parametersize), - value - }); - return { dynamic: false, encoded: padRight(value) }; + +// node_modules/axios/lib/cancel/isCancel.js +function isCancel(value) { + return !!(value && value.__CANCEL__); } -function encodeBoolean(value) { - if (typeof value !== "boolean") - throw new BaseError3(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); - return { dynamic: false, encoded: padLeft(fromBoolean(value)) }; + +// node_modules/axios/lib/cancel/CanceledError.js +function CanceledError(message, config3, request) { + AxiosError_default.call(this, message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config3, request); + this.name = "CanceledError"; } -function encodeNumber2(value, { signed, size: size5 }) { - if (typeof size5 === "number") { - const max = 2n ** (BigInt(size5) - (signed ? 1n : 0n)) - 1n; - const min = signed ? -max - 1n : 0n; - if (value > max || value < min) - throw new IntegerOutOfRangeError2({ - max: max.toString(), - min: min.toString(), - signed, - size: size5 / 8, - value: value.toString() - }); +utils_default.inherits(CanceledError, AxiosError_default, { + __CANCEL__: true +}); +var CanceledError_default = CanceledError; + +// node_modules/axios/lib/core/settle.js +function settle(resolve, reject, response) { + const validateStatus2 = response.config.validateStatus; + if (!response.status || !validateStatus2 || validateStatus2(response.status)) { + resolve(response); + } else { + reject(new AxiosError_default( + "Request failed with status code " + response.status, + [AxiosError_default.ERR_BAD_REQUEST, AxiosError_default.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); } - return { - dynamic: false, - encoded: fromNumber(value, { - size: 32, - signed - }) - }; } -function encodeString2(value) { - const hexValue = fromString2(value); - const partsLength = Math.ceil(size4(hexValue) / 32); - const parts = []; - for (let i = 0; i < partsLength; i++) { - parts.push(padRight(slice2(hexValue, i * 32, (i + 1) * 32))); - } - return { - dynamic: true, - encoded: concat2(padRight(fromNumber(size4(hexValue), { size: 32 })), ...parts) - }; + +// node_modules/axios/lib/helpers/isAbsoluteURL.js +function isAbsoluteURL(url2) { + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url2); } -function encodeTuple2(value, options) { - const { checksumAddress: checksumAddress2, parameter } = options; - let dynamic = false; - const preparedParameters = []; - for (let i = 0; i < parameter.components.length; i++) { - const param_ = parameter.components[i]; - const index2 = Array.isArray(value) ? i : param_.name; - const preparedParam = prepareParameter({ - checksumAddress: checksumAddress2, - parameter: param_, - value: value[index2] - }); - preparedParameters.push(preparedParam); - if (preparedParam.dynamic) - dynamic = true; - } - return { - dynamic, - encoded: dynamic ? encode3(preparedParameters) : concat2(...preparedParameters.map(({ encoded }) => encoded)) - }; + +// node_modules/axios/lib/helpers/combineURLs.js +function combineURLs(baseURL, relativeURL) { + return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; } -function getArrayComponents2(type) { - const matches = type.match(/^(.*)\[(\d+)?\]$/); - return matches ? ( - // Return `null` if the array is dynamic. - [matches[2] ? Number(matches[2]) : null, matches[1]] - ) : void 0; + +// node_modules/axios/lib/core/buildFullPath.js +function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) { + let isRelativeUrl = !isAbsoluteURL(requestedURL); + if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; } -// node_modules/ox/_esm/core/AbiParameters.js -function encode4(parameters, values, options) { - const { checksumAddress: checksumAddress2 = false } = options ?? {}; - if (parameters.length !== values.length) - throw new LengthMismatchError({ - expectedLength: parameters.length, - givenLength: values.length - }); - const preparedParameters = prepareParameters({ - checksumAddress: checksumAddress2, - parameters, - values - }); - const data = encode3(preparedParameters); - if (data.length === 0) - return "0x"; - return data; +// node_modules/axios/lib/adapters/http.js +var import_proxy_from_env = __toESM(require_proxy_from_env(), 1); +var import_follow_redirects = __toESM(require_follow_redirects(), 1); +import http2 from "http"; +import https from "https"; +import util2 from "util"; +import zlib from "zlib"; + +// node_modules/axios/lib/env/data.js +var VERSION = "1.9.0"; + +// node_modules/axios/lib/helpers/parseProtocol.js +function parseProtocol(url2) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url2); + return match && match[1] || ""; } -function encodePacked(types, values) { - if (types.length !== values.length) - throw new LengthMismatchError({ - expectedLength: types.length, - givenLength: values.length - }); - const data = []; - for (let i = 0; i < types.length; i++) { - const type = types[i]; - const value = values[i]; - data.push(encodePacked.encode(type, value)); + +// node_modules/axios/lib/helpers/fromDataURI.js +var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; +function fromDataURI(uri, asBlob, options) { + const _Blob = options && options.Blob || platform_default.classes.Blob; + const protocol = parseProtocol(uri); + if (asBlob === void 0 && _Blob) { + asBlob = true; } - return concat2(...data); -} -(function(encodePacked2) { - function encode6(type, value, isArray2 = false) { - if (type === "address") { - const address = value; - assert2(address); - return padLeft(address.toLowerCase(), isArray2 ? 32 : 0); - } - if (type === "string") - return fromString2(value); - if (type === "bytes") - return value; - if (type === "bool") - return padLeft(fromBoolean(value), isArray2 ? 32 : 1); - const intMatch = type.match(integerRegex3); - if (intMatch) { - const [_type, baseType, bits = "256"] = intMatch; - const size5 = Number.parseInt(bits) / 8; - return fromNumber(value, { - size: isArray2 ? 32 : size5, - signed: baseType === "int" - }); + if (protocol === "data") { + uri = protocol.length ? uri.slice(protocol.length + 1) : uri; + const match = DATA_URL_PATTERN.exec(uri); + if (!match) { + throw new AxiosError_default("Invalid URL", AxiosError_default.ERR_INVALID_URL); } - const bytesMatch = type.match(bytesRegex3); - if (bytesMatch) { - const [_type, size5] = bytesMatch; - if (Number.parseInt(size5) !== (value.length - 2) / 2) - throw new BytesSizeMismatchError2({ - expectedSize: Number.parseInt(size5), - value - }); - return padRight(value, isArray2 ? 32 : 0); + const mime = match[1]; + const isBase64 = match[2]; + const body = match[3]; + const buffer2 = Buffer.from(decodeURIComponent(body), isBase64 ? "base64" : "utf8"); + if (asBlob) { + if (!_Blob) { + throw new AxiosError_default("Blob is not supported", AxiosError_default.ERR_NOT_SUPPORT); + } + return new _Blob([buffer2], { type: mime }); } - const arrayMatch = type.match(arrayRegex); - if (arrayMatch && Array.isArray(value)) { - const [_type, childType] = arrayMatch; - const data = []; - for (let i = 0; i < value.length; i++) { - data.push(encode6(childType, value[i], true)); + return buffer2; + } + throw new AxiosError_default("Unsupported protocol " + protocol, AxiosError_default.ERR_NOT_SUPPORT); +} + +// node_modules/axios/lib/adapters/http.js +import stream3 from "stream"; + +// node_modules/axios/lib/helpers/AxiosTransformStream.js +import stream from "stream"; +var kInternals = Symbol("internals"); +var AxiosTransformStream = class extends stream.Transform { + constructor(options) { + options = utils_default.toFlatObject(options, { + maxRate: 0, + chunkSize: 64 * 1024, + minChunkSize: 100, + timeWindow: 500, + ticksRate: 2, + samplesCount: 15 + }, null, (prop, source) => { + return !utils_default.isUndefined(source[prop]); + }); + super({ + readableHighWaterMark: options.chunkSize + }); + const internals = this[kInternals] = { + timeWindow: options.timeWindow, + chunkSize: options.chunkSize, + maxRate: options.maxRate, + minChunkSize: options.minChunkSize, + bytesSeen: 0, + isCaptured: false, + notifiedBytesLoaded: 0, + ts: Date.now(), + bytes: 0, + onReadCallback: null + }; + this.on("newListener", (event) => { + if (event === "progress") { + if (!internals.isCaptured) { + internals.isCaptured = true; + } } - if (data.length === 0) - return "0x"; - return concat2(...data); + }); + } + _read(size5) { + const internals = this[kInternals]; + if (internals.onReadCallback) { + internals.onReadCallback(); } - throw new InvalidTypeError(type); + return super._read(size5); } - encodePacked2.encode = encode6; -})(encodePacked || (encodePacked = {})); -var ArrayLengthMismatchError = class extends BaseError3 { - constructor({ expectedLength, givenLength, type }) { - super(`Array length mismatch for type \`${type}\`. Expected: \`${expectedLength}\`. Given: \`${givenLength}\`.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.ArrayLengthMismatchError" + _transform(chunk, encoding, callback) { + const internals = this[kInternals]; + const maxRate = internals.maxRate; + const readableHighWaterMark = this.readableHighWaterMark; + const timeWindow = internals.timeWindow; + const divider = 1e3 / timeWindow; + const bytesThreshold = maxRate / divider; + const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; + const pushChunk = (_chunk, _callback) => { + const bytes = Buffer.byteLength(_chunk); + internals.bytesSeen += bytes; + internals.bytes += bytes; + internals.isCaptured && this.emit("progress", internals.bytesSeen); + if (this.push(_chunk)) { + process.nextTick(_callback); + } else { + internals.onReadCallback = () => { + internals.onReadCallback = null; + process.nextTick(_callback); + }; + } + }; + const transformChunk = (_chunk, _callback) => { + const chunkSize = Buffer.byteLength(_chunk); + let chunkRemainder = null; + let maxChunkSize = readableHighWaterMark; + let bytesLeft; + let passed = 0; + if (maxRate) { + const now = Date.now(); + if (!internals.ts || (passed = now - internals.ts) >= timeWindow) { + internals.ts = now; + bytesLeft = bytesThreshold - internals.bytes; + internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; + passed = 0; + } + bytesLeft = bytesThreshold - internals.bytes; + } + if (maxRate) { + if (bytesLeft <= 0) { + return setTimeout(() => { + _callback(null, _chunk); + }, timeWindow - passed); + } + if (bytesLeft < maxChunkSize) { + maxChunkSize = bytesLeft; + } + } + if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) { + chunkRemainder = _chunk.subarray(maxChunkSize); + _chunk = _chunk.subarray(0, maxChunkSize); + } + pushChunk(_chunk, chunkRemainder ? () => { + process.nextTick(_callback, null, chunkRemainder); + } : _callback); + }; + transformChunk(chunk, function transformNextChunk(err, _chunk) { + if (err) { + return callback(err); + } + if (_chunk) { + transformChunk(_chunk, transformNextChunk); + } else { + callback(null); + } }); } }; -var BytesSizeMismatchError2 = class extends BaseError3 { - constructor({ expectedSize, value }) { - super(`Size of bytes "${value}" (bytes${size4(value)}) does not match expected size (bytes${expectedSize}).`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.BytesSizeMismatchError" - }); +var AxiosTransformStream_default = AxiosTransformStream; + +// node_modules/axios/lib/adapters/http.js +import { EventEmitter as EventEmitter2 } from "events"; + +// node_modules/axios/lib/helpers/formDataToStream.js +import util from "util"; +import { Readable } from "stream"; + +// node_modules/axios/lib/helpers/readBlob.js +var { asyncIterator } = Symbol; +var readBlob = async function* (blob) { + if (blob.stream) { + yield* blob.stream(); + } else if (blob.arrayBuffer) { + yield await blob.arrayBuffer(); + } else if (blob[asyncIterator]) { + yield* blob[asyncIterator](); + } else { + yield blob; } }; -var LengthMismatchError = class extends BaseError3 { - constructor({ expectedLength, givenLength }) { - super([ - "ABI encoding parameters/values length mismatch.", - `Expected length (parameters): ${expectedLength}`, - `Given length (values): ${givenLength}` - ].join("\n")); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.LengthMismatchError" - }); +var readBlob_default = readBlob; + +// node_modules/axios/lib/helpers/formDataToStream.js +var BOUNDARY_ALPHABET = platform_default.ALPHABET.ALPHA_DIGIT + "-_"; +var textEncoder = typeof TextEncoder === "function" ? new TextEncoder() : new util.TextEncoder(); +var CRLF = "\r\n"; +var CRLF_BYTES = textEncoder.encode(CRLF); +var CRLF_BYTES_COUNT = 2; +var FormDataPart = class { + constructor(name, value) { + const { escapeName } = this.constructor; + const isStringValue = utils_default.isString(value); + let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF}`; + if (isStringValue) { + value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); + } else { + headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; + } + this.headers = textEncoder.encode(headers + CRLF); + this.contentLength = isStringValue ? value.byteLength : value.size; + this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; + this.name = name; + this.value = value; } -}; -var InvalidArrayError2 = class extends BaseError3 { - constructor(value) { - super(`Value \`${value}\` is not a valid array.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.InvalidArrayError" - }); + async *encode() { + yield this.headers; + const { value } = this; + if (utils_default.isTypedArray(value)) { + yield value; + } else { + yield* readBlob_default(value); + } + yield CRLF_BYTES; + } + static escapeName(name) { + return String(name).replace(/[\r\n"]/g, (match) => ({ + "\r": "%0D", + "\n": "%0A", + '"': "%22" + })[match]); } }; -var InvalidTypeError = class extends BaseError3 { - constructor(type) { - super(`Type \`${type}\` is not a valid ABI Type.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.InvalidTypeError" - }); +var formDataToStream = (form, headersHandler, options) => { + const { + tag = "form-data-boundary", + size: size5 = 25, + boundary = tag + "-" + platform_default.generateString(size5, BOUNDARY_ALPHABET) + } = options || {}; + if (!utils_default.isFormData(form)) { + throw TypeError("FormData instance required"); + } + if (boundary.length < 1 || boundary.length > 70) { + throw Error("boundary must be 10-70 characters long"); + } + const boundaryBytes = textEncoder.encode("--" + boundary + CRLF); + const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF); + let contentLength = footerBytes.byteLength; + const parts = Array.from(form.entries()).map(([name, value]) => { + const part = new FormDataPart(name, value); + contentLength += part.size; + return part; + }); + contentLength += boundaryBytes.byteLength * parts.length; + contentLength = utils_default.toFiniteNumber(contentLength); + const computedHeaders = { + "Content-Type": `multipart/form-data; boundary=${boundary}` + }; + if (Number.isFinite(contentLength)) { + computedHeaders["Content-Length"] = contentLength; } + headersHandler && headersHandler(computedHeaders); + return Readable.from(async function* () { + for (const part of parts) { + yield boundaryBytes; + yield* part.encode(); + } + yield footerBytes; + }()); }; +var formDataToStream_default = formDataToStream; -// node_modules/ox/_esm/core/AbiConstructor.js -function encode5(abiConstructor, options) { - const { bytecode, args } = options; - return concat2(bytecode, abiConstructor.inputs?.length && args?.length ? encode4(abiConstructor.inputs, args) : "0x"); -} -function from3(abiConstructor) { - return from2(abiConstructor); -} - -// node_modules/ox/_esm/core/AbiFunction.js -function encodeData2(abiFunction, ...args) { - const { overloads } = abiFunction; - const item = overloads ? fromAbi2([abiFunction, ...overloads], abiFunction.name, { - args: args[0] - }) : abiFunction; - const selector = getSelector2(item); - const data = args.length > 0 ? encode4(item.inputs, args[0]) : void 0; - return data ? concat2(selector, data) : selector; -} -function from4(abiFunction, options = {}) { - return from2(abiFunction, options); -} -function fromAbi2(abi4, name, options) { - const item = fromAbi(abi4, name, options); - if (item.type !== "function") - throw new NotFoundError2({ name, type: "function" }); - return item; -} -function getSelector2(abiItem) { - return getSelector(abiItem); -} - -// node_modules/viem/_esm/actions/public/simulateCalls.js -init_parseAccount(); - -// node_modules/viem/_esm/constants/address.js -var ethAddress = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; -var zeroAddress = "0x0000000000000000000000000000000000000000"; - -// node_modules/viem/_esm/actions/public/simulateCalls.js -init_contracts(); -init_base(); -init_encodeFunctionData(); -var getBalanceCode = "0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033"; -async function simulateCalls(client, parameters) { - const { blockNumber, blockTag, calls, stateOverrides, traceAssetChanges, traceTransfers, validation } = parameters; - const account = parameters.account ? parseAccount(parameters.account) : void 0; - if (traceAssetChanges && !account) - throw new BaseError2("`account` is required when `traceAssetChanges` is true"); - const getBalanceData = account ? encode5(from3("constructor(bytes, bytes)"), { - bytecode: deploylessCallViaBytecodeBytecode, - args: [ - getBalanceCode, - encodeData2(from4("function getBalance(address)"), [account.address]) - ] - }) : void 0; - const assetAddresses = traceAssetChanges ? await Promise.all(parameters.calls.map(async (call2) => { - if (!call2.data && !call2.abi) - return; - const { accessList } = await createAccessList(client, { - account: account.address, - ...call2, - data: call2.abi ? encodeFunctionData(call2) : call2.data - }); - return accessList.map(({ address, storageKeys }) => storageKeys.length > 0 ? address : null); - })).then((x2) => x2.flat().filter(Boolean)) : []; - const resultsStateOverrides = stateOverrides?.map((override) => { - if (override.address === account?.address) - return { - ...override, - nonce: 0 - }; - return override; - }); - const blocks = await simulateBlocks(client, { - blockNumber, - blockTag, - blocks: [ - ...traceAssetChanges ? [ - // ETH pre balances - { - calls: [{ data: getBalanceData }], - stateOverrides - }, - // Asset pre balances - { - calls: assetAddresses.map((address, i) => ({ - abi: [ - from4("function balanceOf(address) returns (uint256)") - ], - functionName: "balanceOf", - args: [account.address], - to: address, - from: zeroAddress, - nonce: i - })), - stateOverrides: [ - { - address: zeroAddress, - nonce: 0 - } - ] - } - ] : [], - { - calls: [...calls, {}].map((call2, index2) => ({ - ...call2, - from: account?.address, - nonce: index2 - })), - stateOverrides: resultsStateOverrides - }, - ...traceAssetChanges ? [ - // ETH post balances - { - calls: [{ data: getBalanceData }] - }, - // Asset post balances - { - calls: assetAddresses.map((address, i) => ({ - abi: [ - from4("function balanceOf(address) returns (uint256)") - ], - functionName: "balanceOf", - args: [account.address], - to: address, - from: zeroAddress, - nonce: i - })), - stateOverrides: [ - { - address: zeroAddress, - nonce: 0 - } - ] - }, - // Decimals - { - calls: assetAddresses.map((address, i) => ({ - to: address, - abi: [ - from4("function decimals() returns (uint256)") - ], - functionName: "decimals", - from: zeroAddress, - nonce: i - })), - stateOverrides: [ - { - address: zeroAddress, - nonce: 0 - } - ] - }, - // Token URI - { - calls: assetAddresses.map((address, i) => ({ - to: address, - abi: [ - from4("function tokenURI(uint256) returns (string)") - ], - functionName: "tokenURI", - args: [0n], - from: zeroAddress, - nonce: i - })), - stateOverrides: [ - { - address: zeroAddress, - nonce: 0 - } - ] - }, - // Symbols - { - calls: assetAddresses.map((address, i) => ({ - to: address, - abi: [from4("function symbol() returns (string)")], - functionName: "symbol", - from: zeroAddress, - nonce: i - })), - stateOverrides: [ - { - address: zeroAddress, - nonce: 0 - } - ] - } - ] : [] - ], - traceTransfers, - validation - }); - const block_results = traceAssetChanges ? blocks[2] : blocks[0]; - const [block_ethPre, block_assetsPre, , block_ethPost, block_assetsPost, block_decimals, block_tokenURI, block_symbols] = traceAssetChanges ? blocks : []; - const { calls: block_calls, ...block } = block_results; - const results = block_calls.slice(0, -1) ?? []; - const ethPre = block_ethPre?.calls ?? []; - const assetsPre = block_assetsPre?.calls ?? []; - const balancesPre = [...ethPre, ...assetsPre].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null); - const ethPost = block_ethPost?.calls ?? []; - const assetsPost = block_assetsPost?.calls ?? []; - const balancesPost = [...ethPost, ...assetsPost].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null); - const decimals = (block_decimals?.calls ?? []).map((x2) => x2.status === "success" ? x2.result : null); - const symbols = (block_symbols?.calls ?? []).map((x2) => x2.status === "success" ? x2.result : null); - const tokenURI = (block_tokenURI?.calls ?? []).map((x2) => x2.status === "success" ? x2.result : null); - const changes = []; - for (const [i, balancePost] of balancesPost.entries()) { - const balancePre = balancesPre[i]; - if (typeof balancePost !== "bigint") - continue; - if (typeof balancePre !== "bigint") - continue; - const decimals_ = decimals[i - 1]; - const symbol_ = symbols[i - 1]; - const tokenURI_ = tokenURI[i - 1]; - const token = (() => { - if (i === 0) - return { - address: ethAddress, - decimals: 18, - symbol: "ETH" - }; - return { - address: assetAddresses[i - 1], - decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : void 0, - symbol: symbol_ ?? void 0 - }; - })(); - if (changes.some((change) => change.token.address === token.address)) - continue; - changes.push({ - token, - value: { - pre: balancePre, - post: balancePost, - diff: balancePost - balancePre +// node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js +import stream2 from "stream"; +var ZlibHeaderTransformStream = class extends stream2.Transform { + __transform(chunk, encoding, callback) { + this.push(chunk); + callback(); + } + _transform(chunk, encoding, callback) { + if (chunk.length !== 0) { + this._transform = this.__transform; + if (chunk[0] !== 120) { + const header = Buffer.alloc(2); + header[0] = 120; + header[1] = 156; + this.push(header, encoding); } - }); + } + this.__transform(chunk, encoding, callback); } - return { - assetChanges: changes, - block, - results +}; +var ZlibHeaderTransformStream_default = ZlibHeaderTransformStream; + +// node_modules/axios/lib/helpers/callbackify.js +var callbackify = (fn2, reducer) => { + return utils_default.isAsyncFn(fn2) ? function(...args) { + const cb = args.pop(); + fn2.apply(this, args).then((value) => { + try { + reducer ? cb(null, ...reducer(value)) : cb(null, value); + } catch (err) { + cb(err); + } + }, cb); + } : fn2; +}; +var callbackify_default = callbackify; + +// node_modules/axios/lib/helpers/speedometer.js +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; + min = min !== void 0 ? min : 1e3; + return function push(chunkLength) { + const now = Date.now(); + const startedAt = timestamps[tail]; + if (!firstSampleTS) { + firstSampleTS = now; + } + bytes[head] = chunkLength; + timestamps[head] = now; + let i = tail; + let bytesCount = 0; + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } + head = (head + 1) % samplesCount; + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + if (now - firstSampleTS < min) { + return; + } + const passed = startedAt && now - startedAt; + return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; }; } +var speedometer_default = speedometer; -// node_modules/viem/_esm/actions/public/verifyHash.js -init_abis(); -init_contracts(); -init_contract(); -init_encodeDeployData(); -init_getAddress(); -init_isAddressEqual(); -init_isHex(); -init_toHex(); - -// node_modules/viem/_esm/utils/signature/serializeSignature.js -init_secp256k1(); -init_fromHex(); -init_toBytes(); -function serializeSignature({ r, s, to: to2 = "hex", v, yParity }) { - const yParity_ = (() => { - if (yParity === 0 || yParity === 1) - return yParity; - if (v && (v === 27n || v === 28n || v >= 35n)) - return v % 2n === 0n ? 1 : 0; - throw new Error("Invalid `v` or `yParity` value"); - })(); - const signature = `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`; - if (to2 === "hex") - return signature; - return hexToBytes(signature); +// node_modules/axios/lib/helpers/throttle.js +function throttle(fn2, freq) { + let timestamp = 0; + let threshold = 1e3 / freq; + let lastArgs; + let timer; + const invoke = (args, now = Date.now()) => { + timestamp = now; + lastArgs = null; + if (timer) { + clearTimeout(timer); + timer = null; + } + fn2.apply(null, args); + }; + const throttled = (...args) => { + const now = Date.now(); + const passed = now - timestamp; + if (passed >= threshold) { + invoke(args, now); + } else { + lastArgs = args; + if (!timer) { + timer = setTimeout(() => { + timer = null; + invoke(lastArgs); + }, threshold - passed); + } + } + }; + const flush = () => lastArgs && invoke(lastArgs); + return [throttled, flush]; } +var throttle_default = throttle; -// node_modules/viem/_esm/actions/public/verifyHash.js -init_call(); -async function verifyHash(client, parameters) { - const { address, factory, factoryData, hash: hash2, signature, universalSignatureVerifierAddress = client.chain?.contracts?.universalSignatureVerifier?.address, ...rest } = parameters; - const signatureHex = (() => { - if (isHex(signature)) - return signature; - if (typeof signature === "object" && "r" in signature && "s" in signature) - return serializeSignature(signature); - return bytesToHex(signature); - })(); - const wrappedSignature = await (async () => { - if (!factory && !factoryData) - return signatureHex; - if (isErc6492Signature(signatureHex)) - return signatureHex; - return serializeErc6492Signature({ - address: factory, - data: factoryData, - signature: signatureHex - }); - })(); - try { - const args = universalSignatureVerifierAddress ? { - to: universalSignatureVerifierAddress, - data: encodeFunctionData({ - abi: universalSignatureValidatorAbi, - functionName: "isValidSig", - args: [address, hash2, wrappedSignature] - }), - ...rest - } : { - data: encodeDeployData({ - abi: universalSignatureValidatorAbi, - args: [address, hash2, wrappedSignature], - bytecode: universalSignatureValidatorByteCode - }), - ...rest +// node_modules/axios/lib/helpers/progressEventReducer.js +var progressEventReducer = (listener, isDownloadStream, freq = 3) => { + let bytesNotified = 0; + const _speedometer = speedometer_default(50, 250); + return throttle_default((e) => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : void 0; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange2 = loaded <= total; + bytesNotified = loaded; + const data = { + loaded, + total, + progress: total ? loaded / total : void 0, + bytes: progressBytes, + rate: rate ? rate : void 0, + estimated: rate && total && inRange2 ? (total - loaded) / rate : void 0, + event: e, + lengthComputable: total != null, + [isDownloadStream ? "download" : "upload"]: true }; - const { data } = await getAction(client, call, "call")(args); - return hexToBool(data ?? "0x0"); - } catch (error) { - try { - const verified = isAddressEqual(getAddress(address), await recoverAddress({ hash: hash2, signature })); - if (verified) - return true; - } catch { + listener(data); + }, freq); +}; +var progressEventDecorator = (total, throttled) => { + const lengthComputable = total != null; + return [(loaded) => throttled[0]({ + lengthComputable, + total, + loaded + }), throttled[1]]; +}; +var asyncDecorator = (fn2) => (...args) => utils_default.asap(() => fn2(...args)); + +// node_modules/axios/lib/adapters/http.js +var zlibOptions = { + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH +}; +var brotliOptions = { + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH +}; +var isBrotliSupported = utils_default.isFunction(zlib.createBrotliDecompress); +var { http: httpFollow, https: httpsFollow } = import_follow_redirects.default; +var isHttps = /https:?/; +var supportedProtocols = platform_default.protocols.map((protocol) => { + return protocol + ":"; +}); +var flushOnFinish = (stream4, [throttled, flush]) => { + stream4.on("end", flush).on("error", flush); + return throttled; +}; +function dispatchBeforeRedirect(options, responseDetails) { + if (options.beforeRedirects.proxy) { + options.beforeRedirects.proxy(options); + } + if (options.beforeRedirects.config) { + options.beforeRedirects.config(options, responseDetails); + } +} +function setProxy(options, configProxy, location) { + let proxy = configProxy; + if (!proxy && proxy !== false) { + const proxyUrl = import_proxy_from_env.default.getProxyForUrl(location); + if (proxyUrl) { + proxy = new URL(proxyUrl); } - if (error instanceof CallExecutionError) { - return false; + } + if (proxy) { + if (proxy.username) { + proxy.auth = (proxy.username || "") + ":" + (proxy.password || ""); + } + if (proxy.auth) { + if (proxy.auth.username || proxy.auth.password) { + proxy.auth = (proxy.auth.username || "") + ":" + (proxy.auth.password || ""); + } + const base64 = Buffer.from(proxy.auth, "utf8").toString("base64"); + options.headers["Proxy-Authorization"] = "Basic " + base64; + } + options.headers.host = options.hostname + (options.port ? ":" + options.port : ""); + const proxyHost = proxy.hostname || proxy.host; + options.hostname = proxyHost; + options.host = proxyHost; + options.port = proxy.port; + options.path = location; + if (proxy.protocol) { + options.protocol = proxy.protocol.includes(":") ? proxy.protocol : `${proxy.protocol}:`; } - throw error; } + options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { + setProxy(redirectOptions, configProxy, redirectOptions.href); + }; } - -// node_modules/viem/_esm/actions/public/verifyMessage.js -async function verifyMessage(client, { address, message, factory, factoryData, signature, ...callRequest }) { - const hash2 = hashMessage(message); - return verifyHash(client, { - address, - factory, - factoryData, - hash: hash2, - signature, - ...callRequest +var isHttpAdapterSupported = typeof process !== "undefined" && utils_default.kindOf(process) === "process"; +var wrapAsync = (asyncExecutor) => { + return new Promise((resolve, reject) => { + let onDone; + let isDone; + const done = (value, isRejected) => { + if (isDone) return; + isDone = true; + onDone && onDone(value, isRejected); + }; + const _resolve = (value) => { + done(value); + resolve(value); + }; + const _reject = (reason) => { + done(reason, true); + reject(reason); + }; + asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject); }); -} - -// node_modules/viem/_esm/actions/public/verifyTypedData.js -async function verifyTypedData(client, parameters) { - const { address, factory, factoryData, signature, message, primaryType, types, domain, ...callRequest } = parameters; - const hash2 = hashTypedData({ message, primaryType, types, domain }); - return verifyHash(client, { +}; +var resolveFamily = ({ address, family }) => { + if (!utils_default.isString(address)) { + throw TypeError("address must be a string"); + } + return { address, - factory, - factoryData, - hash: hash2, - signature, - ...callRequest - }); -} - -// node_modules/viem/_esm/actions/public/waitForTransactionReceipt.js -init_transaction(); -init_withResolvers(); -init_stringify(); - -// node_modules/viem/_esm/actions/public/watchBlockNumber.js -init_fromHex(); -init_stringify(); -function watchBlockNumber(client, { emitOnBegin = false, emitMissed = false, onBlockNumber, onError, poll: poll_, pollingInterval = client.pollingInterval }) { - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (client.transport.type === "webSocket") - return false; - if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") - return false; - return true; - })(); - let prevBlockNumber; - const pollBlockNumber = () => { - const observerId = stringify([ - "watchBlockNumber", - client.uid, - emitOnBegin, - emitMissed, - pollingInterval - ]); - return observe(observerId, { onBlockNumber, onError }, (emit) => poll(async () => { - try { - const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({ cacheTime: 0 }); - if (prevBlockNumber) { - if (blockNumber === prevBlockNumber) - return; - if (blockNumber - prevBlockNumber > 1 && emitMissed) { - for (let i = prevBlockNumber + 1n; i < blockNumber; i++) { - emit.onBlockNumber(i, prevBlockNumber); - prevBlockNumber = i; - } + family: family || (address.indexOf(".") < 0 ? 6 : 4) + }; +}; +var buildAddressEntry = (address, family) => resolveFamily(utils_default.isObject(address) ? address : { address, family }); +var http_default = isHttpAdapterSupported && function httpAdapter(config3) { + return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { + let { data, lookup, family } = config3; + const { responseType, responseEncoding } = config3; + const method = config3.method.toUpperCase(); + let isDone; + let rejected = false; + let req; + if (lookup) { + const _lookup = callbackify_default(lookup, (value) => utils_default.isArray(value) ? value : [value]); + lookup = (hostname, opt, cb) => { + _lookup(hostname, opt, (err, arg0, arg1) => { + if (err) { + return cb(err); } - } - if (!prevBlockNumber || blockNumber > prevBlockNumber) { - emit.onBlockNumber(blockNumber, prevBlockNumber); - prevBlockNumber = blockNumber; - } - } catch (err) { - emit.onError?.(err); + const addresses = utils_default.isArray(arg0) ? arg0.map((addr) => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; + opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); + }); + }; + } + const emitter = new EventEmitter2(); + const onFinished = () => { + if (config3.cancelToken) { + config3.cancelToken.unsubscribe(abort); + } + if (config3.signal) { + config3.signal.removeEventListener("abort", abort); + } + emitter.removeAllListeners(); + }; + onDone((value, isRejected) => { + isDone = true; + if (isRejected) { + rejected = true; + onFinished(); } - }, { - emitOnBegin, - interval: pollingInterval - })); - }; - const subscribeBlockNumber = () => { - const observerId = stringify([ - "watchBlockNumber", - client.uid, - emitOnBegin, - emitMissed - ]); - return observe(observerId, { onBlockNumber, onError }, (emit) => { - let active = true; - let unsubscribe = () => active = false; - (async () => { - try { - const transport = (() => { - if (client.transport.type === "fallback") { - const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); - if (!transport2) - return client.transport; - return transport2.value; - } - return client.transport; - })(); - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["newHeads"], - onData(data) { - if (!active) - return; - const blockNumber = hexToBigInt(data.result?.number); - emit.onBlockNumber(blockNumber, prevBlockNumber); - prevBlockNumber = blockNumber; - }, - onError(error) { - emit.onError?.(error); - } - }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError?.(err); - } - })(); - return () => unsubscribe(); }); - }; - return enablePolling ? pollBlockNumber() : subscribeBlockNumber(); -} - -// node_modules/viem/_esm/actions/public/waitForTransactionReceipt.js -async function waitForTransactionReceipt(client, { - confirmations = 1, - hash: hash2, - onReplaced, - pollingInterval = client.pollingInterval, - retryCount = 6, - retryDelay = ({ count }) => ~~(1 << count) * 200, - // exponential backoff - timeout = 18e4 -}) { - const observerId = stringify(["waitForTransactionReceipt", client.uid, hash2]); - let transaction; - let replacedTransaction; - let receipt; - let retrying = false; - const { promise, resolve, reject } = withResolvers(); - const timer = timeout ? setTimeout(() => reject(new WaitForTransactionReceiptTimeoutError({ hash: hash2 })), timeout) : void 0; - const _unobserve = observe(observerId, { onReplaced, resolve, reject }, (emit) => { - const _unwatch = getAction(client, watchBlockNumber, "watchBlockNumber")({ - emitMissed: true, - emitOnBegin: true, - poll: true, - pollingInterval, - async onBlockNumber(blockNumber_) { - const done = (fn2) => { - clearTimeout(timer); - _unwatch(); - fn2(); - _unobserve(); - }; - let blockNumber = blockNumber_; - if (retrying) - return; - try { - if (receipt) { - if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) - return; - done(() => emit.resolve(receipt)); - return; - } - if (!transaction) { - retrying = true; - await withRetry(async () => { - transaction = await getAction(client, getTransaction, "getTransaction")({ hash: hash2 }); - if (transaction.blockNumber) - blockNumber = transaction.blockNumber; - }, { - delay: retryDelay, - retryCount - }); - retrying = false; - } - receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ hash: hash2 }); - if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) - return; - done(() => emit.resolve(receipt)); - } catch (err) { - if (err instanceof TransactionNotFoundError || err instanceof TransactionReceiptNotFoundError) { - if (!transaction) { - retrying = false; - return; - } - try { - replacedTransaction = transaction; - retrying = true; - const block = await withRetry(() => getAction(client, getBlock, "getBlock")({ - blockNumber, - includeTransactions: true - }), { - delay: retryDelay, - retryCount, - shouldRetry: ({ error }) => error instanceof BlockNotFoundError - }); - retrying = false; - const replacementTransaction = block.transactions.find(({ from: from5, nonce }) => from5 === replacedTransaction.from && nonce === replacedTransaction.nonce); - if (!replacementTransaction) - return; - receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ - hash: replacementTransaction.hash - }); - if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) - return; - let reason = "replaced"; - if (replacementTransaction.to === replacedTransaction.to && replacementTransaction.value === replacedTransaction.value && replacementTransaction.input === replacedTransaction.input) { - reason = "repriced"; - } else if (replacementTransaction.from === replacementTransaction.to && replacementTransaction.value === 0n) { - reason = "cancelled"; - } - done(() => { - emit.onReplaced?.({ - reason, - replacedTransaction, - transaction: replacementTransaction, - transactionReceipt: receipt - }); - emit.resolve(receipt); - }); - } catch (err_) { - done(() => emit.reject(err_)); - } - } else { - done(() => emit.reject(err)); - } - } + function abort(reason) { + emitter.emit("abort", !reason || reason.type ? new CanceledError_default(null, config3, req) : reason); + } + emitter.once("abort", reject); + if (config3.cancelToken || config3.signal) { + config3.cancelToken && config3.cancelToken.subscribe(abort); + if (config3.signal) { + config3.signal.aborted ? abort() : config3.signal.addEventListener("abort", abort); } - }); - }); - return promise; -} - -// node_modules/viem/_esm/actions/public/watchBlocks.js -init_stringify(); -function watchBlocks(client, { blockTag = "latest", emitMissed = false, emitOnBegin = false, onBlock, onError, includeTransactions: includeTransactions_, poll: poll_, pollingInterval = client.pollingInterval }) { - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (client.transport.type === "webSocket") - return false; - if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") - return false; - return true; - })(); - const includeTransactions = includeTransactions_ ?? false; - let prevBlock; - const pollBlocks = () => { - const observerId = stringify([ - "watchBlocks", - client.uid, - blockTag, - emitMissed, - emitOnBegin, - includeTransactions, - pollingInterval - ]); - return observe(observerId, { onBlock, onError }, (emit) => poll(async () => { - try { - const block = await getAction(client, getBlock, "getBlock")({ - blockTag, - includeTransactions + } + const fullPath = buildFullPath(config3.baseURL, config3.url, config3.allowAbsoluteUrls); + const parsed = new URL(fullPath, platform_default.hasBrowserEnv ? platform_default.origin : void 0); + const protocol = parsed.protocol || supportedProtocols[0]; + if (protocol === "data:") { + let convertedData; + if (method !== "GET") { + return settle(resolve, reject, { + status: 405, + statusText: "method not allowed", + headers: {}, + config: config3 }); - if (block.number && prevBlock?.number) { - if (block.number === prevBlock.number) - return; - if (block.number - prevBlock.number > 1 && emitMissed) { - for (let i = prevBlock?.number + 1n; i < block.number; i++) { - const block2 = await getAction(client, getBlock, "getBlock")({ - blockNumber: i, - includeTransactions - }); - emit.onBlock(block2, prevBlock); - prevBlock = block2; - } - } - } - if ( - // If no previous block exists, emit. - !prevBlock?.number || // If the block tag is "pending" with no block number, emit. - blockTag === "pending" && !block?.number || // If the next block number is greater than the previous block number, emit. - // We don't want to emit blocks in the past. - block.number && block.number > prevBlock.number - ) { - emit.onBlock(block, prevBlock); - prevBlock = block; - } - } catch (err) { - emit.onError?.(err); } - }, { - emitOnBegin, - interval: pollingInterval - })); - }; - const subscribeBlocks = () => { - let active = true; - let emitFetched = true; - let unsubscribe = () => active = false; - (async () => { try { - if (emitOnBegin) { - getAction(client, getBlock, "getBlock")({ - blockTag, - includeTransactions - }).then((block) => { - if (!active) - return; - if (!emitFetched) - return; - onBlock(block, void 0); - emitFetched = false; - }); - } - const transport = (() => { - if (client.transport.type === "fallback") { - const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); - if (!transport2) - return client.transport; - return transport2.value; - } - return client.transport; - })(); - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["newHeads"], - async onData(data) { - if (!active) - return; - const block = await getAction(client, getBlock, "getBlock")({ - blockNumber: data.blockNumber, - includeTransactions - }).catch(() => { - }); - if (!active) - return; - onBlock(block, prevBlock); - emitFetched = false; - prevBlock = block; - }, - onError(error) { - onError?.(error); - } + convertedData = fromDataURI(config3.url, responseType === "blob", { + Blob: config3.env && config3.env.Blob }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); } catch (err) { - onError?.(err); + throw AxiosError_default.from(err, AxiosError_default.ERR_BAD_REQUEST, config3); } - })(); - return () => unsubscribe(); - }; - return enablePolling ? pollBlocks() : subscribeBlocks(); -} - -// node_modules/viem/_esm/actions/public/watchEvent.js -init_stringify(); -init_abi(); -init_rpc(); -function watchEvent(client, { address, args, batch = true, event, events, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ }) { - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (typeof fromBlock === "bigint") - return true; - if (client.transport.type === "webSocket") - return false; - if (client.transport.type === "fallback" && client.transport.transports[0].config.type === "webSocket") - return false; - return true; - })(); - const strict = strict_ ?? false; - const pollEvent = () => { - const observerId = stringify([ - "watchEvent", - address, - args, - batch, - client.uid, - event, - pollingInterval, - fromBlock - ]); - return observe(observerId, { onLogs, onError }, (emit) => { - let previousBlockNumber; - if (fromBlock !== void 0) - previousBlockNumber = fromBlock - 1n; - let filter2; - let initialized = false; - const unwatch = poll(async () => { - if (!initialized) { - try { - filter2 = await getAction(client, createEventFilter, "createEventFilter")({ - address, - args, - event, - events, - strict, - fromBlock - }); - } catch { - } - initialized = true; - return; + if (responseType === "text") { + convertedData = convertedData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === "utf8") { + convertedData = utils_default.stripBOM(convertedData); } + } else if (responseType === "stream") { + convertedData = stream3.Readable.from(convertedData); + } + return settle(resolve, reject, { + data: convertedData, + status: 200, + statusText: "OK", + headers: new AxiosHeaders_default(), + config: config3 + }); + } + if (supportedProtocols.indexOf(protocol) === -1) { + return reject(new AxiosError_default( + "Unsupported protocol " + protocol, + AxiosError_default.ERR_BAD_REQUEST, + config3 + )); + } + const headers = AxiosHeaders_default.from(config3.headers).normalize(); + headers.set("User-Agent", "axios/" + VERSION, false); + const { onUploadProgress, onDownloadProgress } = config3; + const maxRate = config3.maxRate; + let maxUploadRate = void 0; + let maxDownloadRate = void 0; + if (utils_default.isSpecCompliantForm(data)) { + const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); + data = formDataToStream_default(data, (formHeaders) => { + headers.set(formHeaders); + }, { + tag: `axios-${VERSION}-boundary`, + boundary: userBoundary && userBoundary[1] || void 0 + }); + } else if (utils_default.isFormData(data) && utils_default.isFunction(data.getHeaders)) { + headers.set(data.getHeaders()); + if (!headers.hasContentLength()) { try { - let logs; - if (filter2) { - logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter: filter2 }); - } else { - const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({}); - if (previousBlockNumber && previousBlockNumber !== blockNumber) { - logs = await getAction(client, getLogs, "getLogs")({ - address, - args, - event, - events, - fromBlock: previousBlockNumber + 1n, - toBlock: blockNumber - }); - } else { - logs = []; + const knownLength = await util2.promisify(data.getLength).call(data); + Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); + } catch (e) { + } + } + } else if (utils_default.isBlob(data) || utils_default.isFile(data)) { + data.size && headers.setContentType(data.type || "application/octet-stream"); + headers.setContentLength(data.size || 0); + data = stream3.Readable.from(readBlob_default(data)); + } else if (data && !utils_default.isStream(data)) { + if (Buffer.isBuffer(data)) { + } else if (utils_default.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils_default.isString(data)) { + data = Buffer.from(data, "utf-8"); + } else { + return reject(new AxiosError_default( + "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream", + AxiosError_default.ERR_BAD_REQUEST, + config3 + )); + } + headers.setContentLength(data.length, false); + if (config3.maxBodyLength > -1 && data.length > config3.maxBodyLength) { + return reject(new AxiosError_default( + "Request body larger than maxBodyLength limit", + AxiosError_default.ERR_BAD_REQUEST, + config3 + )); + } + } + const contentLength = utils_default.toFiniteNumber(headers.getContentLength()); + if (utils_default.isArray(maxRate)) { + maxUploadRate = maxRate[0]; + maxDownloadRate = maxRate[1]; + } else { + maxUploadRate = maxDownloadRate = maxRate; + } + if (data && (onUploadProgress || maxUploadRate)) { + if (!utils_default.isStream(data)) { + data = stream3.Readable.from(data, { objectMode: false }); + } + data = stream3.pipeline([data, new AxiosTransformStream_default({ + maxRate: utils_default.toFiniteNumber(maxUploadRate) + })], utils_default.noop); + onUploadProgress && data.on("progress", flushOnFinish( + data, + progressEventDecorator( + contentLength, + progressEventReducer(asyncDecorator(onUploadProgress), false, 3) + ) + )); + } + let auth = void 0; + if (config3.auth) { + const username = config3.auth.username || ""; + const password = config3.auth.password || ""; + auth = username + ":" + password; + } + if (!auth && parsed.username) { + const urlUsername = parsed.username; + const urlPassword = parsed.password; + auth = urlUsername + ":" + urlPassword; + } + auth && headers.delete("authorization"); + let path; + try { + path = buildURL( + parsed.pathname + parsed.search, + config3.params, + config3.paramsSerializer + ).replace(/^\?/, ""); + } catch (err) { + const customErr = new Error(err.message); + customErr.config = config3; + customErr.url = config3.url; + customErr.exists = true; + return reject(customErr); + } + headers.set( + "Accept-Encoding", + "gzip, compress, deflate" + (isBrotliSupported ? ", br" : ""), + false + ); + const options = { + path, + method, + headers: headers.toJSON(), + agents: { http: config3.httpAgent, https: config3.httpsAgent }, + auth, + protocol, + family, + beforeRedirect: dispatchBeforeRedirect, + beforeRedirects: {} + }; + !utils_default.isUndefined(lookup) && (options.lookup = lookup); + if (config3.socketPath) { + options.socketPath = config3.socketPath; + } else { + options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; + options.port = parsed.port; + setProxy(options, config3.proxy, protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options.path); + } + let transport; + const isHttpsRequest = isHttps.test(options.protocol); + options.agent = isHttpsRequest ? config3.httpsAgent : config3.httpAgent; + if (config3.transport) { + transport = config3.transport; + } else if (config3.maxRedirects === 0) { + transport = isHttpsRequest ? https : http2; + } else { + if (config3.maxRedirects) { + options.maxRedirects = config3.maxRedirects; + } + if (config3.beforeRedirect) { + options.beforeRedirects.config = config3.beforeRedirect; + } + transport = isHttpsRequest ? httpsFollow : httpFollow; + } + if (config3.maxBodyLength > -1) { + options.maxBodyLength = config3.maxBodyLength; + } else { + options.maxBodyLength = Infinity; + } + if (config3.insecureHTTPParser) { + options.insecureHTTPParser = config3.insecureHTTPParser; + } + req = transport.request(options, function handleResponse(res) { + if (req.destroyed) return; + const streams = [res]; + const responseLength = +res.headers["content-length"]; + if (onDownloadProgress || maxDownloadRate) { + const transformStream = new AxiosTransformStream_default({ + maxRate: utils_default.toFiniteNumber(maxDownloadRate) + }); + onDownloadProgress && transformStream.on("progress", flushOnFinish( + transformStream, + progressEventDecorator( + responseLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) + ) + )); + streams.push(transformStream); + } + let responseStream = res; + const lastRequest = res.req || req; + if (config3.decompress !== false && res.headers["content-encoding"]) { + if (method === "HEAD" || res.statusCode === 204) { + delete res.headers["content-encoding"]; + } + switch ((res.headers["content-encoding"] || "").toLowerCase()) { + /*eslint default-case:0*/ + case "gzip": + case "x-gzip": + case "compress": + case "x-compress": + streams.push(zlib.createUnzip(zlibOptions)); + delete res.headers["content-encoding"]; + break; + case "deflate": + streams.push(new ZlibHeaderTransformStream_default()); + streams.push(zlib.createUnzip(zlibOptions)); + delete res.headers["content-encoding"]; + break; + case "br": + if (isBrotliSupported) { + streams.push(zlib.createBrotliDecompress(brotliOptions)); + delete res.headers["content-encoding"]; } - previousBlockNumber = blockNumber; - } - if (logs.length === 0) - return; - if (batch) - emit.onLogs(logs); - else - for (const log of logs) - emit.onLogs([log]); - } catch (err) { - if (filter2 && err instanceof InvalidInputRpcError) - initialized = false; - emit.onError?.(err); } - }, { - emitOnBegin: true, - interval: pollingInterval + } + responseStream = streams.length > 1 ? stream3.pipeline(streams, utils_default.noop) : streams[0]; + const offListeners = stream3.finished(responseStream, () => { + offListeners(); + onFinished(); }); - return async () => { - if (filter2) - await getAction(client, uninstallFilter, "uninstallFilter")({ filter: filter2 }); - unwatch(); + const response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: new AxiosHeaders_default(res.headers), + config: config3, + request: lastRequest }; - }); - }; - const subscribeEvent = () => { - let active = true; - let unsubscribe = () => active = false; - (async () => { - try { - const transport = (() => { - if (client.transport.type === "fallback") { - const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket"); - if (!transport2) - return client.transport; - return transport2.value; + if (responseType === "stream") { + response.data = responseStream; + settle(resolve, reject, response); + } else { + const responseBuffer = []; + let totalResponseBytes = 0; + responseStream.on("data", function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; + if (config3.maxContentLength > -1 && totalResponseBytes > config3.maxContentLength) { + rejected = true; + responseStream.destroy(); + reject(new AxiosError_default( + "maxContentLength size of " + config3.maxContentLength + " exceeded", + AxiosError_default.ERR_BAD_RESPONSE, + config3, + lastRequest + )); } - return client.transport; - })(); - const events_ = events ?? (event ? [event] : void 0); - let topics = []; - if (events_) { - const encoded = events_.flatMap((event2) => encodeEventTopics({ - abi: [event2], - eventName: event2.name, - args - })); - topics = [encoded]; - if (event) - topics = topics[0]; - } - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["logs", { address, topics }], - onData(data) { - if (!active) - return; - const log = data.result; - try { - const { eventName, args: args2 } = decodeEventLog({ - abi: events_ ?? [], - data: log.data, - topics: log.topics, - strict - }); - const formatted = formatLog(log, { args: args2, eventName }); - onLogs([formatted]); - } catch (err) { - let eventName; - let isUnnamed; - if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { - if (strict_) - return; - eventName = err.abiItem.name; - isUnnamed = err.abiItem.inputs?.some((x2) => !("name" in x2 && x2.name)); + }); + responseStream.on("aborted", function handlerStreamAborted() { + if (rejected) { + return; + } + const err = new AxiosError_default( + "stream has been aborted", + AxiosError_default.ERR_BAD_RESPONSE, + config3, + lastRequest + ); + responseStream.destroy(err); + reject(err); + }); + responseStream.on("error", function handleStreamError(err) { + if (req.destroyed) return; + reject(AxiosError_default.from(err, null, config3, lastRequest)); + }); + responseStream.on("end", function handleStreamEnd() { + try { + let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (responseType !== "arraybuffer") { + responseData = responseData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === "utf8") { + responseData = utils_default.stripBOM(responseData); } - const formatted = formatLog(log, { - args: isUnnamed ? [] : {}, - eventName - }); - onLogs([formatted]); } - }, - onError(error) { - onError?.(error); + response.data = responseData; + } catch (err) { + return reject(AxiosError_default.from(err, null, config3, response.request, response)); } + settle(resolve, reject, response); }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError?.(err); } - })(); - return () => unsubscribe(); + emitter.once("abort", (err) => { + if (!responseStream.destroyed) { + responseStream.emit("error", err); + responseStream.destroy(); + } + }); + }); + emitter.once("abort", (err) => { + reject(err); + req.destroy(err); + }); + req.on("error", function handleRequestError(err) { + reject(AxiosError_default.from(err, null, config3, req)); + }); + req.on("socket", function handleRequestSocket(socket) { + socket.setKeepAlive(true, 1e3 * 60); + }); + if (config3.timeout) { + const timeout = parseInt(config3.timeout, 10); + if (Number.isNaN(timeout)) { + reject(new AxiosError_default( + "error trying to parse `config.timeout` to int", + AxiosError_default.ERR_BAD_OPTION_VALUE, + config3, + req + )); + return; + } + req.setTimeout(timeout, function handleRequestTimeout() { + if (isDone) return; + let timeoutErrorMessage = config3.timeout ? "timeout of " + config3.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = config3.transitional || transitional_default; + if (config3.timeoutErrorMessage) { + timeoutErrorMessage = config3.timeoutErrorMessage; + } + reject(new AxiosError_default( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, + config3, + req + )); + abort(); + }); + } + if (utils_default.isStream(data)) { + let ended = false; + let errored = false; + data.on("end", () => { + ended = true; + }); + data.once("error", (err) => { + errored = true; + req.destroy(err); + }); + data.on("close", () => { + if (!ended && !errored) { + abort(new CanceledError_default("Request stream has been aborted", config3, req)); + } + }); + data.pipe(req); + } else { + req.end(data); + } + }); +}; + +// node_modules/axios/lib/helpers/isURLSameOrigin.js +var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url2) => { + url2 = new URL(url2, platform_default.origin); + return origin2.protocol === url2.protocol && origin2.host === url2.host && (isMSIE || origin2.port === url2.port); +})( + new URL(platform_default.origin), + platform_default.navigator && /(msie|trident)/i.test(platform_default.navigator.userAgent) +) : () => true; + +// node_modules/axios/lib/helpers/cookies.js +var cookies_default = platform_default.hasStandardBrowserEnv ? ( + // Standard browser envs support document.cookie + { + write(name, value, expires, path, domain, secure) { + const cookie = [name + "=" + encodeURIComponent(value)]; + utils_default.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString()); + utils_default.isString(path) && cookie.push("path=" + path); + utils_default.isString(domain) && cookie.push("domain=" + domain); + secure === true && cookie.push("secure"); + document.cookie = cookie.join("; "); + }, + read(name) { + const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)")); + return match ? decodeURIComponent(match[3]) : null; + }, + remove(name) { + this.write(name, "", Date.now() - 864e5); + } + } +) : ( + // Non-standard browser env (web workers, react-native) lack needed support. + { + write() { + }, + read() { + return null; + }, + remove() { + } + } +); + +// node_modules/axios/lib/core/mergeConfig.js +var headersToObject = (thing) => thing instanceof AxiosHeaders_default ? { ...thing } : thing; +function mergeConfig(config1, config22) { + config22 = config22 || {}; + const config3 = {}; + function getMergedValue(target, source, prop, caseless) { + if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) { + return utils_default.merge.call({ caseless }, target, source); + } else if (utils_default.isPlainObject(source)) { + return utils_default.merge({}, source); + } else if (utils_default.isArray(source)) { + return source.slice(); + } + return source; + } + function mergeDeepProperties(a, b2, prop, caseless) { + if (!utils_default.isUndefined(b2)) { + return getMergedValue(a, b2, prop, caseless); + } else if (!utils_default.isUndefined(a)) { + return getMergedValue(void 0, a, prop, caseless); + } + } + function valueFromConfig2(a, b2) { + if (!utils_default.isUndefined(b2)) { + return getMergedValue(void 0, b2); + } + } + function defaultToConfig2(a, b2) { + if (!utils_default.isUndefined(b2)) { + return getMergedValue(void 0, b2); + } else if (!utils_default.isUndefined(a)) { + return getMergedValue(void 0, a); + } + } + function mergeDirectKeys(a, b2, prop) { + if (prop in config22) { + return getMergedValue(a, b2); + } else if (prop in config1) { + return getMergedValue(void 0, a); + } + } + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + withXSRFToken: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b2, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b2), prop, true) }; - return enablePolling ? pollEvent() : subscribeEvent(); + utils_default.forEach(Object.keys(Object.assign({}, config1, config22)), function computeConfigValue(prop) { + const merge2 = mergeMap[prop] || mergeDeepProperties; + const configValue = merge2(config1[prop], config22[prop], prop); + utils_default.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config3[prop] = configValue); + }); + return config3; } -// node_modules/viem/_esm/actions/public/watchPendingTransactions.js -init_stringify(); -function watchPendingTransactions(client, { batch = true, onError, onTransactions, poll: poll_, pollingInterval = client.pollingInterval }) { - const enablePolling = typeof poll_ !== "undefined" ? poll_ : client.transport.type !== "webSocket"; - const pollPendingTransactions = () => { - const observerId = stringify([ - "watchPendingTransactions", - client.uid, - batch, - pollingInterval - ]); - return observe(observerId, { onTransactions, onError }, (emit) => { - let filter2; - const unwatch = poll(async () => { - try { - if (!filter2) { - try { - filter2 = await getAction(client, createPendingTransactionFilter, "createPendingTransactionFilter")({}); - return; - } catch (err) { - unwatch(); - throw err; - } - } - const hashes = await getAction(client, getFilterChanges, "getFilterChanges")({ filter: filter2 }); - if (hashes.length === 0) - return; - if (batch) - emit.onTransactions(hashes); - else - for (const hash2 of hashes) - emit.onTransactions([hash2]); - } catch (err) { - emit.onError?.(err); +// node_modules/axios/lib/helpers/resolveConfig.js +var resolveConfig_default = (config3) => { + const newConfig = mergeConfig({}, config3); + let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; + newConfig.headers = headers = AxiosHeaders_default.from(headers); + newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config3.params, config3.paramsSerializer); + if (auth) { + headers.set( + "Authorization", + "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : "")) + ); + } + let contentType; + if (utils_default.isFormData(data)) { + if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv) { + headers.setContentType(void 0); + } else if ((contentType = headers.getContentType()) !== false) { + const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : []; + headers.setContentType([type || "multipart/form-data", ...tokens].join("; ")); + } + } + if (platform_default.hasStandardBrowserEnv) { + withXSRFToken && utils_default.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); + if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin_default(newConfig.url)) { + const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies_default.read(xsrfCookieName); + if (xsrfValue) { + headers.set(xsrfHeaderName, xsrfValue); + } + } + } + return newConfig; +}; + +// node_modules/axios/lib/adapters/xhr.js +var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; +var xhr_default = isXHRAdapterSupported && function(config3) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + const _config = resolveConfig_default(config3); + let requestData = _config.data; + const requestHeaders = AxiosHeaders_default.from(_config.headers).normalize(); + let { responseType, onUploadProgress, onDownloadProgress } = _config; + let onCanceled; + let uploadThrottled, downloadThrottled; + let flushUpload, flushDownload; + function done() { + flushUpload && flushUpload(); + flushDownload && flushDownload(); + _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + _config.signal && _config.signal.removeEventListener("abort", onCanceled); + } + let request = new XMLHttpRequest(); + request.open(_config.method.toUpperCase(), _config.url, true); + request.timeout = _config.timeout; + function onloadend() { + if (!request) { + return; + } + const responseHeaders = AxiosHeaders_default.from( + "getAllResponseHeaders" in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config3, + request + }; + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + request = null; + } + if ("onloadend" in request) { + request.onloadend = onloadend; + } else { + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; } - }, { - emitOnBegin: true, - interval: pollingInterval + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { + return; + } + setTimeout(onloadend); + }; + } + request.onabort = function handleAbort() { + if (!request) { + return; + } + reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config3, request)); + request = null; + }; + request.onerror = function handleError() { + reject(new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config3, request)); + request = null; + }; + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded"; + const transitional2 = _config.transitional || transitional_default; + if (_config.timeoutErrorMessage) { + timeoutErrorMessage = _config.timeoutErrorMessage; + } + reject(new AxiosError_default( + timeoutErrorMessage, + transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, + config3, + request + )); + request = null; + }; + requestData === void 0 && requestHeaders.setContentType(null); + if ("setRequestHeader" in request) { + utils_default.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); }); - return async () => { - if (filter2) - await getAction(client, uninstallFilter, "uninstallFilter")({ filter: filter2 }); - unwatch(); + } + if (!utils_default.isUndefined(_config.withCredentials)) { + request.withCredentials = !!_config.withCredentials; + } + if (responseType && responseType !== "json") { + request.responseType = _config.responseType; + } + if (onDownloadProgress) { + [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true); + request.addEventListener("progress", downloadThrottled); + } + if (onUploadProgress && request.upload) { + [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress); + request.upload.addEventListener("progress", uploadThrottled); + request.upload.addEventListener("loadend", flushUpload); + } + if (_config.cancelToken || _config.signal) { + onCanceled = (cancel) => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError_default(null, config3, request) : cancel); + request.abort(); + request = null; }; - }); - }; - const subscribePendingTransactions = () => { - let active = true; - let unsubscribe = () => active = false; - (async () => { + _config.cancelToken && _config.cancelToken.subscribe(onCanceled); + if (_config.signal) { + _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled); + } + } + const protocol = parseProtocol(_config.url); + if (protocol && platform_default.protocols.indexOf(protocol) === -1) { + reject(new AxiosError_default("Unsupported protocol " + protocol + ":", AxiosError_default.ERR_BAD_REQUEST, config3)); + return; + } + request.send(requestData || null); + }); +}; + +// node_modules/axios/lib/helpers/composeSignals.js +var composeSignals = (signals, timeout) => { + const { length } = signals = signals ? signals.filter(Boolean) : []; + if (timeout || length) { + let controller = new AbortController(); + let aborted; + const onabort = function(reason) { + if (!aborted) { + aborted = true; + unsubscribe(); + const err = reason instanceof Error ? reason : this.reason; + controller.abort(err instanceof AxiosError_default ? err : new CanceledError_default(err instanceof Error ? err.message : err)); + } + }; + let timer = timeout && setTimeout(() => { + timer = null; + onabort(new AxiosError_default(`timeout ${timeout} of ms exceeded`, AxiosError_default.ETIMEDOUT)); + }, timeout); + const unsubscribe = () => { + if (signals) { + timer && clearTimeout(timer); + timer = null; + signals.forEach((signal2) => { + signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort); + }); + signals = null; + } + }; + signals.forEach((signal2) => signal2.addEventListener("abort", onabort)); + const { signal } = controller; + signal.unsubscribe = () => utils_default.asap(unsubscribe); + return signal; + } +}; +var composeSignals_default = composeSignals; + +// node_modules/axios/lib/helpers/trackStream.js +var streamChunk = function* (chunk, chunkSize) { + let len = chunk.byteLength; + if (!chunkSize || len < chunkSize) { + yield chunk; + return; + } + let pos = 0; + let end; + while (pos < len) { + end = pos + chunkSize; + yield chunk.slice(pos, end); + pos = end; + } +}; +var readBytes = async function* (iterable, chunkSize) { + for await (const chunk of readStream(iterable)) { + yield* streamChunk(chunk, chunkSize); + } +}; +var readStream = async function* (stream4) { + if (stream4[Symbol.asyncIterator]) { + yield* stream4; + return; + } + const reader = stream4.getReader(); + try { + for (; ; ) { + const { done, value } = await reader.read(); + if (done) { + break; + } + yield value; + } + } finally { + await reader.cancel(); + } +}; +var trackStream = (stream4, chunkSize, onProgress, onFinish) => { + const iterator2 = readBytes(stream4, chunkSize); + let bytes = 0; + let done; + let _onFinish = (e) => { + if (!done) { + done = true; + onFinish && onFinish(e); + } + }; + return new ReadableStream({ + async pull(controller) { try { - const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({ - params: ["newPendingTransactions"], - onData(data) { - if (!active) - return; - const transaction = data.result; - onTransactions([transaction]); - }, - onError(error) { - onError?.(error); - } - }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); + const { done: done2, value } = await iterator2.next(); + if (done2) { + _onFinish(); + controller.close(); + return; + } + let len = value.byteLength; + if (onProgress) { + let loadedBytes = bytes += len; + onProgress(loadedBytes); + } + controller.enqueue(new Uint8Array(value)); } catch (err) { - onError?.(err); + _onFinish(err); + throw err; } - })(); - return () => unsubscribe(); - }; - return enablePolling ? pollPendingTransactions() : subscribePendingTransactions(); -} - -// node_modules/viem/_esm/utils/siwe/parseSiweMessage.js -function parseSiweMessage(message) { - const { scheme, statement, ...prefix } = message.match(prefixRegex)?.groups ?? {}; - const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = message.match(suffixRegex)?.groups ?? {}; - const resources = message.split("Resources:")[1]?.split("\n- ").slice(1); - return { - ...prefix, - ...suffix, - ...chainId ? { chainId: Number(chainId) } : {}, - ...expirationTime ? { expirationTime: new Date(expirationTime) } : {}, - ...issuedAt ? { issuedAt: new Date(issuedAt) } : {}, - ...notBefore ? { notBefore: new Date(notBefore) } : {}, - ...requestId ? { requestId } : {}, - ...resources ? { resources } : {}, - ...scheme ? { scheme } : {}, - ...statement ? { statement } : {} - }; -} -var prefixRegex = /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/; -var suffixRegex = /(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/; + }, + cancel(reason) { + _onFinish(reason); + return iterator2.return(); + } + }, { + highWaterMark: 2 + }); +}; -// node_modules/viem/_esm/utils/siwe/validateSiweMessage.js -init_isAddressEqual(); -function validateSiweMessage(parameters) { - const { address, domain, message, nonce, scheme, time = /* @__PURE__ */ new Date() } = parameters; - if (domain && message.domain !== domain) - return false; - if (nonce && message.nonce !== nonce) - return false; - if (scheme && message.scheme !== scheme) - return false; - if (message.expirationTime && time >= message.expirationTime) - return false; - if (message.notBefore && time < message.notBefore) - return false; +// node_modules/axios/lib/adapters/fetch.js +var isFetchSupported = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function"; +var isReadableStreamSupported = isFetchSupported && typeof ReadableStream === "function"; +var encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder5) => (str) => encoder5.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Response(str).arrayBuffer())); +var test = (fn2, ...args) => { try { - if (!message.address) - return false; - if (address && !isAddressEqual(message.address, address)) - return false; - } catch { + return !!fn2(...args); + } catch (e) { return false; } - return true; -} - -// node_modules/viem/_esm/actions/siwe/verifySiweMessage.js -async function verifySiweMessage(client, parameters) { - const { address, domain, message, nonce, scheme, signature, time = /* @__PURE__ */ new Date(), ...callRequest } = parameters; - const parsed = parseSiweMessage(message); - if (!parsed.address) - return false; - const isValid = validateSiweMessage({ - address, - domain, - message: parsed, - nonce, - scheme, - time - }); - if (!isValid) - return false; - const hash2 = hashMessage(message); - return verifyHash(client, { - address: parsed.address, - hash: hash2, - signature, - ...callRequest - }); -} - -// node_modules/viem/_esm/clients/decorators/public.js -function publicActions(client) { - return { - call: (args) => call(client, args), - createAccessList: (args) => createAccessList(client, args), - createBlockFilter: () => createBlockFilter(client), - createContractEventFilter: (args) => createContractEventFilter(client, args), - createEventFilter: (args) => createEventFilter(client, args), - createPendingTransactionFilter: () => createPendingTransactionFilter(client), - estimateContractGas: (args) => estimateContractGas(client, args), - estimateGas: (args) => estimateGas(client, args), - getBalance: (args) => getBalance(client, args), - getBlobBaseFee: () => getBlobBaseFee(client), - getBlock: (args) => getBlock(client, args), - getBlockNumber: (args) => getBlockNumber(client, args), - getBlockTransactionCount: (args) => getBlockTransactionCount(client, args), - getBytecode: (args) => getCode(client, args), - getChainId: () => getChainId(client), - getCode: (args) => getCode(client, args), - getContractEvents: (args) => getContractEvents(client, args), - getEip712Domain: (args) => getEip712Domain(client, args), - getEnsAddress: (args) => getEnsAddress(client, args), - getEnsAvatar: (args) => getEnsAvatar(client, args), - getEnsName: (args) => getEnsName(client, args), - getEnsResolver: (args) => getEnsResolver(client, args), - getEnsText: (args) => getEnsText(client, args), - getFeeHistory: (args) => getFeeHistory(client, args), - estimateFeesPerGas: (args) => estimateFeesPerGas(client, args), - getFilterChanges: (args) => getFilterChanges(client, args), - getFilterLogs: (args) => getFilterLogs(client, args), - getGasPrice: () => getGasPrice(client), - getLogs: (args) => getLogs(client, args), - getProof: (args) => getProof(client, args), - estimateMaxPriorityFeePerGas: (args) => estimateMaxPriorityFeePerGas(client, args), - getStorageAt: (args) => getStorageAt(client, args), - getTransaction: (args) => getTransaction(client, args), - getTransactionConfirmations: (args) => getTransactionConfirmations(client, args), - getTransactionCount: (args) => getTransactionCount(client, args), - getTransactionReceipt: (args) => getTransactionReceipt(client, args), - multicall: (args) => multicall(client, args), - prepareTransactionRequest: (args) => prepareTransactionRequest(client, args), - readContract: (args) => readContract(client, args), - sendRawTransaction: (args) => sendRawTransaction(client, args), - simulate: (args) => simulateBlocks(client, args), - simulateBlocks: (args) => simulateBlocks(client, args), - simulateCalls: (args) => simulateCalls(client, args), - simulateContract: (args) => simulateContract(client, args), - verifyMessage: (args) => verifyMessage(client, args), - verifySiweMessage: (args) => verifySiweMessage(client, args), - verifyTypedData: (args) => verifyTypedData(client, args), - uninstallFilter: (args) => uninstallFilter(client, args), - waitForTransactionReceipt: (args) => waitForTransactionReceipt(client, args), - watchBlocks: (args) => watchBlocks(client, args), - watchBlockNumber: (args) => watchBlockNumber(client, args), - watchContractEvent: (args) => watchContractEvent(client, args), - watchEvent: (args) => watchEvent(client, args), - watchPendingTransactions: (args) => watchPendingTransactions(client, args) - }; -} - -// node_modules/viem/_esm/clients/createPublicClient.js -function createPublicClient(parameters) { - const { key = "public", name = "Public Client" } = parameters; - const client = createClient({ - ...parameters, - key, - name, - type: "publicClient" - }); - return client.extend(publicActions); -} - -// node_modules/viem/_esm/actions/wallet/deployContract.js -init_encodeDeployData(); -function deployContract(walletClient, parameters) { - const { abi: abi4, args, bytecode, ...request } = parameters; - const calldata = encodeDeployData({ abi: abi4, args, bytecode }); - return sendTransaction(walletClient, { - ...request, - ...request.authorizationList ? { to: null } : {}, - data: calldata - }); -} - -// node_modules/viem/_esm/actions/wallet/getAddresses.js -init_getAddress(); -async function getAddresses(client) { - if (client.account?.type === "local") - return [client.account.address]; - const addresses = await client.request({ method: "eth_accounts" }, { dedupe: true }); - return addresses.map((address) => checksumAddress(address)); -} - -// node_modules/viem/_esm/actions/wallet/getPermissions.js -async function getPermissions(client) { - const permissions = await client.request({ method: "wallet_getPermissions" }, { dedupe: true }); - return permissions; -} - -// node_modules/viem/_esm/actions/wallet/prepareAuthorization.js -init_parseAccount(); -init_isAddressEqual(); -async function prepareAuthorization(client, parameters) { - const { account: account_ = client.account, chainId, nonce } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/eip7702/prepareAuthorization" - }); - const account = parseAccount(account_); - const executor = (() => { - if (!parameters.executor) - return void 0; - if (parameters.executor === "self") - return parameters.executor; - return parseAccount(parameters.executor); - })(); - const authorization = { - address: parameters.contractAddress ?? parameters.address, - chainId, - nonce - }; - if (typeof authorization.chainId === "undefined") - authorization.chainId = client.chain?.id ?? await getAction(client, getChainId, "getChainId")({}); - if (typeof authorization.nonce === "undefined") { - authorization.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({ - address: account.address, - blockTag: "pending" +}; +var supportsRequestStream = isReadableStreamSupported && test(() => { + let duplexAccessed = false; + const hasContentType = new Request(platform_default.origin, { + body: new ReadableStream(), + method: "POST", + get duplex() { + duplexAccessed = true; + return "half"; + } + }).headers.has("Content-Type"); + return duplexAccessed && !hasContentType; +}); +var DEFAULT_CHUNK_SIZE = 64 * 1024; +var supportsResponseStream = isReadableStreamSupported && test(() => utils_default.isReadableStream(new Response("").body)); +var resolvers = { + stream: supportsResponseStream && ((res) => res.body) +}; +isFetchSupported && ((res) => { + ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => { + !resolvers[type] && (resolvers[type] = utils_default.isFunction(res[type]) ? (res2) => res2[type]() : (_, config3) => { + throw new AxiosError_default(`Response type '${type}' is not supported`, AxiosError_default.ERR_NOT_SUPPORT, config3); }); - if (executor === "self" || executor?.address && isAddressEqual(executor.address, account.address)) - authorization.nonce += 1; + }); +})(new Response()); +var getBodyLength = async (body) => { + if (body == null) { + return 0; } - return authorization; -} - -// node_modules/viem/_esm/actions/wallet/requestAddresses.js -init_getAddress(); -async function requestAddresses(client) { - const addresses = await client.request({ method: "eth_requestAccounts" }, { dedupe: true, retryCount: 0 }); - return addresses.map((address) => getAddress(address)); -} - -// node_modules/viem/_esm/actions/wallet/requestPermissions.js -async function requestPermissions(client, permissions) { - return client.request({ - method: "wallet_requestPermissions", - params: [permissions] - }, { retryCount: 0 }); -} - -// node_modules/viem/_esm/actions/wallet/signAuthorization.js -init_parseAccount(); -async function signAuthorization(client, parameters) { - const { account: account_ = client.account } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/eip7702/signAuthorization" + if (utils_default.isBlob(body)) { + return body.size; + } + if (utils_default.isSpecCompliantForm(body)) { + const _request = new Request(platform_default.origin, { + method: "POST", + body }); - const account = parseAccount(account_); - if (!account.signAuthorization) - throw new AccountTypeNotSupportedError({ - docsPath: "/docs/eip7702/signAuthorization", - metaMessages: [ - "The `signAuthorization` Action does not support JSON-RPC Accounts." - ], - type: account.type + return (await _request.arrayBuffer()).byteLength; + } + if (utils_default.isArrayBufferView(body) || utils_default.isArrayBuffer(body)) { + return body.byteLength; + } + if (utils_default.isURLSearchParams(body)) { + body = body + ""; + } + if (utils_default.isString(body)) { + return (await encodeText(body)).byteLength; + } +}; +var resolveBodyLength = async (headers, body) => { + const length = utils_default.toFiniteNumber(headers.getContentLength()); + return length == null ? getBodyLength(body) : length; +}; +var fetch_default = isFetchSupported && (async (config3) => { + let { + url: url2, + method, + data, + signal, + cancelToken, + timeout, + onDownloadProgress, + onUploadProgress, + responseType, + headers, + withCredentials = "same-origin", + fetchOptions + } = resolveConfig_default(config3); + responseType = responseType ? (responseType + "").toLowerCase() : "text"; + let composedSignal = composeSignals_default([signal, cancelToken && cancelToken.toAbortSignal()], timeout); + let request; + const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { + composedSignal.unsubscribe(); + }); + let requestContentLength; + try { + if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) { + let _request = new Request(url2, { + method: "POST", + body: data, + duplex: "half" + }); + let contentTypeHeader; + if (utils_default.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) { + headers.setContentType(contentTypeHeader); + } + if (_request.body) { + const [onProgress, flush] = progressEventDecorator( + requestContentLength, + progressEventReducer(asyncDecorator(onUploadProgress)) + ); + data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); + } + } + if (!utils_default.isString(withCredentials)) { + withCredentials = withCredentials ? "include" : "omit"; + } + const isCredentialsSupported = "credentials" in Request.prototype; + request = new Request(url2, { + ...fetchOptions, + signal: composedSignal, + method: method.toUpperCase(), + headers: headers.normalize().toJSON(), + body: data, + duplex: "half", + credentials: isCredentialsSupported ? withCredentials : void 0 }); - const authorization = await prepareAuthorization(client, parameters); - return account.signAuthorization(authorization); -} - -// node_modules/viem/_esm/actions/wallet/signMessage.js -init_parseAccount(); -init_toHex(); -async function signMessage(client, { account: account_ = client.account, message }) { - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/signMessage" + let response = await fetch(request); + const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response"); + if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) { + const options = {}; + ["status", "statusText", "headers"].forEach((prop) => { + options[prop] = response[prop]; + }); + const responseContentLength = utils_default.toFiniteNumber(response.headers.get("content-length")); + const [onProgress, flush] = onDownloadProgress && progressEventDecorator( + responseContentLength, + progressEventReducer(asyncDecorator(onDownloadProgress), true) + ) || []; + response = new Response( + trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { + flush && flush(); + unsubscribe && unsubscribe(); + }), + options + ); + } + responseType = responseType || "text"; + let responseData = await resolvers[utils_default.findKey(resolvers, responseType) || "text"](response, config3); + !isStreamResponse && unsubscribe && unsubscribe(); + return await new Promise((resolve, reject) => { + settle(resolve, reject, { + data: responseData, + headers: AxiosHeaders_default.from(response.headers), + status: response.status, + statusText: response.statusText, + config: config3, + request + }); }); - const account = parseAccount(account_); - if (account.signMessage) - return account.signMessage({ message }); - const message_ = (() => { - if (typeof message === "string") - return stringToHex(message); - if (message.raw instanceof Uint8Array) - return toHex(message.raw); - return message.raw; - })(); - return client.request({ - method: "personal_sign", - params: [message_, account.address] - }, { retryCount: 0 }); -} + } catch (err) { + unsubscribe && unsubscribe(); + if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config3, request), + { + cause: err.cause || err + } + ); + } + throw AxiosError_default.from(err, err && err.code, config3, request); + } +}); -// node_modules/viem/_esm/actions/wallet/signTransaction.js -init_parseAccount(); -init_toHex(); -init_transactionRequest(); -init_assertRequest(); -async function signTransaction(client, parameters) { - const { account: account_ = client.account, chain = client.chain, ...transaction } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/signTransaction" - }); - const account = parseAccount(account_); - assertRequest({ - account, - ...parameters - }); - const chainId = await getAction(client, getChainId, "getChainId")({}); - if (chain !== null) - assertCurrentChain({ - currentChainId: chainId, - chain - }); - const formatters = chain?.formatters || client.chain?.formatters; - const format = formatters?.transactionRequest?.format || formatTransactionRequest; - if (account.signTransaction) - return account.signTransaction({ - ...transaction, - chainId - }, { serializer: client.chain?.serializers?.transaction }); - return await client.request({ - method: "eth_signTransaction", - params: [ - { - ...format(transaction), - chainId: numberToHex(chainId), - from: account.address +// node_modules/axios/lib/adapters/adapters.js +var knownAdapters = { + http: http_default, + xhr: xhr_default, + fetch: fetch_default +}; +utils_default.forEach(knownAdapters, (fn2, value) => { + if (fn2) { + try { + Object.defineProperty(fn2, "name", { value }); + } catch (e) { + } + Object.defineProperty(fn2, "adapterName", { value }); + } +}); +var renderReason = (reason) => `- ${reason}`; +var isResolvedHandle = (adapter) => utils_default.isFunction(adapter) || adapter === null || adapter === false; +var adapters_default = { + getAdapter: (adapters) => { + adapters = utils_default.isArray(adapters) ? adapters : [adapters]; + const { length } = adapters; + let nameOrAdapter; + let adapter; + const rejectedReasons = {}; + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id2; + adapter = nameOrAdapter; + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id2 = String(nameOrAdapter)).toLowerCase()]; + if (adapter === void 0) { + throw new AxiosError_default(`Unknown adapter '${id2}'`); + } } - ] - }, { retryCount: 0 }); -} + if (adapter) { + break; + } + rejectedReasons[id2 || "#" + i] = adapter; + } + if (!adapter) { + const reasons = Object.entries(rejectedReasons).map( + ([id2, state]) => `adapter ${id2} ` + (state === false ? "is not supported by the environment" : "is not available in the build") + ); + let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"; + throw new AxiosError_default( + `There is no suitable adapter to dispatch the request ` + s, + "ERR_NOT_SUPPORT" + ); + } + return adapter; + }, + adapters: knownAdapters +}; -// node_modules/viem/_esm/actions/wallet/signTypedData.js -init_parseAccount(); -async function signTypedData(client, parameters) { - const { account: account_ = client.account, domain, message, primaryType } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/signTypedData" - }); - const account = parseAccount(account_); - const types = { - EIP712Domain: getTypesForEIP712Domain({ domain }), - ...parameters.types - }; - validateTypedData({ domain, message, primaryType, types }); - if (account.signTypedData) - return account.signTypedData({ domain, message, primaryType, types }); - const typedData = serializeTypedData({ domain, message, primaryType, types }); - return client.request({ - method: "eth_signTypedData_v4", - params: [account.address, typedData] - }, { retryCount: 0 }); +// node_modules/axios/lib/core/dispatchRequest.js +function throwIfCancellationRequested(config3) { + if (config3.cancelToken) { + config3.cancelToken.throwIfRequested(); + } + if (config3.signal && config3.signal.aborted) { + throw new CanceledError_default(null, config3); + } } - -// node_modules/viem/_esm/actions/wallet/switchChain.js -init_toHex(); -async function switchChain(client, { id: id2 }) { - await client.request({ - method: "wallet_switchEthereumChain", - params: [ - { - chainId: numberToHex(id2) +function dispatchRequest(config3) { + throwIfCancellationRequested(config3); + config3.headers = AxiosHeaders_default.from(config3.headers); + config3.data = transformData.call( + config3, + config3.transformRequest + ); + if (["post", "put", "patch"].indexOf(config3.method) !== -1) { + config3.headers.setContentType("application/x-www-form-urlencoded", false); + } + const adapter = adapters_default.getAdapter(config3.adapter || defaults_default.adapter); + return adapter(config3).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config3); + response.data = transformData.call( + config3, + config3.transformResponse, + response + ); + response.headers = AxiosHeaders_default.from(response.headers); + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config3); + if (reason && reason.response) { + reason.response.data = transformData.call( + config3, + config3.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders_default.from(reason.response.headers); } - ] - }, { retryCount: 0 }); -} - -// node_modules/viem/_esm/actions/wallet/watchAsset.js -async function watchAsset(client, params) { - const added = await client.request({ - method: "wallet_watchAsset", - params - }, { retryCount: 0 }); - return added; + } + return Promise.reject(reason); + }); } -// node_modules/viem/_esm/clients/decorators/wallet.js -function walletActions(client) { - return { - addChain: (args) => addChain(client, args), - deployContract: (args) => deployContract(client, args), - getAddresses: () => getAddresses(client), - getChainId: () => getChainId(client), - getPermissions: () => getPermissions(client), - prepareAuthorization: (args) => prepareAuthorization(client, args), - prepareTransactionRequest: (args) => prepareTransactionRequest(client, args), - requestAddresses: () => requestAddresses(client), - requestPermissions: (args) => requestPermissions(client, args), - sendRawTransaction: (args) => sendRawTransaction(client, args), - sendTransaction: (args) => sendTransaction(client, args), - signAuthorization: (args) => signAuthorization(client, args), - signMessage: (args) => signMessage(client, args), - signTransaction: (args) => signTransaction(client, args), - signTypedData: (args) => signTypedData(client, args), - switchChain: (args) => switchChain(client, args), - watchAsset: (args) => watchAsset(client, args), - writeContract: (args) => writeContract(client, args) +// node_modules/axios/lib/helpers/validator.js +var validators = {}; +["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => { + validators[type] = function validator(thing) { + return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type; }; +}); +var deprecatedWarnings = {}; +validators.transitional = function transitional(validator, version4, message) { + function formatMessage(opt, desc) { + return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); + } + return (value, opt, opts) => { + if (validator === false) { + throw new AxiosError_default( + formatMessage(opt, " has been removed" + (version4 ? " in " + version4 : "")), + AxiosError_default.ERR_DEPRECATED + ); + } + if (version4 && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + console.warn( + formatMessage( + opt, + " has been deprecated since v" + version4 + " and will be removed in the near future" + ) + ); + } + return validator ? validator(value, opt, opts) : true; + }; +}; +validators.spelling = function spelling(correctSpelling) { + return (value, opt) => { + console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); + return true; + }; +}; +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== "object") { + throw new AxiosError_default("options must be an object", AxiosError_default.ERR_BAD_OPTION_VALUE); + } + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === void 0 || validator(value, opt, options); + if (result !== true) { + throw new AxiosError_default("option " + opt + " must be " + result, AxiosError_default.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError_default("Unknown option " + opt, AxiosError_default.ERR_BAD_OPTION); + } + } } +var validator_default = { + assertOptions, + validators +}; -// node_modules/viem/_esm/clients/createWalletClient.js -function createWalletClient(parameters) { - const { key = "wallet", name = "Wallet Client", transport } = parameters; - const client = createClient({ - ...parameters, - key, - name, - transport, - type: "walletClient" - }); - return client.extend(walletActions); -} - -// node_modules/viem/_esm/index.js -init_abi(); -init_contract(); -init_rpc(); -init_node(); -init_request(); -init_transaction(); -init_decodeAbiParameters(); -init_encodeAbiParameters(); -init_getAbiItem(); -init_toBytes(); -init_formatUnits(); -init_isHex(); -init_keccak256(); - -// src/common/utils/callContract.ts -async function executeTransaction(publicClient, walletClient, params, nonceManager) { - const chainId = publicClient.chain.id; - const address = walletClient.account.address; - let txHash; - if (globalConfig.VIEM.SIMULATE_TX) { - const { request } = await publicClient.simulateContract(params); - txHash = await walletClient.writeContract({ request }); - } else { - const nonce = await nonceManager.consume({ - address, - chainId, - client: publicClient - }); - const paramsToSend = { - gas: globalConfig.TX_MANAGER.GAS_LIMIT.DEFAULT, - ...params, - nonce +// node_modules/axios/lib/core/Axios.js +var validators2 = validator_default.validators; +var Axios = class { + constructor(instanceConfig) { + this.defaults = instanceConfig || {}; + this.interceptors = { + request: new InterceptorManager_default(), + response: new InterceptorManager_default() }; - txHash = await walletClient.writeContract(paramsToSend); } - await publicClient.waitForTransactionReceipt({ - hash: txHash - }); - return txHash; -} -async function callContract(publicClient, walletClient, params) { - try { - const nonceManager = NonceManager.getInstance(); - const isRetryableError = async (error) => { - if (error instanceof ContractFunctionExecutionError && error.cause instanceof TransactionExecutionError && (error.cause.cause instanceof NonceTooHighError || error.cause.cause instanceof NonceTooLowError) || error instanceof TransactionNotFoundError || error instanceof WaitForTransactionReceiptTimeoutError) { - const chainId = publicClient.chain.id; - const address = walletClient.account.address; - nonceManager.reset({ chainId, address }); - return true; + /** + * Dispatch a request + * + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled + */ + async request(configOrUrl, config3) { + try { + return await this._request(configOrUrl, config3); + } catch (err) { + if (err instanceof Error) { + let dummy = {}; + Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error(); + const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : ""; + try { + if (!err.stack) { + err.stack = stack; + } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) { + err.stack += "\n" + stack; + } + } catch (e) { + } } - return false; - }; - return asyncRetry( - () => executeTransaction(publicClient, walletClient, params, nonceManager), - { - maxRetries: 20, - delayMs: 1e3, - isRetryableError + throw err; + } + } + _request(configOrUrl, config3) { + if (typeof configOrUrl === "string") { + config3 = config3 || {}; + config3.url = configOrUrl; + } else { + config3 = configOrUrl || {}; + } + config3 = mergeConfig(this.defaults, config3); + const { transitional: transitional2, paramsSerializer, headers } = config3; + if (transitional2 !== void 0) { + validator_default.assertOptions(transitional2, { + silentJSONParsing: validators2.transitional(validators2.boolean), + forcedJSONParsing: validators2.transitional(validators2.boolean), + clarifyTimeoutError: validators2.transitional(validators2.boolean) + }, false); + } + if (paramsSerializer != null) { + if (utils_default.isFunction(paramsSerializer)) { + config3.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator_default.assertOptions(paramsSerializer, { + encode: validators2.function, + serialize: validators2.function + }, true); } + } + if (config3.allowAbsoluteUrls !== void 0) { + } else if (this.defaults.allowAbsoluteUrls !== void 0) { + config3.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; + } else { + config3.allowAbsoluteUrls = true; + } + validator_default.assertOptions(config3, { + baseUrl: validators2.spelling("baseURL"), + withXsrfToken: validators2.spelling("withXSRFToken") + }, true); + config3.method = (config3.method || this.defaults.method || "get").toLowerCase(); + let contextHeaders = headers && utils_default.merge( + headers.common, + headers[config3.method] ); - } catch (error) { - throw new AppError("ContractCallError" /* ContractCallError */, error); + headers && utils_default.forEach( + ["delete", "get", "head", "post", "put", "patch", "common"], + (method) => { + delete headers[method]; + } + ); + config3.headers = AxiosHeaders_default.concat(contextHeaders, headers); + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config3) === false) { + return; + } + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + let promise; + let i = 0; + let len; + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), void 0]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + promise = Promise.resolve(config3); + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + return promise; + } + len = requestInterceptorChain.length; + let newConfig = config3; + i = 0; + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + i = 0; + len = responseInterceptorChain.length; + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + return promise; } -} + getUri(config3) { + config3 = mergeConfig(this.defaults, config3); + const fullPath = buildFullPath(config3.baseURL, config3.url, config3.allowAbsoluteUrls); + return buildURL(fullPath, config3.params, config3.paramsSerializer); + } +}; +utils_default.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) { + Axios.prototype[method] = function(url2, config3) { + return this.request(mergeConfig(config3 || {}, { + method, + url: url2, + data: (config3 || {}).data + })); + }; +}); +utils_default.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { + function generateHTTPMethod(isForm) { + return function httpMethod(url2, data, config3) { + return this.request(mergeConfig(config3 || {}, { + method, + headers: isForm ? { + "Content-Type": "multipart/form-data" + } : {}, + url: url2, + data + })); + }; + } + Axios.prototype[method] = generateHTTPMethod(); + Axios.prototype[method + "Form"] = generateHTTPMethod(true); +}); +var Axios_default = Axios; -// src/common/utils/checkGas.ts -var import_web_api = __toESM(require_dist4(), 1); -var SAFE_TXS_COUNT_FOR_OPERATOR_BALANCE = 15n; -async function notifyInSlack(message) { - try { - if (!globalConfig.NOTIFICATIONS.SLACK.MONITORING_SYSTEM_CHANNEL_ID || !globalConfig.NOTIFICATIONS.SLACK.BOT_TOKEN) { - return; +// node_modules/axios/lib/cancel/CancelToken.js +var CancelToken = class _CancelToken { + constructor(executor) { + if (typeof executor !== "function") { + throw new TypeError("executor must be a function."); } - const webClient = new import_web_api.WebClient(globalConfig.NOTIFICATIONS.SLACK.BOT_TOKEN); - const res = await webClient.chat.postMessage({ - channel: globalConfig.NOTIFICATIONS.SLACK.MONITORING_SYSTEM_CHANNEL_ID, - text: message + let resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; }); - if (!res.ok) { - console.error(`Failed to send message to slack: ${res.error}`); + const token = this; + this.promise.then((cancel) => { + if (!token._listeners) return; + let i = token._listeners.length; + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + this.promise.then = (onfulfilled) => { + let _resolve; + const promise = new Promise((resolve) => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + return promise; + }; + executor(function cancel(message, config3, request) { + if (token.reason) { + return; + } + token.reason = new CanceledError_default(message, config3, request); + resolvePromise(token.reason); + }); + } + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; } - } catch (error) { - console.error(JSON.stringify(error, null, 2)); } -} -async function getChainOperatorMinBalance(publicClient) { - const currentGasPrice = await publicClient.getGasPrice(); - const averageTxCostInWei = currentGasPrice * globalConfig.TX_MANAGER.GAS_LIMIT.DEFAULT; - return averageTxCostInWei * SAFE_TXS_COUNT_FOR_OPERATOR_BALANCE; -} -async function checkAndNotifyInsufficientGas() { - const operatorAddress = globalConfig.OPERATOR_ADDRESS; - const viemClientManager = ViemClientManager.getInstance(); - const networkManager = NetworkManager.getInstance(); - const logger = Logger.getInstance().getLogger("GasChecker"); - try { - const activeNetworks = networkManager.getActiveNetworks(); - if (activeNetworks.length === 0) { - logger.warn("No active networks found when checking gas balances"); + /** + * Subscribe to the cancel signal + */ + subscribe(listener) { + if (this.reason) { + listener(this.reason); return; } - const balancePromises = activeNetworks.map(async (network) => { - const { publicClient } = viemClientManager.getClients(network); - const [balance, operatorMinBalance] = await Promise.all([ - publicClient.getBalance({ - address: operatorAddress - }), - getChainOperatorMinBalance(publicClient) - ]); - return { network, balance, operatorMinBalance }; - }); - const chainsInfo = await Promise.all(balancePromises); - for (const chainInfo of chainsInfo) { - const { balance, operatorMinBalance, network } = chainInfo; - if (balance < operatorMinBalance) { - const message = `Insufficient gas on ${network.name} (chain ID: ${network.id}). Minimum required: ${formatUnits(operatorMinBalance, 18)}, actual: ${formatUnits(balance, 18)}`; - await notifyInSlack(message); - logger.info(message); - } + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; } - } catch (error) { - logger.error("Error checking gas balances:", error); } -} -async function checkGas() { - await checkAndNotifyInsufficientGas(); - setInterval(async () => { - await checkAndNotifyInsufficientGas(); - }, globalConfig.NOTIFICATIONS.INTERVAL); -} - -// src/common/utils/createViemChain.ts -function createViemChain(chainDefinition) { - return defineChain({ - id: chainDefinition.id, - name: chainDefinition.name, - nativeCurrency: { - decimals: 18, - name: "eth", - symbol: "eth" - }, - rpcUrls: { - default: { http: chainDefinition.rpcUrls } - }, - blockExplorers: chainDefinition.blockExplorer ? { - default: { - name: chainDefinition.blockExplorer.name, - url: chainDefinition.blockExplorer.url - } - } : void 0, - testnet: chainDefinition.isTestnet - }); -} - -// src/common/utils/customHttpTransport.ts -function createCustomHttpTransport(url2) { - const logger = Logger.getInstance().getLogger("ViemTransport"); - return (config3) => { - const transport = http2(url2, { - batch: true - })(config3); - return transport; - }; -} - -// src/common/utils/decoders/decodeCLFReport.ts -var clfReportSubmissionAbi = parseAbiParameters([ - "bytes32[3] reportContext", - "bytes report", - "bytes32[] rs", - "bytes32[] ss", - "bytes32 rawVs" -]); -var clfReportAbi = parseAbiParameters([ - "bytes32[] requestIds", - "bytes[] results", - "bytes[] errors", - "bytes[] onchainMetadata", - "bytes[] offchainMetadata" -]); -function decodeCLFReport(tx) { - const inputData = tx.input.slice(10); - const decodedData = decodeAbiParameters(clfReportSubmissionAbi, `0x${inputData}`); - const reportBytes = decodedData[1]; - const decodedReport = decodeAbiParameters(clfReportAbi, reportBytes); - const report = { - reportContext: decodedData[0], - report: { - requestIds: decodedReport[0], - results: decodedReport[1], - errors: decodedReport[2], - onchainMetadata: decodedReport[3], - offchainMetadata: decodedReport[4] - }, - rs: decodedData[2], - ss: decodedData[3], - rawVs: decodedData[4], - reportBytes - }; - return report; -} - -// src/common/utils/decoders/decodeMessageReportResult.ts -function decodeMessageReportResult(resultBytes) { - try { - const decodedClfResult = decodeAbiParameters( - [ - { - type: "tuple", - name: "reportConfig", - components: [ - { type: "uint8", name: "type" }, - { type: "uint8", name: "payloadVersion" }, - { type: "address", name: "requester" } - ] - }, - { type: "bytes", name: "payload" } - ], - resultBytes - ); - const decodedPayload = decodeAbiParameters( - [ - { - type: "tuple", - components: [ - { type: "bytes32", name: "messageId" }, - { type: "bytes32", name: "messageHashSum" }, - { type: "bytes", name: "messageSender" }, - { type: "uint24", name: "srcChainSelector" }, - { type: "uint24", name: "dstChainSelector" }, - { type: "uint256", name: "srcBlockNumber" }, - { - type: "tuple", - name: "dstChainData", - components: [ - { type: "address", name: "receiver" }, - { type: "uint256", name: "gasLimit" } - ] - }, - { type: "bytes[]", name: "allowedOperators" } - ] - } - ], - hexToBytes(decodedClfResult[1]) - ); - return { - reportConfig: decodedClfResult[0], - ...decodedPayload[0] + /** + * Unsubscribe from the cancel signal + */ + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index2 = this._listeners.indexOf(listener); + if (index2 !== -1) { + this._listeners.splice(index2, 1); + } + } + toAbortSignal() { + const controller = new AbortController(); + const abort = (err) => { + controller.abort(err); }; - } catch (error) { - console.error("Error decoding CLF message report response:", error); - throw new Error("Failed to decode CLF message report response"); + this.subscribe(abort); + controller.signal.unsubscribe = () => this.unsubscribe(abort); + return controller.signal; } -} - -// src/common/utils/fetchNetworkConfigs.ts -async function fetchNetworkConfigs() { - const httpClient = HttpClient.getQueueInstance(); - try { - const [mainnetSummary, testnetSummary] = await Promise.all([ - httpClient.get(globalConfig.URLS.V2_NETWORKS.MAINNET_SUMMARY), - httpClient.get(globalConfig.URLS.V2_NETWORKS.TESTNET_SUMMARY) - ]); - const mainnetDetailPromises = Object.keys(mainnetSummary).map(async (networkName) => { - const url2 = `${globalConfig.URLS.V2_NETWORKS.MAINNET_DETAIL_BASE}/${networkName}.json`; - const response = await httpClient.get(url2); - const details = await response; - return { networkName, details }; - }); - const testnetDetailPromises = Object.keys(testnetSummary).map(async (networkName) => { - const url2 = `${globalConfig.URLS.V2_NETWORKS.TESTNET_DETAIL_BASE}/${networkName}.json`; - const response = await httpClient.get(url2); - const details = await response; - return { networkName, details }; - }); - const mainnetDetails = await Promise.all(mainnetDetailPromises); - const testnetDetails = await Promise.all(testnetDetailPromises); - const processedMainnetNetworks = mainnetDetails.reduce((acc, { networkName, details }) => { - const chainDefinition = { - id: details.chainId, - name: details.name, - rpcUrls: details.rpcs, - blockExplorer: details.blockExplorers[0] ? { - name: details.blockExplorers[0].name, - url: details.blockExplorers[0].url - } : void 0, - isTestnet: false - }; - acc[networkName] = { - name: details.name, - chainId: details.chainId, - chainSelector: details.chainSelector.toString(), - viemChain: createViemChain(chainDefinition) - }; - return acc; - }, {}); - const processedTestnetNetworks = testnetDetails.reduce((acc, { networkName, details }) => { - const chainDefinition = { - id: details.chainId, - name: details.name, - rpcUrls: details.rpcs, - blockExplorer: details.blockExplorers[0] ? { - name: details.blockExplorers[0].name, - url: details.blockExplorers[0].url - } : void 0, - isTestnet: true - }; - acc[networkName] = { - name: details.name, - chainId: details.chainId, - chainSelector: details.chainSelector.toString(), - viemChain: createViemChain(chainDefinition) - }; - return acc; - }, {}); + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new _CancelToken(function executor(c) { + cancel = c; + }); return { - mainnetNetworks: processedMainnetNetworks, - testnetNetworks: processedTestnetNetworks + token, + cancel }; - } catch (error) { - console.error("Failed to fetch network configurations:", error); - return { mainnetNetworks: {}, testnetNetworks: {} }; } -} - -// src/common/utils/getEnvVar.ts -import process2 from "process"; -function getEnvVar(key) { - const value = process2.env[key]; - if (value === void 0 || value === "") throw new Error(`Missing environment variable ${key}`); - return value; -} +}; +var CancelToken_default = CancelToken; -// src/common/utils/getGranularLogLevels.ts -import process3 from "process"; -function getGranularLogLevels() { - const logLevels = {}; - const LOG_LEVEL_PREFIX = "LOG_LEVEL_"; - Object.keys(process3.env).forEach((key) => { - if (key.startsWith(LOG_LEVEL_PREFIX) && key !== "LOG_LEVEL_DEFAULT") { - const componentName = key.substring(LOG_LEVEL_PREFIX.length); - const level = process3.env[key]; - if (componentName && level) { - logLevels[componentName] = level; - console.log( - `[getGranularLogLevels] Component-specific log level: ${componentName}=${level}` - ); - } - } - }); - return logLevels; +// node_modules/axios/lib/helpers/spread.js +function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; } -// src/common/utils/getOptionalEnvVar.ts -function getOptionalEnvVar(key, defaultValue) { - const value = process.env[key]; - return value !== void 0 && value !== "" ? value : defaultValue; +// node_modules/axios/lib/helpers/isAxiosError.js +function isAxiosError(payload) { + return utils_default.isObject(payload) && payload.isAxiosError === true; } -// src/common/utils/localhostViemChain.ts -var localhostViemChain = defineChain({ - id: 1, - name: "localhost", - nativeCurrency: { - decimals: 18, - name: "eth", - symbol: "eth" - }, - rpcUrls: { - default: { http: [process.env.LOCALHOST_RPC_URL] } - }, - blockExplorers: [ - { - name: "localhost", - url: process.env.LOCALHOST_RPC_URL - } - ], - testnet: true +// node_modules/axios/lib/helpers/HttpStatusCode.js +var HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511 +}; +Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; }); +var HttpStatusCode_default = HttpStatusCode; -// src/constants/localRpcLoaders.ts -function getRpcOverride() { - try { - return __require("../../rpcs.override.json"); - } catch { - return {}; - } -} -function getRpcExtension() { - try { - return __require("../../rpcs.extension.json"); - } catch { - return {}; - } +// node_modules/axios/lib/axios.js +function createInstance(defaultConfig) { + const context = new Axios_default(defaultConfig); + const instance = bind(Axios_default.prototype.request, context); + utils_default.extend(instance, Axios_default.prototype, context, { allOwnKeys: true }); + utils_default.extend(instance, context, null, { allOwnKeys: true }); + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + return instance; } - -// src/constants/globalConfig.ts -var globalConfig = { - NETWORK_MODE: getEnvVar("NETWORK_MODE"), - OPERATOR_ADDRESS: getEnvVar("OPERATOR_ADDRESS"), - IGNORED_NETWORK_IDS: [], - WHITELISTED_NETWORK_IDS: { - mainnet: [], - testnet: [], - localhost: [ - /* 1 */ - ] - }, - LOGGER: { - LOG_LEVEL_DEFAULT: getOptionalEnvVar("LOG_LEVEL_DEFAULT", "info"), - LOG_LEVELS_GRANULAR: getGranularLogLevels(), - LOG_DIR: "logs", - LOG_MAX_FILES: "7d", - LOG_MAX_SIZE: "20m" - }, - URLS: { - CONCERO_RPCS: `https://raw.githubusercontent.com/concero/rpcs/refs/heads/${process.env.RPC_SERVICE_GIT_BRANCH ?? "master"}/output/`, - CONCERO_DEPLOYMENTS: `https://raw.githubusercontent.com/concero/v2-contracts/refs/heads/${process.env.DEPLOYMENTS_SERVICE_GIT_BRANCH ?? "master"}/.env.deployments.${getEnvVar("NETWORK_MODE") === "localhost" || getEnvVar("NETWORK_MODE") === "testnet" ? "testnet" : "mainnet"}`, - V2_NETWORKS: { - MAINNET_SUMMARY: "https://github.com/concero/v2-networks/raw/refs/heads/master/networks/mainnet.json", - TESTNET_SUMMARY: "https://github.com/concero/v2-networks/raw/refs/heads/master/networks/testnet.json", - MAINNET_DETAIL_BASE: "https://github.com/concero/v2-networks/raw/refs/heads/master/networks/mainnet", - TESTNET_DETAIL_BASE: "https://github.com/concero/v2-networks/raw/refs/heads/master/networks/testnet" - } - }, - VIEM: { - RECEIPT: {}, - WRITE_CONTRACT: {}, - FALLBACK_TRANSPORT_OPTIONS: { - retryCount: 5, - retryDelay: 2e3 - }, - SIMULATE_TX: getEnvVar("SIMULATE_TX") === "true" - }, - HTTPCLIENT: { - DEFAULT_TIMEOUT: 5e3, - MAX_RETRIES: 3, - RETRY_DELAY: 1e3 - }, - ABI: { - CONCERO_VERIFIER: abi2, - CONCERO_ROUTER: abi, - EVM_DST_CHAIN_DATA: { - components: [ - { - internalType: "address", - name: "receiver", - type: "address" - }, - { - internalType: "uint256", - name: "gasLimit", - type: "uint256" - } - ], - internalType: "struct ConceroTypes.EvmDstChainData", - name: "dstChainData", - type: "tuple" - } - }, - RPC: { - OVERRIDE: getRpcOverride(), - EXTENSION: getRpcExtension() - }, - TX_MANAGER: { - DRY_RUN: getEnvVar("DRY_RUN") === "true", - DEFAULT_CONFIRMATIONS: 3, - DEFAULT_RECEIPT_TIMEOUT: 6e4, - GAS_LIMIT: { - DEFAULT: 2000000n, - SUBMIT_MESSAGE_REPORT_OVERHEAD: 1000000n - } - }, - NETWORK_MANAGER: { - NETWORK_UPDATE_INTERVAL_MS: 1e3 * 60 * 60 - // 1 hour - }, - BLOCK_MANAGER: { - POLLING_INTERVAL_MS: parseInt(getEnvVar("BLOCK_MANAGER_POLLING_INTERVAL_MS")) || 5e3, - SEQUENTIAL_BATCH_SIZE: 100n, - CATCHUP_BATCH_SIZE: 500n, - MAX_BLOCKS_TO_PROCESS: 100n, - USE_CHECKPOINTS: getEnvVar("USE_CHECKPOINTS") === "true" - }, - NOTIFICATIONS: { - SLACK: { - MONITORING_SYSTEM_CHANNEL_ID: process.env.SLACK_MONITORING_SYSTEM_CHANNEL_ID, - BOT_TOKEN: process.env.SLACK_BOT_TOKEN - }, - INTERVAL: 60 * 60 * 1e3 - } +var axios = createInstance(defaults_default); +axios.Axios = Axios_default; +axios.CanceledError = CanceledError_default; +axios.CancelToken = CancelToken_default; +axios.isCancel = isCancel; +axios.VERSION = VERSION; +axios.toFormData = toFormData_default; +axios.AxiosError = AxiosError_default; +axios.Cancel = axios.CanceledError; +axios.all = function all(promises) { + return Promise.all(promises); }; +axios.spread = spread; +axios.isAxiosError = isAxiosError; +axios.mergeConfig = mergeConfig; +axios.AxiosHeaders = AxiosHeaders_default; +axios.formToJSON = (thing) => formDataToJSON_default(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing); +axios.getAdapter = adapters_default.getAdapter; +axios.HttpStatusCode = HttpStatusCode_default; +axios.default = axios; +var axios_default = axios; + +// node_modules/axios/index.js +var { + Axios: Axios2, + AxiosError: AxiosError2, + CanceledError: CanceledError2, + isCancel: isCancel2, + CancelToken: CancelToken2, + VERSION: VERSION2, + all: all2, + Cancel, + isAxiosError: isAxiosError2, + spread: spread2, + toFormData: toFormData2, + AxiosHeaders: AxiosHeaders2, + HttpStatusCode: HttpStatusCode2, + formToJSON, + getAdapter, + mergeConfig: mergeConfig2 +} = axios_default; -// src/common/utils/httpClient.ts -var { RETRY_DELAY, MAX_RETRIES, DEFAULT_TIMEOUT } = globalConfig.HTTPCLIENT; +// src/common/utils/HttpClient.ts var HttpClient = class _HttpClient extends ManagerBase { - static defaultInstance; - static queueInstance; + static instance; axiosInstance; logger; - requestQueue = []; - activeRequests = 0; - maxConcurrentRequests; - constructor(maxConcurrentRequests) { + config; + constructor(logger, config3) { super(); - this.maxConcurrentRequests = maxConcurrentRequests; - this.logger = Logger.getInstance().getLogger("HttpClient"); + this.logger = logger; + this.config = config3; } - static createInstance(maxConcurrentRequests) { - return new _HttpClient(maxConcurrentRequests); + static createInstance(logger, config3) { + this.instance = new _HttpClient(logger, config3); + return this.instance; } static getInstance() { - if (!_HttpClient.defaultInstance) { - _HttpClient.defaultInstance = new _HttpClient(); - } - return _HttpClient.defaultInstance; - } - static getQueueInstance() { - if (!_HttpClient.queueInstance) { - _HttpClient.queueInstance = new _HttpClient(2); - } - return _HttpClient.queueInstance; + return this.instance; } async initialize() { if (this.initialized) { @@ -62175,20 +61941,20 @@ var HttpClient = class _HttpClient extends ManagerBase { } async setupAxiosInstance() { this.axiosInstance = axios_default.create({ - timeout: DEFAULT_TIMEOUT + timeout: this.config.defaultTimeout }); this.axiosInstance.interceptors.response.use( (response) => response, async (error) => { const config3 = error.config; const logger = this.logger; - if (config3 && config3.__retryCount < MAX_RETRIES) { + if (config3 && config3.__retryCount < this.config.maxRetries) { config3.__retryCount = config3.__retryCount || 0; config3.__retryCount += 1; logger.warn( - `Retrying request to ${config3.url}. Attempt ${config3.__retryCount} of ${MAX_RETRIES}. Error: ${error.message}` + `Retrying request to ${config3.url}. Attempt ${config3.__retryCount} of ${this.config.maxRetries}. Error: ${error.message}` ); - await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY)); + await new Promise((resolve) => setTimeout(resolve, this.config.retryDelay)); return this.axiosInstance(config3); } logger.error( @@ -62199,38 +61965,14 @@ var HttpClient = class _HttpClient extends ManagerBase { ); } dispose() { - this.requestQueue = []; - this.activeRequests = 0; this.axiosInstance = void 0; super.dispose(); } static disposeInstances() { - if (_HttpClient.defaultInstance) { - _HttpClient.defaultInstance.dispose(); - _HttpClient.defaultInstance = void 0; + if (_HttpClient.instance) { + _HttpClient.instance.dispose(); + _HttpClient.instance = void 0; } - if (_HttpClient.queueInstance) { - _HttpClient.queueInstance.dispose(); - _HttpClient.queueInstance = void 0; - } - } - async processQueue() { - if ((this.maxConcurrentRequests === void 0 || this.activeRequests < this.maxConcurrentRequests) && this.requestQueue.length > 0) { - const nextRequest = this.requestQueue.shift(); - if (nextRequest) { - this.activeRequests++; - try { - await nextRequest(); - } finally { - this.activeRequests--; - this.processQueue(); - } - } - } - } - enqueueRequest(requestFn) { - this.requestQueue.push(requestFn); - this.processQueue(); } async request(method, url2, config3 = {}, body) { if (!this.initialized || !this.axiosInstance) { @@ -62239,26 +61981,21 @@ var HttpClient = class _HttpClient extends ManagerBase { new Error("HttpClient not initialized") ); } - return new Promise((resolve, reject) => { - const executeRequest = async () => { - try { - this.logger.debug( - `${method} request to ${url2} with config: ${JSON.stringify(config3)} ${body ? `and body: ${JSON.stringify(body)}` : ""}` - ); - const response = await this.axiosInstance.request({ - method, - url: url2, - data: body, - ...config3 - }); - resolve(response.data); - } catch (error) { - this.logger.error(`Request failed for ${url2} with error:`, error); - reject(new AppError("FailedHTTPRequest" /* FailedHTTPRequest */, error)); - } - }; - this.enqueueRequest(executeRequest); - }); + try { + this.logger.debug( + `${method} request to ${url2} with config: ${JSON.stringify(config3)} ${body ? `and body: ${JSON.stringify(body)}` : ""}` + ); + const response = await this.axiosInstance.request({ + method, + url: url2, + data: body, + ...config3 + }); + return response.data; + } catch (error) { + this.logger.error(`Request failed for ${url2} with error:`, error); + throw new AppError("FailedHTTPRequest" /* FailedHTTPRequest */, error); + } } async get(url2, config3 = {}) { return this.request("GET", url2, config3); @@ -62268,54 +62005,367 @@ var HttpClient = class _HttpClient extends ManagerBase { } }; +// src/common/utils/fetchNetworkConfigs.ts +async function fetchNetworkConfigs(networkMode = "testnet") { + const logger = Logger.getInstance().getLogger("NetworkConfig"); + const httpClient = HttpClient.getInstance(); + try { + let mainnetNetworks = {}; + let testnetNetworks = {}; + if (networkMode === "localhost") { + return { mainnetNetworks, testnetNetworks }; + } + if (networkMode === "mainnet") { + const mainnetData = await httpClient.get(globalConfig.URLS.V2_NETWORKS.MAINNET); + mainnetNetworks = processNetworkData( + mainnetData, + false, + logger + ); + } else if (networkMode === "testnet") { + const testnetData = await httpClient.get(globalConfig.URLS.V2_NETWORKS.TESTNET); + testnetNetworks = processNetworkData( + testnetData, + true, + logger + ); + } + return { + mainnetNetworks, + testnetNetworks + }; + } catch (error) { + logger.error(`Failed to fetch ${networkMode} network configurations:`, error); + throw error; + } +} +function processNetworkData(networkData, isTestnet, logger) { + const processedNetworks = {}; + for (const [networkName, details] of Object.entries(networkData)) { + try { + const chainDefinition = { + id: details.chainId, + name: details.name, + rpcUrls: details.rpcUrls, + blockExplorer: details.blockExplorers[0] ? { + name: details.blockExplorers[0].name, + url: details.blockExplorers[0].url + } : void 0, + isTestnet + }; + processedNetworks[networkName] = { + name: details.name, + chainId: details.chainId, + chainSelector: details.chainSelector.toString(), + viemChain: createViemChain(chainDefinition) + }; + } catch (error) { + const networkType = isTestnet ? "testnet" : "mainnet"; + logger.warn( + `Failed to process ${networkType} network ${networkName}: ${error instanceof Error ? error.message : String(error)}` + ); + } + } + return processedNetworks; +} + +// src/common/utils/getEnvVar.ts +import process2 from "process"; +function getEnvVar(key) { + const value = process2.env[key]; + if (value === void 0 || value === "") throw new Error(`Missing environment variable ${key}`); + return value; +} + +// src/common/utils/getGranularLogLevels.ts +import process3 from "process"; +function getGranularLogLevels() { + const logLevels = {}; + const LOG_LEVEL_PREFIX = "LOG_LEVEL_"; + Object.keys(process3.env).forEach((key) => { + if (key.startsWith(LOG_LEVEL_PREFIX) && key !== "LOG_LEVEL_DEFAULT") { + const componentName = key.substring(LOG_LEVEL_PREFIX.length); + const level = process3.env[key]; + if (componentName && level) { + logLevels[componentName] = level; + console.log( + `[getGranularLogLevels] Component-specific log level: ${componentName}=${level}` + ); + } + } + }); + return logLevels; +} + +// src/common/utils/getOptionalEnvVar.ts +function getOptionalEnvVar(key, defaultValue) { + const value = process.env[key]; + return value !== void 0 && value !== "" ? value : defaultValue; +} + +// src/common/utils/localhostViemChain.ts +var localhostViemChain = defineChain({ + id: 1, + name: "localhost", + nativeCurrency: { + decimals: 18, + name: "eth", + symbol: "eth" + }, + rpcUrls: { + default: { http: [process.env.LOCALHOST_RPC_URL] } + }, + blockExplorers: [ + { + name: "localhost", + url: process.env.LOCALHOST_RPC_URL + } + ], + testnet: true +}); + +// src/constants/localRpcLoaders.ts +function getRpcOverride() { + try { + return __require("../../rpcs.override.json"); + } catch { + return {}; + } +} +function getRpcExtension() { + try { + return __require("../../rpcs.extension.json"); + } catch { + return {}; + } +} + +// src/constants/globalConfig.ts +var globalConfig = { + NETWORK_MODE: getEnvVar("NETWORK_MODE"), + OPERATOR_ADDRESS: getEnvVar("OPERATOR_ADDRESS"), + IGNORED_NETWORK_IDS: [], + WHITELISTED_NETWORK_IDS: { + mainnet: [], + testnet: [], + localhost: [ + /* 1 */ + ] + }, + LOGGER: { + LOG_LEVEL_DEFAULT: getOptionalEnvVar("LOG_LEVEL_DEFAULT", "info"), + LOG_LEVELS_GRANULAR: getGranularLogLevels(), + LOG_DIR: "logs", + LOG_MAX_FILES: "7d", + LOG_MAX_SIZE: "20m" + }, + URLS: { + CONCERO_RPCS: `https://raw.githubusercontent.com/concero/rpcs/refs/heads/${process.env.RPC_SERVICE_GIT_BRANCH ?? "master"}/output`, + CONCERO_DEPLOYMENTS: `https://raw.githubusercontent.com/concero/v2-contracts/refs/heads/${process.env.DEPLOYMENTS_SERVICE_GIT_BRANCH ?? "master"}/.env.deployments.${getEnvVar("NETWORK_MODE") === "localhost" || getEnvVar("NETWORK_MODE") === "testnet" ? "testnet" : "mainnet"}`, + V2_NETWORKS: { + MAINNET: "https://github.com/concero/v2-networks/raw/refs/heads/master/networks/mainnet.json", + TESTNET: "https://github.com/concero/v2-networks/raw/refs/heads/master/networks/testnet.json" + } + }, + VIEM: { + RECEIPT: {}, + WRITE_CONTRACT: {}, + FALLBACK_TRANSPORT_OPTIONS: { + retryCount: 5, + retryDelay: 2e3 + }, + SIMULATE_TX: getEnvVar("SIMULATE_TX") === "true" + }, + HTTPCLIENT: { + DEFAULT_TIMEOUT: 5e3, + MAX_RETRIES: 3, + RETRY_DELAY: 1e3 + }, + ABI: { + CONCERO_VERIFIER: abi2, + CONCERO_ROUTER: abi, + EVM_DST_CHAIN_DATA: { + components: [ + { + internalType: "address", + name: "receiver", + type: "address" + }, + { + internalType: "uint256", + name: "gasLimit", + type: "uint256" + } + ], + internalType: "struct ConceroTypes.EvmDstChainData", + name: "dstChainData", + type: "tuple" + } + }, + RPC: { + OVERRIDE: getRpcOverride(), + EXTENSION: getRpcExtension() + }, + TX_MANAGER: { + DRY_RUN: getEnvVar("DRY_RUN") === "true", + DEFAULT_CONFIRMATIONS: 3, + DEFAULT_RECEIPT_TIMEOUT: 6e4, + GAS_LIMIT: { + DEFAULT: 2000000n, + SUBMIT_MESSAGE_REPORT_OVERHEAD: 1000000n + } + }, + NETWORK_MANAGER: { + NETWORK_UPDATE_INTERVAL_MS: 1e3 * 60 * 60 + // 1 hour + }, + BLOCK_MANAGER: { + POLLING_INTERVAL_MS: parseInt(getEnvVar("BLOCK_MANAGER_POLLING_INTERVAL_MS")) || 5e3, + SEQUENTIAL_BATCH_SIZE: 100n, + CATCHUP_BATCH_SIZE: 500n, + MAX_BLOCKS_TO_PROCESS: 100n, + USE_CHECKPOINTS: getEnvVar("USE_CHECKPOINTS") === "true" + }, + NOTIFICATIONS: { + SLACK: { + MONITORING_SYSTEM_CHANNEL_ID: process.env.SLACK_MONITORING_SYSTEM_CHANNEL_ID, + BOT_TOKEN: process.env.SLACK_BOT_TOKEN + }, + INTERVAL: 60 * 60 * 1e3 + } +}; + // src/common/utils/initializeManagers.ts async function initializeManagers() { - const logger = Logger.createInstance(); + const logger = Logger.createInstance({ + logDir: globalConfig.LOGGER.LOG_DIR, + logMaxSize: globalConfig.LOGGER.LOG_MAX_SIZE, + logMaxFiles: globalConfig.LOGGER.LOG_MAX_FILES, + logLevelDefault: globalConfig.LOGGER.LOG_LEVEL_DEFAULT, + logLevelsGranular: globalConfig.LOGGER.LOG_LEVELS_GRANULAR + }); await logger.initialize(); - const httpClient = HttpClient.getInstance(); - const httpQueue = HttpClient.getQueueInstance(); - httpClient.initialize(); - httpQueue.initialize(); - const rpcManager = RpcManager.createInstance(); - const viemClientManager = ViemClientManager.createInstance(rpcManager); - const deploymentManager = DeploymentManager.createInstance(); - const networkManager = NetworkManager.createInstance(rpcManager, deploymentManager); - const blockCheckpointManager = BlockCheckpointManager.createInstance(); + const httpLoggerInstance = logger.getLogger("HttpClient"); + const httpClient = HttpClient.createInstance(httpLoggerInstance, { + retryDelay: globalConfig.HTTPCLIENT.RETRY_DELAY, + maxRetries: globalConfig.HTTPCLIENT.MAX_RETRIES, + defaultTimeout: globalConfig.HTTPCLIENT.DEFAULT_TIMEOUT + }); + await httpClient.initialize(); + const blockCheckpointManagerConfig = { + useCheckpoints: globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS + }; + const blockManagerConfig = { + pollingIntervalMs: globalConfig.BLOCK_MANAGER.POLLING_INTERVAL_MS, + catchupBatchSize: globalConfig.BLOCK_MANAGER.CATCHUP_BATCH_SIZE, + useCheckpoints: globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS + }; + const blockManagerRegistryConfig = { + blockManagerConfig + }; + const rpcManagerConfig = { + rpcOverrides: globalConfig.RPC.OVERRIDE, + rpcExtensions: globalConfig.RPC.EXTENSION, + conceroRpcsUrl: globalConfig.URLS.CONCERO_RPCS, + networkMode: globalConfig.NETWORK_MODE + }; + const viemClientManagerConfig = { + fallbackTransportOptions: globalConfig.VIEM.FALLBACK_TRANSPORT_OPTIONS + }; + const deploymentManagerConfig = { + conceroDeploymentsUrl: globalConfig.URLS.CONCERO_DEPLOYMENTS, + networkMode: globalConfig.NETWORK_MODE + }; + const networkManagerConfig = { + networkUpdateIntervalMs: globalConfig.NETWORK_MANAGER.NETWORK_UPDATE_INTERVAL_MS, + networkMode: globalConfig.NETWORK_MODE, + ignoredNetworkIds: globalConfig.IGNORED_NETWORK_IDS, + whitelistedNetworkIds: globalConfig.WHITELISTED_NETWORK_IDS, + defaultConfirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS + }; + const txWriterConfig = { + dryRun: globalConfig.TX_MANAGER.DRY_RUN + }; + const txReaderConfig = {}; + const txMonitorConfig = {}; + const txManagerConfig = { + defaultConfirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS + }; + const nonceManagerConfig = {}; + const rpcManager = RpcManager.createInstance(logger.getLogger("RpcManager"), rpcManagerConfig); + const viemClientManager = ViemClientManager.createInstance( + logger.getLogger("ViemClientManager"), + rpcManager, + viemClientManagerConfig + ); + const deploymentManager = DeploymentManager.createInstance( + logger.getLogger("DeploymentManager"), + deploymentManagerConfig + ); + const networkManager = NetworkManager.createInstance( + logger.getLogger("NetworkManager"), + networkManagerConfig + ); + const blockCheckpointManager = BlockCheckpointManager.createInstance( + logger.getLogger("BlockCheckpointManager"), + blockCheckpointManagerConfig + ); const blockManagerRegistry = BlockManagerRegistry.createInstance( + logger.getLogger("BlockManagerRegistry"), blockCheckpointManager, networkManager, viemClientManager, - rpcManager + rpcManager, + blockManagerRegistryConfig ); + await networkManager.initialize(); await rpcManager.initialize(); await viemClientManager.initialize(); await deploymentManager.initialize(); - await networkManager.initialize(); + networkManager.registerUpdateListener(rpcManager); + networkManager.registerUpdateListener(deploymentManager); + networkManager.registerUpdateListener(viemClientManager); + networkManager.registerUpdateListener(blockManagerRegistry); + await networkManager.triggerInitialUpdates(); await blockCheckpointManager.initialize(); await blockManagerRegistry.initialize(); - const txWriter = TxWriter.createInstance(networkManager, viemClientManager); + const txWriter = TxWriter.createInstance( + logger.getLogger("TxWriter"), + networkManager, + viemClientManager, + txWriterConfig + ); const txReader = TxReader.createInstance( + logger.getLogger("TxReader"), networkManager, viemClientManager, - blockManagerRegistry + blockManagerRegistry, + txReaderConfig ); await txWriter.initialize(); await txReader.initialize(); const txMonitor = TxMonitor.createInstance( + logger.getLogger("TxMonitor"), viemClientManager, (txHash, chainName) => txWriter.onTxFinality(txHash, chainName), - (txHash, chainName) => txWriter.onTxReorg(txHash, chainName) + (txHash, chainName) => txWriter.onTxReorg(txHash, chainName), + txMonitorConfig ); const txManager = TxManager.createInstance( + logger.getLogger("TxManager"), networkManager, viemClientManager, blockManagerRegistry, txWriter, txReader, - txMonitor + txMonitor, + txManagerConfig ); await txManager.initialize(); - const nonceManager = NonceManager.createInstance(); + const nonceManager = NonceManager.createInstance( + logger.getLogger("NonceManager"), + nonceManagerConfig + ); await nonceManager.initialize(); } @@ -62344,12 +62394,14 @@ var BlockCheckpointManager = class _BlockCheckpointManager extends ManagerBase { static instance; prisma = DbManager.getClient(); logger; - constructor() { + config; + constructor(logger, config3) { super(); - this.logger = Logger.getInstance().getLogger("BlockCheckpointManager"); + this.logger = logger; + this.config = config3; } - static createInstance() { - _BlockCheckpointManager.instance = new _BlockCheckpointManager(); + static createInstance(logger, config3) { + _BlockCheckpointManager.instance = new _BlockCheckpointManager(logger, config3); return _BlockCheckpointManager.instance; } static getInstance() { @@ -62374,7 +62426,7 @@ var BlockCheckpointManager = class _BlockCheckpointManager extends ManagerBase { } } async updateLastProcessedBlock(networkName, blockNumber) { - if (!globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS) return; + if (!this.config.useCheckpoints) return; try { await this.prisma.blockCheckpoint.upsert({ where: { network: networkName }, @@ -62412,21 +62464,24 @@ var BlockManager = class _BlockManager { blockCheckpointManager; blockRangeHandlers = /* @__PURE__ */ new Map(); logger; + config; isDisposed = false; isPolling = false; - pollingIntervalMs = globalConfig.BLOCK_MANAGER.POLLING_INTERVAL_MS; + pollingIntervalMs; pollingTimeout = null; - constructor(initialBlock, network, publicClient, blockCheckpointManager) { + constructor(initialBlock, network, publicClient, blockCheckpointManager, logger, config3) { this.lastProcessedBlockNumber = initialBlock; this.publicClient = publicClient; this.network = network; this.blockCheckpointManager = blockCheckpointManager; - this.logger = Logger.getInstance().getLogger("BlockManager"); + this.logger = logger; + this.config = config3; + this.pollingIntervalMs = config3.pollingIntervalMs; } - static async create(network, publicClient, blockCheckpointManager) { + static async create(network, publicClient, blockCheckpointManager, logger, config3) { let initialBlock; - const staticLogger = Logger.getInstance().getLogger("BlockManager"); - if (!globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS) { + const staticLogger = logger; + if (!config3.useCheckpoints) { initialBlock = await publicClient.getBlockNumber(); staticLogger.debug( `${network.name}: Checkpoints disabled. Starting from current chain tip: ${initialBlock}` @@ -62452,7 +62507,9 @@ var BlockManager = class _BlockManager { initialBlock, network, publicClient, - blockCheckpointManager + blockCheckpointManager, + logger, + config3 ); return blockManager; } @@ -62547,7 +62604,7 @@ var BlockManager = class _BlockManager { ); while (currentBlock < this.latestBlock && !this.isDisposed) { const startBlock = currentBlock + 1n; - const endBlock = startBlock + globalConfig.BLOCK_MANAGER.CATCHUP_BATCH_SIZE - 1n > this.latestBlock ? this.latestBlock : startBlock + globalConfig.BLOCK_MANAGER.CATCHUP_BATCH_SIZE - 1n; + const endBlock = startBlock + this.config.catchupBatchSize - 1n > this.latestBlock ? this.latestBlock : startBlock + this.config.catchupBatchSize - 1n; await this.processBlockRange(startBlock, endBlock); currentBlock = endBlock; } @@ -62589,19 +62646,24 @@ var BlockManagerRegistry = class _BlockManagerRegistry extends ManagerBase { viemClientManager; rpcManager; logger; - constructor(blockCheckpointManager, networkManager, viemClientManager, rpcManager) { + config; + constructor(logger, blockCheckpointManager, networkManager, viemClientManager, rpcManager, config3) { super(); + this.logger = logger; this.blockCheckpointManager = blockCheckpointManager; this.networkManager = networkManager; this.viemClientManager = viemClientManager; this.rpcManager = rpcManager; - this.logger = Logger.getInstance().getLogger("BlockManagerRegistry"); + this.config = config3; } - onNetworksUpdated(networks) { + async onNetworksUpdated(networks) { this.logger.info(`Networks updated, syncing BlockManagers for ${networks.length} networks`); - this.updateBlockManagers(networks).catch((error) => { + try { + await this.updateBlockManagers(networks); + } catch (error) { this.logger.error("Failed to sync BlockManagers after network update", error); - }); + throw error; + } } async ensureBlockManagerForNetwork(network) { if (this.blockManagers.has(network.name)) { @@ -62609,7 +62671,6 @@ var BlockManagerRegistry = class _BlockManagerRegistry extends ManagerBase { return this.blockManagers.get(network.name); } try { - await this.rpcManager.ensureRpcsForNetwork(network); const { publicClient } = this.viemClientManager.getClients(network); const blockManager = await this.createBlockManager(network, publicClient); return blockManager; @@ -62634,19 +62695,21 @@ var BlockManagerRegistry = class _BlockManagerRegistry extends ManagerBase { } const newNetworks = networks.filter((network) => !currentNetworkNames.has(network.name)); if (newNetworks.length > 0) { - this.logger.debug(`Creating ${newNetworks.length} new BlockManagers in parallel`); + this.logger.debug(`Creating ${newNetworks.length} new BlockManagers`); const results = await Promise.all( newNetworks.map((network) => this.ensureBlockManagerForNetwork(network)) ); } } //TODO: attempt to refactor createInstance to a base class - static createInstance(blockCheckpointManager, networkManager, viemClientManager, rpcManager) { + static createInstance(logger, blockCheckpointManager, networkManager, viemClientManager, rpcManager, config3) { _BlockManagerRegistry.instance = new _BlockManagerRegistry( + logger, blockCheckpointManager, networkManager, viemClientManager, - rpcManager + rpcManager, + config3 ); return _BlockManagerRegistry.instance; } @@ -62664,9 +62727,6 @@ var BlockManagerRegistry = class _BlockManagerRegistry extends ManagerBase { this.networkManager.registerUpdateListener(this); await super.initialize(); this.logger.debug("Initialized"); - const activeNetworks = this.networkManager.getActiveNetworks(); - this.logger.debug(`Starting initial sync for ${activeNetworks.length} networks`); - await this.updateBlockManagers(activeNetworks); } catch (error) { this.logger.error("Failed to initialize", error); throw error; @@ -62679,7 +62739,13 @@ var BlockManagerRegistry = class _BlockManagerRegistry extends ManagerBase { const blockManager = await BlockManager.create( network, publicClient, - this.blockCheckpointManager + this.blockCheckpointManager, + this.logger, + { + pollingIntervalMs: this.config.blockManagerConfig.pollingIntervalMs, + catchupBatchSize: this.config.blockManagerConfig.catchupBatchSize, + useCheckpoints: this.config.blockManagerConfig.useCheckpoints + } ); this.blockManagers.set(network.name, blockManager); this.logger.debug(`Created BlockManager for network ${network.name}`); @@ -62729,13 +62795,15 @@ var DeploymentManager = class _DeploymentManager extends ManagerBase { conceroVerifier; httpClient; logger; - constructor() { + config; + constructor(logger, config3) { super(); - this.httpClient = HttpClient.getQueueInstance(); - this.logger = Logger.getInstance().getLogger("DeploymentManager"); + this.httpClient = HttpClient.getInstance(); + this.logger = logger; + this.config = config3; } - static createInstance() { - _DeploymentManager.instance = new _DeploymentManager(); + static createInstance(logger, config3) { + _DeploymentManager.instance = new _DeploymentManager(logger, config3); return _DeploymentManager.instance; } static getInstance() { @@ -62792,7 +62860,7 @@ var DeploymentManager = class _DeploymentManager extends ManagerBase { async updateDeployments() { const now = Date.now(); try { - const deployments = await this.httpClient.get(globalConfig.URLS.CONCERO_DEPLOYMENTS, { + const deployments = await this.httpClient.get(this.config.conceroDeploymentsUrl, { responseType: "text" // Ensure Axios returns raw text }); @@ -62810,7 +62878,7 @@ var DeploymentManager = class _DeploymentManager extends ManagerBase { } this.conceroRoutersMapByChainName = routerMap; const verifierEntry = deploymentsEnvArr.find((d) => { - const networkSuffix = globalConfig.NETWORK_MODE === "testnet" ? "ARBITRUM_SEPOLIA" : "ARBITRUM"; + const networkSuffix = this.config.networkMode === "testnet" ? "ARBITRUM_SEPOLIA" : "ARBITRUM"; return d.startsWith(`CONCERO_VERIFIER_PROXY_${networkSuffix}`); }); if (verifierEntry) { @@ -62825,10 +62893,13 @@ var DeploymentManager = class _DeploymentManager extends ManagerBase { ); } } - onNetworksUpdated() { - this.updateDeployments().catch( - (err) => this.logger.error("Failed to update deployments after network update:", err) - ); + async onNetworksUpdated(networks) { + try { + await this.updateDeployments(); + } catch (err) { + this.logger.error("Failed to update deployments after network update:", err); + throw err; + } } extractNetworkName(key) { const prefix = "CONCERO_ROUTER_PROXY_"; @@ -62836,7 +62907,7 @@ var DeploymentManager = class _DeploymentManager extends ManagerBase { return parts[0] + parts.slice(1).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(""); } isLocalhostEnv() { - return globalConfig.NETWORK_MODE === "localhost"; + return this.config.networkMode === "localhost"; } dispose() { super.dispose(); @@ -62852,27 +62923,19 @@ var NetworkManager = class _NetworkManager extends ManagerBase { allNetworks = {}; activeNetworks = []; updateIntervalId = null; - rpcManager = null; - deploymentsManager = null; updateListeners = []; logger; - constructor(rpcManager, deploymentsManager) { + config; + constructor(logger, config3) { super(); - this.rpcManager = rpcManager || null; - this.deploymentsManager = deploymentsManager || null; - this.logger = Logger.getInstance().getLogger("NetworkManager"); - if (this.rpcManager && "onNetworksUpdated" in this.rpcManager) { - this.registerUpdateListener(this.rpcManager); - } - if (this.deploymentsManager && "onNetworksUpdated" in this.deploymentsManager) { - this.registerUpdateListener(this.deploymentsManager); - } + this.config = config3; + this.logger = logger; } static getInstance() { return _NetworkManager.instance; } - static createInstance(rpcManager, deploymentsManager) { - this.instance = new _NetworkManager(rpcManager, deploymentsManager); + static createInstance(logger, config3) { + this.instance = new _NetworkManager(logger, config3); return this.instance; } async initialize() { @@ -62939,11 +63002,11 @@ var NetworkManager = class _NetworkManager extends ManagerBase { return network; } getVerifierNetwork() { - if (globalConfig.NETWORK_MODE === "mainnet") { + if (this.config.networkMode === "mainnet") { return this.mainnetNetworks["arbitrum"]; - } else if (globalConfig.NETWORK_MODE === "testnet") { + } else if (this.config.networkMode === "testnet") { return this.testnetNetworks["arbitrumSepolia"]; - } else if (globalConfig.NETWORK_MODE === "localhost") { + } else if (this.config.networkMode === "localhost") { const localNetwork = this.testnetNetworks["localhost"]; if (!localNetwork) { this.logger.error( @@ -62956,7 +63019,7 @@ var NetworkManager = class _NetworkManager extends ManagerBase { ); return localNetwork; } else { - throw new Error(`Unsupported network mode: ${globalConfig.NETWORK_MODE}`); + throw new Error(`Unsupported network mode: ${this.config.networkMode}`); } } async forceUpdate() { @@ -62970,50 +63033,98 @@ var NetworkManager = class _NetworkManager extends ManagerBase { () => this.updateNetworks().catch( (err) => this.logger.error("Network update failed:", err) ), - globalConfig.NETWORK_MANAGER.NETWORK_UPDATE_INTERVAL_MS + this.config.networkUpdateIntervalMs ); } async updateNetworks() { + let networksFetched = false; try { const operatorPK = getEnvVar("OPERATOR_PRIVATE_KEY"); - if (globalConfig.NETWORK_MODE === "localhost") { + if (this.config.networkMode === "localhost") { this.mainnetNetworks = {}; const localhostNetworks = this.getTestingNetworks(operatorPK); this.testnetNetworks = localhostNetworks; this.logger.debug( `Using localhost networks only: ${Object.keys(localhostNetworks).join(", ")}` ); + networksFetched = true; } else { - const { mainnetNetworks: fetchedMainnet, testnetNetworks: fetchedTestnet } = await fetchNetworkConfigs(); - this.mainnetNetworks = this.createNetworkConfig(fetchedMainnet, "mainnet", [ - operatorPK - ]); - this.testnetNetworks = { - ...this.createNetworkConfig(fetchedTestnet, "testnet", [operatorPK]) - }; + try { + const { mainnetNetworks: fetchedMainnet, testnetNetworks: fetchedTestnet } = await fetchNetworkConfigs(this.config.networkMode); + const hasMainnetNetworks = Object.keys(fetchedMainnet).length > 0; + const hasTestnetNetworks = Object.keys(fetchedTestnet).length > 0; + if (hasMainnetNetworks) { + this.mainnetNetworks = this.createNetworkConfig(fetchedMainnet, "mainnet", [ + operatorPK + ]); + } else { + this.logger.warn( + "No mainnet networks fetched, keeping existing mainnet networks" + ); + } + if (hasTestnetNetworks) { + this.testnetNetworks = this.createNetworkConfig(fetchedTestnet, "testnet", [ + operatorPK + ]); + } else { + this.logger.warn( + "No testnet networks fetched, keeping existing testnet networks" + ); + } + networksFetched = true; + } catch (error) { + this.logger.warn( + "Failed to fetch network configurations. Will retry on next update cycle:", + error + ); + if (Object.keys(this.allNetworks).length === 0) { + this.logger.error( + "No network configurations available. Unable to initialize services." + ); + } + } } this.allNetworks = { ...this.testnetNetworks, ...this.mainnetNetworks }; - this.activeNetworks = this.filterNetworks( - globalConfig.NETWORK_MODE - ); - this.logger.debug( - `Networks updated - Active networks: ${this.activeNetworks.length} (${this.activeNetworks.map((n) => n.name).join(", ")})` - ); - this.notifyListeners(); + const filteredNetworks = this.filterNetworks(this.config.networkMode); + if (networksFetched) { + this.activeNetworks = filteredNetworks; + this.logger.debug( + `Networks updated - Active networks: ${this.activeNetworks.length} (${this.activeNetworks.map((n) => n.name).join(", ")})` + ); + } + if (networksFetched) { + await this.notifyListeners(); + } } catch (error) { this.logger.error("Failed to update networks:", error); - throw error; } } - notifyListeners() { + async notifyListeners() { for (const listener of this.updateListeners) { try { - listener.onNetworksUpdated(this.activeNetworks); + await listener.onNetworksUpdated(this.activeNetworks); } catch (error) { this.logger.error("Error in network update listener:", error); } } } + async triggerInitialUpdates() { + this.logger.debug("Triggering initial updates for all listeners sequentially"); + for (const listener of this.updateListeners) { + try { + this.logger.debug(`Triggering initial update for ${listener.constructor.name}`); + await listener.onNetworksUpdated(this.activeNetworks); + this.logger.debug(`Completed initial update for ${listener.constructor.name}`); + } catch (error) { + this.logger.error( + `Error in initial update for ${listener.constructor.name}:`, + error + ); + throw error; + } + } + this.logger.debug("Completed all initial updates"); + } createNetworkConfig(networks, networkType, accounts) { return Object.fromEntries( Object.entries(networks).map(([key, network]) => { @@ -63026,7 +63137,7 @@ var NetworkManager = class _NetworkManager extends ManagerBase { id: network.chainId, accounts, chainSelector: network.chainSelector || network.chainId.toString(), - confirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS, + confirmations: this.config.defaultConfirmations, viemChain: network.viemChain } ]; @@ -63041,15 +63152,15 @@ var NetworkManager = class _NetworkManager extends ManagerBase { id: 1, accounts: [operatorPK], chainSelector: "1", - confirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS, + confirmations: this.config.defaultConfirmations, viemChain: localhostViemChain } }; } filterNetworks(networkType) { let networks = []; - const ignoredIds = globalConfig.IGNORED_NETWORK_IDS || []; - const whitelistedIds = globalConfig.WHITELISTED_NETWORK_IDS[networkType] || []; + const ignoredIds = this.config.ignoredNetworkIds || []; + const whitelistedIds = this.config.whitelistedNetworkIds[networkType] || []; switch (networkType) { case "localhost": networks = Object.values( @@ -63290,12 +63401,16 @@ var NonceManager = class _NonceManager extends ManagerBase { static instance = null; noncesMap = {}; mutexMap = {}; - constructor() { + logger; + config; + constructor(logger, config3) { super(); + this.logger = logger; + this.config = config3; } - static createInstance() { + static createInstance(logger, config3) { if (!_NonceManager.instance) { - _NonceManager.instance = new _NonceManager(); + _NonceManager.instance = new _NonceManager(logger, config3); } return _NonceManager.instance; } @@ -63358,18 +63473,22 @@ var RpcManager = class _RpcManager extends ManagerBase { static instance; httpClient; logger; - constructor() { + config; + constructor(logger, config3) { super(); - this.httpClient = HttpClient.getQueueInstance(); - this.logger = Logger.getInstance().getLogger("RpcManager"); + this.httpClient = HttpClient.getInstance(logger, { + retryDelay: 1e3, + maxRetries: 3, + defaultTimeout: 1e4 + }); + this.logger = logger; + this.config = config3; } - static createInstance() { - _RpcManager.instance = new _RpcManager(); + static createInstance(logger, config3) { + _RpcManager.instance = new _RpcManager(logger, config3); return _RpcManager.instance; } rpcUrls = {}; - lastUpdateTime = {}; - rpcUpdateListeners = []; static getInstance() { if (!_RpcManager.instance) { throw new Error("RpcManager is not initialized. Call createInstance() first."); @@ -63381,113 +63500,38 @@ var RpcManager = class _RpcManager extends ManagerBase { await super.initialize(); this.logger.debug("Initialized"); } - registerRpcUpdateListener(listener) { - if (!this.rpcUpdateListeners.includes(listener)) { - this.rpcUpdateListeners.push(listener); - } - } - unregisterRpcUpdateListener(listener) { - const index2 = this.rpcUpdateListeners.indexOf(listener); - if (index2 !== -1) { - this.rpcUpdateListeners.splice(index2, 1); - } - } async ensureRpcsForNetwork(network) { - const now = Date.now(); - const lastUpdate = this.lastUpdateTime[network.name] || 0; if (!this.rpcUrls[network.name] || this.rpcUrls[network.name].length === 0) { - await this.updateRpcsForNetwork(network); - } - } - async fetchRpcUrls(chainId, chainName, chainType) { - try { - const rpcOverride = globalConfig.RPC.OVERRIDE[chainId.toString()]; - if (rpcOverride && rpcOverride.length) return rpcOverride; - if (chainType === "localhost") { - const localhostUrl = process.env.LOCALHOST_RPC_URL; - if (!localhostUrl) { - throw new Error("LOCALHOST_RPC_URL environment variable is not set"); - } - return [localhostUrl]; - } - const url2 = `${globalConfig.URLS.CONCERO_RPCS}${chainType}/${chainId}-${chainName}.json`; - const chainConfig = await this.httpClient.get(url2); - const response = await chainConfig; - const urls = response.urls; - const rpcsExtension = globalConfig.RPC.EXTENSION[chainId.toString()]; - if (rpcsExtension) { - rpcsExtension.forEach((url3) => { - urls.push(url3); - }); - } - if (!urls) { - throw new Error(`Invalid RPC URL response format for chain ${chainName}`); - } - return urls; - } catch (error) { - this.logger.error(`Error fetching RPC URLs for ${chainName}:`, error); - throw error; + await this.updateRpcs([network]); } } async updateRpcsForNetworks(networks) { - const updatePromises = []; - const updatedNetworks = []; - for (const network of networks) { - updatePromises.push( - this.updateRpcsForNetwork(network).then(() => { - updatedNetworks.push(network); - }).catch((error) => { - this.logger.error( - `Failed to update RPC for network ${network.name}:`, - error - ); - }) - ); - } - await Promise.allSettled(updatePromises); - if (updatedNetworks.length > 0) { - this.notifyRpcUpdateListeners(updatedNetworks); - } - this.logger.debug( - `Updated RPC URLs for ${updatedNetworks.map((network) => network.name).join(", ")}: ${updatedNetworks.length} networks updated` - ); + await this.updateRpcs(networks); } - async updateRpcsForNetwork(network) { + async updateRpcs(networks) { try { - const urls = await this.fetchRpcUrls(network.id, network.name, network.type); - if (urls.length > 0) { - const previousUrls = this.rpcUrls[network.name] || []; - this.rpcUrls[network.name] = urls; - this.lastUpdateTime[network.name] = Date.now(); - if (JSON.stringify(previousUrls) !== JSON.stringify(urls)) { - this.notifyRpcUpdateListeners([network]); - } - } else { - this.logger.warn(`No RPC URLs found for chain ${network.name}`); - this.rpcUrls[network.name] = []; + const url2 = `${this.config.conceroRpcsUrl}/${this.config.networkMode}.json`; + const response = await this.httpClient.get(url2); + if (!response) { + throw new Error("Failed to fetch RPC data"); } + this.rpcUrls = response; + this.logger.debug(`Updated RPCs for ${Object.keys(response).length} networks`); } catch (error) { - this.logger.error(`Failed to update RPC URLs for chain ${network.name}:`, error); - this.rpcUrls[network.name] = this.rpcUrls[network.name] || []; + this.logger.error("Failed to update RPCs:", error); throw error; } } - notifyRpcUpdateListeners(networks) { - for (const listener of this.rpcUpdateListeners) { - try { - listener.onRpcUrlsUpdated(networks); - } catch (error) { - this.logger.error("Error in RPC update listener:", error); - } - } - } getRpcsForNetwork(networkName) { return this.rpcUrls[networkName] || []; } - onNetworksUpdated(networks) { - this.updateRpcsForNetworks(networks).catch( - (err) => this.logger.error("Failed to update RPCs after network update:", err) - ); + async onNetworksUpdated(networks) { + try { + await this.updateRpcs(networks); + } catch (err) { + this.logger.error("Failed to update RPCs after network update:", err); + throw err; + } } }; @@ -63501,25 +63545,29 @@ var TxManager = class _TxManager extends ManagerBase { viemClientManager; blockManagerRegistry; logger; - constructor(networkManager, viemClientManager, blockManagerRegistry, txWriter, txReader, txMonitor) { + config; + constructor(logger, networkManager, viemClientManager, blockManagerRegistry, txWriter, txReader, txMonitor, config3) { super(); + this.logger = logger; this.networkManager = networkManager; this.viemClientManager = viemClientManager; this.blockManagerRegistry = blockManagerRegistry; this.txWriter = txWriter; this.txReader = txReader; this.txMonitor = txMonitor; - this.logger = Logger.getInstance().getLogger("TxManager"); + this.config = config3; } - static createInstance(networkManager, viemClientManager, blockManagerRegistry, txWriter, txReader, txMonitor) { + static createInstance(logger, networkManager, viemClientManager, blockManagerRegistry, txWriter, txReader, txMonitor, config3) { if (!_TxManager.instance) { _TxManager.instance = new _TxManager( + logger, networkManager, viemClientManager, blockManagerRegistry, txWriter, txReader, - txMonitor + txMonitor, + config3 ); } return _TxManager.instance; @@ -63587,15 +63635,21 @@ var TxMonitor = class _TxMonitor { txFinalityCallback; txReorgCallback; logger; - constructor(viemClientManager, txFinalityCallback, txReorgCallback) { + constructor(logger, viemClientManager, txFinalityCallback, txReorgCallback, config3) { this.viemClientManager = viemClientManager; this.txFinalityCallback = txFinalityCallback; this.txReorgCallback = txReorgCallback; - this.logger = Logger.getInstance().getLogger("TxMonitor"); + this.logger = logger; this.logger.info("initialized"); } - static createInstance(viemClientManager, txFinalityCallback, txReorgCallback) { - _TxMonitor.instance = new _TxMonitor(viemClientManager, txFinalityCallback, txReorgCallback); + static createInstance(logger, viemClientManager, txFinalityCallback, txReorgCallback, config3) { + _TxMonitor.instance = new _TxMonitor( + logger, + viemClientManager, + txFinalityCallback, + txReorgCallback, + config3 + ); return _TxMonitor.instance; } static getInstance() { @@ -63787,17 +63841,25 @@ var TxReader = class _TxReader { cachedLogs = /* @__PURE__ */ new Map(); blockManagerUnwatchers = /* @__PURE__ */ new Map(); logger; + config; networkManager; viemClientManager; blockManagerRegistry; - constructor(networkManager, viemClientManager, blockManagerRegistry) { + constructor(logger, networkManager, viemClientManager, blockManagerRegistry, config3) { this.networkManager = networkManager; this.viemClientManager = viemClientManager; this.blockManagerRegistry = blockManagerRegistry; - this.logger = Logger.getInstance().getLogger("TxReader"); + this.logger = logger; + this.config = config3; } - static createInstance(networkManager, viemClientManager, blockManagerRegistry) { - _TxReader.instance = new _TxReader(networkManager, viemClientManager, blockManagerRegistry); + static createInstance(logger, networkManager, viemClientManager, blockManagerRegistry, config3) { + _TxReader.instance = new _TxReader( + logger, + networkManager, + viemClientManager, + blockManagerRegistry, + config3 + ); return _TxReader.instance; } static getInstance() { @@ -63977,13 +64039,15 @@ var TxWriter = class _TxWriter { networkManager; viemClientManager; logger; - constructor(networkManager, viemClientManager) { + config; + constructor(logger, networkManager, viemClientManager, config3) { this.networkManager = networkManager; this.viemClientManager = viemClientManager; - this.logger = Logger.getInstance().getLogger("TxWriter"); + this.logger = logger; + this.config = config3; } - static createInstance(networkManager, viemClientManager) { - _TxWriter.instance = new _TxWriter(networkManager, viemClientManager); + static createInstance(logger, networkManager, viemClientManager, config3) { + _TxWriter.instance = new _TxWriter(logger, networkManager, viemClientManager, config3); return _TxWriter.instance; } static getInstance() { @@ -63996,9 +64060,9 @@ var TxWriter = class _TxWriter { this.logger.info("Initialized"); } async callContract(walletClient, publicClient, network, params) { - const txType = this.determineTxType(params); + const txType = await this.determineTxType(params); try { - if (globalConfig.TX_MANAGER.DRY_RUN) { + if (this.config.dryRun) { this.logger.info( `[DRY_RUN][${network.name}] Contract call: ${params.functionName}` ); @@ -64074,6 +64138,10 @@ var TxWriter = class _TxWriter { return tx.status !== "finalized" /* FINALIZED */; }); } + getTransactionsByMessageId(messageId) { + const allTxs = Array.from(this.transactions.values()); + return allTxs.filter((tx) => tx.messageId === messageId); + } dispose() { this.transactions.clear(); this.txByType.clear(); @@ -64221,13 +64289,15 @@ var ViemClientManager = class _ViemClientManager extends ManagerBase { clients = /* @__PURE__ */ new Map(); rpcManager; logger; - constructor(rpcManager) { + config; + constructor(logger, rpcManager, config3) { super(); this.rpcManager = rpcManager; - this.logger = Logger.getInstance().getLogger("ViemClientManager"); + this.logger = logger; + this.config = config3; } - static createInstance(rpcManager) { - _ViemClientManager.instance = new _ViemClientManager(rpcManager); + static createInstance(logger, rpcManager, config3) { + _ViemClientManager.instance = new _ViemClientManager(logger, rpcManager, config3); return _ViemClientManager.instance; } static getInstance() { @@ -64238,7 +64308,6 @@ var ViemClientManager = class _ViemClientManager extends ManagerBase { } async initialize() { if (this.initialized) return; - this.rpcManager.registerRpcUpdateListener(this); await super.initialize(); this.logger.debug("Initialized"); } @@ -64250,7 +64319,7 @@ var ViemClientManager = class _ViemClientManager extends ManagerBase { return fallback( rpcUrls.map((url2) => createCustomHttpTransport(url2)), { - ...globalConfig.VIEM.FALLBACK_TRANSPORT_OPTIONS, + ...this.config.fallbackTransportOptions, shouldThrow: (error) => { if (error instanceof HttpRequestError || error instanceof RpcRequestError || error instanceof TransactionNotFoundError || error instanceof UnknownRpcError || error instanceof UnknownNodeError || error instanceof InvalidInputRpcError || error instanceof MethodNotFoundRpcError || error instanceof TimeoutError || error instanceof MethodNotSupportedRpcError) { return false; @@ -64306,7 +64375,8 @@ var ViemClientManager = class _ViemClientManager extends ManagerBase { this.clients.set(chain.name, newClients); return newClients; } - onRpcUrlsUpdated(networks) { + // hook from NetworkManager + onNetworksUpdated(networks) { this.resetClientsForNetworks(networks); } resetClientsForNetworks(networks) { @@ -64319,8 +64389,6 @@ var ViemClientManager = class _ViemClientManager extends ManagerBase { } this.logger.debug(`Viem clients reset for ${networks.map((n) => n.name).join(", ")}`); } - onNetworksUpdated(networks) { - } async updateClientsForNetworks(networks) { for (const network of networks) { try { @@ -64333,9 +64401,6 @@ var ViemClientManager = class _ViemClientManager extends ManagerBase { } } dispose() { - if (this.rpcManager) { - this.rpcManager.unregisterRpcUpdateListener(this); - } this.clients.clear(); super.dispose(); _ViemClientManager.instance = void 0; @@ -64433,7 +64498,7 @@ async function waitForOperatorRegistration(network, contractAddress, fromBlockNu const viemClientManager = ViemClientManager.getInstance(); const { publicClient } = viemClientManager.getClients(network); const POLL_INTERVAL_MS = 3 * 1e3; - const MAX_RETRIES2 = 100; + const MAX_RETRIES = 100; const EVENT_NAME = "OperatorRegistered"; let retries = 0; logger.info( @@ -64441,7 +64506,7 @@ async function waitForOperatorRegistration(network, contractAddress, fromBlockNu ); return new Promise((resolve, reject) => { const checkForRegistrationEvent = async () => { - if (retries >= MAX_RETRIES2) { + if (retries >= MAX_RETRIES) { reject(new Error("Max retries reached while waiting for operator registration")); return; } @@ -64989,22 +65054,6 @@ export { }; /*! Bundled license information: -mime-db/index.js: - (*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015-2022 Douglas Christopher Wilson - * MIT Licensed - *) - -mime-types/index.js: - (*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - *) - safe-buffer/index.js: (*! safe-buffer. MIT License. Feross Aboukhadijeh *) @@ -65035,6 +65084,22 @@ file-stream-rotator/FileStreamRotator.js: @noble/curves/esm/secp256k1.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) +mime-db/index.js: + (*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + *) + +mime-types/index.js: + (*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + *) + axios/dist/node/axios.cjs: (*! Axios v1.9.0 Copyright (c) 2025 Matt Zabriskie and contributors *) diff --git a/src/common/managers/BlockManagerRegistry.ts b/src/common/managers/BlockManagerRegistry.ts index 2ea8dff..6550006 100644 --- a/src/common/managers/BlockManagerRegistry.ts +++ b/src/common/managers/BlockManagerRegistry.ts @@ -42,11 +42,14 @@ export class BlockManagerRegistry this.config = config; } - public onNetworksUpdated(networks: ConceroNetwork[]): void { + public async onNetworksUpdated(networks: ConceroNetwork[]): Promise { this.logger.info(`Networks updated, syncing BlockManagers for ${networks.length} networks`); - this.updateBlockManagers(networks).catch(error => { + try { + await this.updateBlockManagers(networks); + } catch (error) { this.logger.error("Failed to sync BlockManagers after network update", error); - }); + throw error; + } } private async ensureBlockManagerForNetwork( @@ -66,6 +69,7 @@ export class BlockManagerRegistry return blockManager; } catch (error) { this.logger.warn(`Failed to create BlockManager for network ${network.name}`, error); + return null; } } @@ -132,16 +136,8 @@ export class BlockManagerRegistry if (this.initialized) return; try { - // Register as a network update listener - this.networkManager.registerUpdateListener(this); - await super.initialize(); this.logger.debug("Initialized"); - - // Perform the initial sync of BlockManagers with active networks - const activeNetworks = this.networkManager.getActiveNetworks(); - this.logger.debug(`Starting initial sync for ${activeNetworks.length} networks`); - await this.updateBlockManagers(activeNetworks); } catch (error) { this.logger.error("Failed to initialize", error); throw error; diff --git a/src/common/managers/DeploymentManager.ts b/src/common/managers/DeploymentManager.ts index 1894976..d0864fd 100644 --- a/src/common/managers/DeploymentManager.ts +++ b/src/common/managers/DeploymentManager.ts @@ -1,5 +1,6 @@ import { Address } from "viem"; +import { ConceroNetwork } from "../../types/ConceroNetwork"; import { DeploymentManagerConfig } from "../../types/ManagerConfigs"; import { IDeploymentsManager, NetworkUpdateListener } from "../../types/managers"; import { getEnvVar } from "../utils/getEnvVar"; @@ -149,11 +150,14 @@ export class DeploymentManager } } - onNetworksUpdated() { + async onNetworksUpdated(networks: ConceroNetwork[]): Promise { // this.logger.debug("Received onNetworksUpdated"); - this.updateDeployments().catch(err => - this.logger.error("Failed to update deployments after network update:", err), - ); + try { + await this.updateDeployments(); + } catch (err) { + this.logger.error("Failed to update deployments after network update:", err); + throw err; + } } private extractNetworkName(key: string): string | null { diff --git a/src/common/managers/NetworkManager.ts b/src/common/managers/NetworkManager.ts index 801921a..0a09fec 100644 --- a/src/common/managers/NetworkManager.ts +++ b/src/common/managers/NetworkManager.ts @@ -222,23 +222,43 @@ export class NetworkManager extends ManagerBase implements INetworkManager { } if (networksFetched) { - this.notifyListeners(); + await this.notifyListeners(); } } catch (error) { this.logger.error("Failed to update networks:", error); } } - private notifyListeners(): void { + private async notifyListeners(): Promise { for (const listener of this.updateListeners) { try { - listener.onNetworksUpdated(this.activeNetworks); + await listener.onNetworksUpdated(this.activeNetworks); } catch (error) { this.logger.error("Error in network update listener:", error); } } } + public async triggerInitialUpdates(): Promise { + this.logger.debug("Triggering initial updates for all listeners sequentially"); + + for (const listener of this.updateListeners) { + try { + this.logger.debug(`Triggering initial update for ${listener.constructor.name}`); + await listener.onNetworksUpdated(this.activeNetworks); + this.logger.debug(`Completed initial update for ${listener.constructor.name}`); + } catch (error) { + this.logger.error( + `Error in initial update for ${listener.constructor.name}:`, + error, + ); + throw error; // Fail fast if initial updates fail + } + } + + this.logger.debug("Completed all initial updates"); + } + private createNetworkConfig( networks: Record, networkType: "mainnet" | "testnet" | "localhost", diff --git a/src/common/managers/RpcManager.ts b/src/common/managers/RpcManager.ts index 8f5f102..8380d56 100644 --- a/src/common/managers/RpcManager.ts +++ b/src/common/managers/RpcManager.ts @@ -1,6 +1,6 @@ import { ConceroNetwork } from "../../types/ConceroNetwork"; import { RpcManagerConfig } from "../../types/ManagerConfigs"; -import { IRpcManager, NetworkUpdateListener, RpcUpdateListener } from "../../types/managers"; +import { IRpcManager, NetworkUpdateListener } from "../../types/managers"; import { LoggerInterface } from "../utils/"; import { HttpClient } from "../utils/HttpClient"; import { ManagerBase } from "./ManagerBase"; @@ -29,7 +29,6 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat } private rpcUrls: Record = {}; - private rpcUpdateListeners: RpcUpdateListener[] = []; public static getInstance(): RpcManager { if (!RpcManager.instance) { @@ -45,19 +44,6 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat this.logger.debug("Initialized"); } - public registerRpcUpdateListener(listener: RpcUpdateListener): void { - if (!this.rpcUpdateListeners.includes(listener)) { - this.rpcUpdateListeners.push(listener); - } - } - - public unregisterRpcUpdateListener(listener: RpcUpdateListener): void { - const index = this.rpcUpdateListeners.indexOf(listener); - if (index !== -1) { - this.rpcUpdateListeners.splice(index, 1); - } - } - public async ensureRpcsForNetwork(network: ConceroNetwork): Promise { if (!this.rpcUrls[network.name] || this.rpcUrls[network.name].length === 0) { await this.updateRpcs([network]); @@ -72,25 +58,23 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat try { const url = `${this.config.conceroRpcsUrl}/${this.config.networkMode}.json`; - const response = await this.httpClient.get>(url); + const response = + await this.httpClient.get< + Record + >(url); if (!response) { throw new Error("Failed to fetch RPC data"); } - this.rpcUrls = response; - - // Get list of networks that were updated - const updatedNetworks: ConceroNetwork[] = Object.keys(response).map( - networkName => - ({ - name: networkName, - }) as ConceroNetwork, + // Extract just the rpcUrls from each network's data + this.rpcUrls = Object.fromEntries( + Object.entries(response).map(([networkName, data]) => [ + networkName, + data.rpcUrls || [], + ]), ); - // Notify listeners - this.notifyRpcUpdateListeners(updatedNetworks); - this.logger.debug(`Updated RPCs for ${Object.keys(response).length} networks`); } catch (error) { this.logger.error("Failed to update RPCs:", error); @@ -98,23 +82,16 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat } } - private notifyRpcUpdateListeners(networks: ConceroNetwork[]): void { - for (const listener of this.rpcUpdateListeners) { - try { - listener.onRpcUrlsUpdated(networks); - } catch (error) { - this.logger.error("Error in RPC update listener:", error); - } - } - } - public getRpcsForNetwork(networkName: string): string[] { return this.rpcUrls[networkName] || []; } - public onNetworksUpdated(networks: ConceroNetwork[]): void { - this.updateRpcs(networks).catch(err => - this.logger.error("Failed to update RPCs after network update:", err), - ); + public async onNetworksUpdated(networks: ConceroNetwork[]): Promise { + try { + await this.updateRpcs(networks); + } catch (err) { + this.logger.error("Failed to update RPCs after network update:", err); + throw err; + } } } diff --git a/src/common/managers/ViemClientManager.ts b/src/common/managers/ViemClientManager.ts index 8601a99..47bac6e 100644 --- a/src/common/managers/ViemClientManager.ts +++ b/src/common/managers/ViemClientManager.ts @@ -4,7 +4,7 @@ import type { PrivateKeyAccount } from "viem/accounts/types"; import { ConceroNetwork } from "../../types/ConceroNetwork"; import { ViemClientManagerConfig } from "../../types/ManagerConfigs"; -import { IRpcManager, NetworkUpdateListener, RpcUpdateListener } from "../../types/managers"; +import { IRpcManager, NetworkUpdateListener } from "../../types/managers"; import { createCustomHttpTransport, getEnvVar, LoggerInterface } from "../utils"; import { ManagerBase } from "./ManagerBase"; @@ -16,10 +16,7 @@ export interface ViemClients { account: PrivateKeyAccount; } // Creates & updates Viem Fallback Clients for each network -export class ViemClientManager - extends ManagerBase - implements RpcUpdateListener, NetworkUpdateListener -{ +export class ViemClientManager extends ManagerBase implements NetworkUpdateListener { private static instance: ViemClientManager; private clients: Map = new Map(); private rpcManager: IRpcManager; @@ -56,8 +53,6 @@ export class ViemClientManager public async initialize(): Promise { if (this.initialized) return; - // Register as RPC update listener - this.rpcManager.registerRpcUpdateListener(this); await super.initialize(); this.logger.debug("Initialized"); } @@ -124,14 +119,10 @@ export class ViemClientManager return newClients; } - // hook from RPCManager - public onRpcUrlsUpdated(networks: ConceroNetwork[]): void { - this.resetClientsForNetworks(networks); - } - // hook from NetworkManager public onNetworksUpdated(networks: ConceroNetwork[]): void { - // Networks updated, no action needed as clients are created on demand + // Reset clients as RPC URLs may have changed + this.resetClientsForNetworks(networks); } private resetClientsForNetworks(networks: ConceroNetwork[]): void { @@ -159,9 +150,6 @@ export class ViemClientManager } public override dispose(): void { - if (this.rpcManager) { - this.rpcManager.unregisterRpcUpdateListener(this); - } this.clients.clear(); super.dispose(); ViemClientManager.instance = undefined as any; diff --git a/src/common/utils/initializeManagers.ts b/src/common/utils/initializeManagers.ts index 5d13225..4fbf81c 100644 --- a/src/common/utils/initializeManagers.ts +++ b/src/common/utils/initializeManagers.ts @@ -134,6 +134,8 @@ export async function initializeManagers(): Promise { await rpcManager.initialize(); await viemClientManager.initialize(); await deploymentManager.initialize(); + await blockCheckpointManager.initialize(); + await blockManagerRegistry.initialize(); // Register network update listeners after all managers are initialized networkManager.registerUpdateListener(rpcManager); @@ -141,8 +143,10 @@ export async function initializeManagers(): Promise { networkManager.registerUpdateListener(viemClientManager); networkManager.registerUpdateListener(blockManagerRegistry); - await blockCheckpointManager.initialize(); - await blockManagerRegistry.initialize(); + // Trigger initial updates sequentially for all registered listeners + // This ensures each manager has the data it needs before the next one initializes + await networkManager.triggerInitialUpdates(); + const txWriter = TxWriter.createInstance( logger.getLogger("TxWriter"), networkManager, diff --git a/src/constants/globalConfig.ts b/src/constants/globalConfig.ts index 97d13c4..7260d66 100644 --- a/src/constants/globalConfig.ts +++ b/src/constants/globalConfig.ts @@ -47,7 +47,7 @@ const globalConfig: GlobalConfig = { HTTPCLIENT: { DEFAULT_TIMEOUT: 5000, MAX_RETRIES: 3, - RETRY_DELAY: 1000, + RETRY_DELAY: 100, }, ABI: { CONCERO_VERIFIER: conceroVerifierAbi as Abi, diff --git a/src/types/managers/INetworkManager.ts b/src/types/managers/INetworkManager.ts index 1f58dd9..a27fcee 100644 --- a/src/types/managers/INetworkManager.ts +++ b/src/types/managers/INetworkManager.ts @@ -14,6 +14,7 @@ export interface INetworkManager { getNetworkBySelector(selector: string): ConceroNetwork; getVerifierNetwork(): ConceroNetwork | undefined; forceUpdate(): Promise; + triggerInitialUpdates(): Promise; registerUpdateListener(listener: NetworkUpdateListener): void; unregisterUpdateListener(listener: NetworkUpdateListener): void; } diff --git a/src/types/managers/IRpcManager.ts b/src/types/managers/IRpcManager.ts index a1f1152..7ef3979 100644 --- a/src/types/managers/IRpcManager.ts +++ b/src/types/managers/IRpcManager.ts @@ -1,12 +1,8 @@ import { ConceroNetwork } from "../ConceroNetwork"; -import { RpcUpdateListener } from "./RpcUpdateListener"; - export interface IRpcManager { initialize(): Promise; ensureRpcsForNetwork(network: ConceroNetwork): Promise; updateRpcsForNetworks(networks: ConceroNetwork[]): Promise; - registerRpcUpdateListener(listener: RpcUpdateListener): void; - unregisterRpcUpdateListener(listener: RpcUpdateListener): void; getRpcsForNetwork(networkName: string): string[]; } diff --git a/src/types/managers/IViemClientManager.ts b/src/types/managers/IViemClientManager.ts index c52855f..fe5dcb8 100644 --- a/src/types/managers/IViemClientManager.ts +++ b/src/types/managers/IViemClientManager.ts @@ -2,9 +2,9 @@ import { ViemClients } from "../../common/managers/ViemClientManager"; import { ConceroNetwork } from "../ConceroNetwork"; -import { RpcUpdateListener } from "./RpcUpdateListener"; +import { NetworkUpdateListener } from "./NetworkUpdateListener"; -export interface IViemClientManager extends RpcUpdateListener { +export interface IViemClientManager extends NetworkUpdateListener { initialize(): Promise; getClients(chain: ConceroNetwork): ViemClients; updateClientsForNetworks(networks: ConceroNetwork[]): Promise; diff --git a/src/types/managers/NetworkUpdateListener.ts b/src/types/managers/NetworkUpdateListener.ts index 8a5cb2a..047aeb9 100644 --- a/src/types/managers/NetworkUpdateListener.ts +++ b/src/types/managers/NetworkUpdateListener.ts @@ -1,3 +1,3 @@ export interface NetworkUpdateListener { - onNetworksUpdated(networks: any[]): void; + onNetworksUpdated(networks: any[]): Promise | void; } diff --git a/src/types/managers/RpcUpdateListener.ts b/src/types/managers/RpcUpdateListener.ts deleted file mode 100644 index 29717fc..0000000 --- a/src/types/managers/RpcUpdateListener.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface RpcUpdateListener { - onRpcUrlsUpdated(networks: any[]): void; -} diff --git a/src/types/managers/index.ts b/src/types/managers/index.ts index 6dba9e7..991c2f7 100644 --- a/src/types/managers/index.ts +++ b/src/types/managers/index.ts @@ -8,4 +8,3 @@ export { ITxManager } from "./ITxManager"; export { ITxMonitor, MonitoredTransaction } from "./ITxMonitor"; export { IViemClientManager } from "./IViemClientManager"; export { NetworkUpdateListener } from "./NetworkUpdateListener"; -export { RpcUpdateListener } from "./RpcUpdateListener"; From ea34d74815fd9372cdda49c6566cea508c9caed5 Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 19 Jul 2025 14:45:45 +0100 Subject: [PATCH 03/11] upd --- src/common/utils/initializeManagers.ts | 115 ++++++++----------------- 1 file changed, 36 insertions(+), 79 deletions(-) diff --git a/src/common/utils/initializeManagers.ts b/src/common/utils/initializeManagers.ts index 4fbf81c..bda5676 100644 --- a/src/common/utils/initializeManagers.ts +++ b/src/common/utils/initializeManagers.ts @@ -13,20 +13,6 @@ import { } from "../managers"; import { globalConfig } from "../../constants"; -import { - BlockCheckpointManagerConfig, - BlockManagerConfig, - BlockManagerRegistryConfig, - DeploymentManagerConfig, - NetworkManagerConfig, - NonceManagerConfig, - RpcManagerConfig, - TxManagerConfig, - TxMonitorConfig, - TxReaderConfig, - TxWriterConfig, - ViemClientManagerConfig, -} from "../../types/ManagerConfigs"; import { HttpClient } from "./HttpClient"; import { Logger } from "./Logger"; @@ -50,75 +36,39 @@ export async function initializeManagers(): Promise { await httpClient.initialize(); - const blockCheckpointManagerConfig: BlockCheckpointManagerConfig = { - useCheckpoints: globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS, - }; - - const blockManagerConfig: BlockManagerConfig = { - pollingIntervalMs: globalConfig.BLOCK_MANAGER.POLLING_INTERVAL_MS, - catchupBatchSize: globalConfig.BLOCK_MANAGER.CATCHUP_BATCH_SIZE, - useCheckpoints: globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS, - }; - - const blockManagerRegistryConfig: BlockManagerRegistryConfig = { - blockManagerConfig, - }; - - const rpcManagerConfig: RpcManagerConfig = { + // Core infrastructure managers + const rpcManager = RpcManager.createInstance(logger.getLogger("RpcManager"), { rpcOverrides: globalConfig.RPC.OVERRIDE, rpcExtensions: globalConfig.RPC.EXTENSION, conceroRpcsUrl: globalConfig.URLS.CONCERO_RPCS, networkMode: globalConfig.NETWORK_MODE as "mainnet" | "testnet" | "localhost", - }; - - const viemClientManagerConfig: ViemClientManagerConfig = { - fallbackTransportOptions: globalConfig.VIEM.FALLBACK_TRANSPORT_OPTIONS, - }; - - const deploymentManagerConfig: DeploymentManagerConfig = { - conceroDeploymentsUrl: globalConfig.URLS.CONCERO_DEPLOYMENTS, - networkMode: globalConfig.NETWORK_MODE as "mainnet" | "testnet" | "localhost", - }; - - const networkManagerConfig: NetworkManagerConfig = { - networkUpdateIntervalMs: globalConfig.NETWORK_MANAGER.NETWORK_UPDATE_INTERVAL_MS, - networkMode: globalConfig.NETWORK_MODE as "mainnet" | "testnet" | "localhost", - ignoredNetworkIds: globalConfig.IGNORED_NETWORK_IDS, - whitelistedNetworkIds: globalConfig.WHITELISTED_NETWORK_IDS, - defaultConfirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS, - }; - - const txWriterConfig: TxWriterConfig = { - dryRun: globalConfig.TX_MANAGER.DRY_RUN, - }; - - const txReaderConfig: TxReaderConfig = {}; - const txMonitorConfig: TxMonitorConfig = {}; - - const txManagerConfig: TxManagerConfig = { - defaultConfirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS, - }; - - const nonceManagerConfig: NonceManagerConfig = {}; - - // Core infrastructure managers - const rpcManager = RpcManager.createInstance(logger.getLogger("RpcManager"), rpcManagerConfig); + }); const viemClientManager = ViemClientManager.createInstance( logger.getLogger("ViemClientManager"), rpcManager, - viemClientManagerConfig, + { + fallbackTransportOptions: globalConfig.VIEM.FALLBACK_TRANSPORT_OPTIONS, + }, ); const deploymentManager = DeploymentManager.createInstance( logger.getLogger("DeploymentManager"), - deploymentManagerConfig, - ); - const networkManager = NetworkManager.createInstance( - logger.getLogger("NetworkManager"), - networkManagerConfig, + { + conceroDeploymentsUrl: globalConfig.URLS.CONCERO_DEPLOYMENTS, + networkMode: globalConfig.NETWORK_MODE as "mainnet" | "testnet" | "localhost", + }, ); + const networkManager = NetworkManager.createInstance(logger.getLogger("NetworkManager"), { + networkUpdateIntervalMs: globalConfig.NETWORK_MANAGER.NETWORK_UPDATE_INTERVAL_MS, + networkMode: globalConfig.NETWORK_MODE as "mainnet" | "testnet" | "localhost", + ignoredNetworkIds: globalConfig.IGNORED_NETWORK_IDS, + whitelistedNetworkIds: globalConfig.WHITELISTED_NETWORK_IDS, + defaultConfirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS, + }); const blockCheckpointManager = BlockCheckpointManager.createInstance( logger.getLogger("BlockCheckpointManager"), - blockCheckpointManagerConfig, + { + useCheckpoints: globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS, + }, ); const blockManagerRegistry = BlockManagerRegistry.createInstance( @@ -127,7 +77,13 @@ export async function initializeManagers(): Promise { networkManager, viemClientManager, rpcManager, - blockManagerRegistryConfig, + { + blockManagerConfig: { + pollingIntervalMs: globalConfig.BLOCK_MANAGER.POLLING_INTERVAL_MS, + catchupBatchSize: globalConfig.BLOCK_MANAGER.CATCHUP_BATCH_SIZE, + useCheckpoints: globalConfig.BLOCK_MANAGER.USE_CHECKPOINTS, + }, + }, ); await networkManager.initialize(); @@ -151,14 +107,16 @@ export async function initializeManagers(): Promise { logger.getLogger("TxWriter"), networkManager, viemClientManager, - txWriterConfig, + { + dryRun: globalConfig.TX_MANAGER.DRY_RUN, + }, ); const txReader = TxReader.createInstance( logger.getLogger("TxReader"), networkManager, viemClientManager, blockManagerRegistry, - txReaderConfig, + {}, ); await txWriter.initialize(); @@ -169,7 +127,7 @@ export async function initializeManagers(): Promise { viemClientManager, (txHash, chainName) => txWriter.onTxFinality(txHash, chainName), (txHash, chainName) => txWriter.onTxReorg(txHash, chainName), - txMonitorConfig, + {}, ); const txManager = TxManager.createInstance( @@ -180,14 +138,13 @@ export async function initializeManagers(): Promise { txWriter, txReader, txMonitor, - txManagerConfig, + { + defaultConfirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS, + }, ); await txManager.initialize(); - const nonceManager = NonceManager.createInstance( - logger.getLogger("NonceManager"), - nonceManagerConfig, - ); + const nonceManager = NonceManager.createInstance(logger.getLogger("NonceManager"), {}); await nonceManager.initialize(); } From 03b263bfe77abe20dc35f10a934a2185040d80b2 Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 19 Jul 2025 15:05:22 +0100 Subject: [PATCH 04/11] upd --- src/common/managers/DeploymentManager.ts | 36 ++++++++++++++++------ src/common/managers/RpcManager.ts | 39 +++++++++++++++--------- src/common/managers/ViemClientManager.ts | 28 ++++++++--------- 3 files changed, 64 insertions(+), 39 deletions(-) diff --git a/src/common/managers/DeploymentManager.ts b/src/common/managers/DeploymentManager.ts index d0864fd..06e5d51 100644 --- a/src/common/managers/DeploymentManager.ts +++ b/src/common/managers/DeploymentManager.ts @@ -61,16 +61,12 @@ export class DeploymentManager } const router = this.conceroRoutersMapByChainName[chainName]; - if (router !== undefined) return router; - await this.updateDeployments(); - - const updatedRouter = this.conceroRoutersMapByChainName[chainName]; - if (!updatedRouter) { + if (!router) { throw new Error(`Router not found for chain: ${chainName}`); } - return updatedRouter; + return router; } async getConceroRouters(): Promise> { @@ -102,7 +98,7 @@ export class DeploymentManager return this.conceroVerifier; } - async updateDeployments(): Promise { + async updateDeployments(networks?: ConceroNetwork[]): Promise { const now = Date.now(); try { @@ -120,15 +116,35 @@ export class DeploymentManager const routerMap: Record = {} as Record; + // If networks are provided, create a set for efficient lookup + const activeNetworkNames = networks ? new Set(networks.map(n => n.name)) : null; + + // Remove deployments for networks that are no longer active + if (activeNetworkNames) { + const currentNetworkNames = Object.keys(this.conceroRoutersMapByChainName); + for (const networkName of currentNetworkNames) { + if (!activeNetworkNames.has(networkName)) { + delete this.conceroRoutersMapByChainName[networkName]; + this.logger.debug( + `Removed deployment for inactive network: ${networkName}`, + ); + } + } + } + for (const deploymentEnv of conceroRouterDeploymentsEnv) { const [name, address] = deploymentEnv.split("="); const networkName = this.extractNetworkName(name); if (networkName) { - routerMap[networkName as string] = address as Address; + // If networks are provided, only store deployments for active networks + if (!activeNetworkNames || activeNetworkNames.has(networkName)) { + routerMap[networkName as string] = address as Address; + } } } - this.conceroRoutersMapByChainName = routerMap; + // Update the deployments + Object.assign(this.conceroRoutersMapByChainName, routerMap); const verifierEntry = deploymentsEnvArr.find((d: string) => { const networkSuffix = @@ -153,7 +169,7 @@ export class DeploymentManager async onNetworksUpdated(networks: ConceroNetwork[]): Promise { // this.logger.debug("Received onNetworksUpdated"); try { - await this.updateDeployments(); + await this.updateDeployments(networks); } catch (err) { this.logger.error("Failed to update deployments after network update:", err); throw err; diff --git a/src/common/managers/RpcManager.ts b/src/common/managers/RpcManager.ts index 8380d56..a977d9a 100644 --- a/src/common/managers/RpcManager.ts +++ b/src/common/managers/RpcManager.ts @@ -11,14 +11,11 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat private httpClient: HttpClient; private logger: LoggerInterface; private config: RpcManagerConfig; + private rpcUrls: Record = {}; constructor(logger: LoggerInterface, config: RpcManagerConfig) { super(); - this.httpClient = HttpClient.getInstance(logger, { - retryDelay: 1000, - maxRetries: 3, - defaultTimeout: 10000, - }); + this.httpClient = HttpClient.getInstance(); this.logger = logger; this.config = config; } @@ -28,8 +25,6 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat return RpcManager.instance; } - private rpcUrls: Record = {}; - public static getInstance(): RpcManager { if (!RpcManager.instance) { throw new Error("RpcManager is not initialized. Call createInstance() first."); @@ -67,15 +62,29 @@ export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdat throw new Error("Failed to fetch RPC data"); } - // Extract just the rpcUrls from each network's data - this.rpcUrls = Object.fromEntries( - Object.entries(response).map(([networkName, data]) => [ - networkName, - data.rpcUrls || [], - ]), - ); + // Create a set of active network names for efficient lookup + const activeNetworkNames = new Set(networks.map(n => n.name)); + + // Remove RPCs for networks that are no longer active + const currentNetworkNames = Object.keys(this.rpcUrls); + for (const networkName of currentNetworkNames) { + if (!activeNetworkNames.has(networkName)) { + delete this.rpcUrls[networkName]; + this.logger.debug(`Removed RPCs for inactive network: ${networkName}`); + } + } + + // Only store RPCs for active networks + const activeNetworkRpcs = Object.entries(response) + .filter(([networkName]) => activeNetworkNames.has(networkName)) + .map(([networkName, data]) => [networkName, data.rpcUrls || []]); + + // Update RPCs for active networks + for (const [networkName, rpcUrls] of activeNetworkRpcs) { + this.rpcUrls[networkName] = rpcUrls as string[]; + } - this.logger.debug(`Updated RPCs for ${Object.keys(response).length} networks`); + this.logger.debug(`Updated RPCs for ${activeNetworkRpcs.length} active networks`); } catch (error) { this.logger.error("Failed to update RPCs:", error); throw error; diff --git a/src/common/managers/ViemClientManager.ts b/src/common/managers/ViemClientManager.ts index 47bac6e..95b2fbd 100644 --- a/src/common/managers/ViemClientManager.ts +++ b/src/common/managers/ViemClientManager.ts @@ -120,28 +120,28 @@ export class ViemClientManager extends ManagerBase implements NetworkUpdateListe } // hook from NetworkManager - public onNetworksUpdated(networks: ConceroNetwork[]): void { - // Reset clients as RPC URLs may have changed - this.resetClientsForNetworks(networks); - } - - private resetClientsForNetworks(networks: ConceroNetwork[]): void { - for (const network of networks) { - try { - this.clients.delete(network.name); - } catch (error) { - this.logger.error(`Failed to update viem clients for ${network.name}:`, error); + public async onNetworksUpdated(networks: ConceroNetwork[]): Promise { + // Create a set of active network names for efficient lookup + const activeNetworkNames = new Set(networks.map(n => n.name)); + + // Remove clients for networks that are no longer active + const currentNetworkNames = Array.from(this.clients.keys()); + for (const networkName of currentNetworkNames) { + if (!activeNetworkNames.has(networkName)) { + this.clients.delete(networkName); + this.logger.debug(`Removed clients for inactive network: ${networkName}`); } } - this.logger.debug(`Viem clients reset for ${networks.map(n => n.name).join(", ")}`); + // Update clients for active networks + await this.updateClientsForNetworks(networks); } public async updateClientsForNetworks(networks: ConceroNetwork[]): Promise { for (const network of networks) { try { - const newClients = this.initializeClients(network); - this.clients.set(network.name, newClients); + const newClient = this.initializeClients(network); + this.clients.set(network.name, newClient); this.logger.debug(`Updated clients for chain ${network.name}`); } catch (error) { this.logger.error(`Failed to update clients for chain ${network.name}`, error); From 86e0e8f30d4579b7b80cbadbf033b6fd1a52f75e Mon Sep 17 00:00:00 2001 From: Oleg Date: Sat, 19 Jul 2025 15:13:01 +0100 Subject: [PATCH 05/11] upd --- src/constants/globalConfig.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/constants/globalConfig.ts b/src/constants/globalConfig.ts index 7260d66..d7b741b 100644 --- a/src/constants/globalConfig.ts +++ b/src/constants/globalConfig.ts @@ -40,7 +40,7 @@ const globalConfig: GlobalConfig = { WRITE_CONTRACT: {}, FALLBACK_TRANSPORT_OPTIONS: { retryCount: 5, - retryDelay: 2000, + retryDelay: 150, }, SIMULATE_TX: getEnvVar("SIMULATE_TX") === "true", }, From 988fa0a98be16bb16206d8d44566e0d67be56048 Mon Sep 17 00:00:00 2001 From: Oleg Date: Sun, 20 Jul 2025 17:17:59 +0100 Subject: [PATCH 06/11] interfaces updates --- src/common/managers/BlockManagerRegistry.ts | 33 ++++++++++--------- src/common/managers/NonceManager.ts | 23 ++----------- src/common/managers/TxManager.ts | 29 +++++++++-------- src/common/managers/TxMonitor.ts | 10 +++--- src/common/managers/TxReader.ts | 36 +++++++++------------ src/common/managers/TxWriter.ts | 16 ++++----- src/types/managers/IDbManager.ts | 11 +++++++ src/types/managers/INonceManager.ts | 19 +++++++++++ src/types/managers/index.ts | 3 ++ 9 files changed, 97 insertions(+), 83 deletions(-) create mode 100644 src/types/managers/IDbManager.ts create mode 100644 src/types/managers/INonceManager.ts diff --git a/src/common/managers/BlockManagerRegistry.ts b/src/common/managers/BlockManagerRegistry.ts index 6550006..e1af8ed 100644 --- a/src/common/managers/BlockManagerRegistry.ts +++ b/src/common/managers/BlockManagerRegistry.ts @@ -2,15 +2,18 @@ import { PublicClient } from "viem"; import { ConceroNetwork } from "../../types/ConceroNetwork"; import { BlockManagerRegistryConfig } from "../../types/ManagerConfigs"; -import { IBlockManagerRegistry, NetworkUpdateListener } from "../../types/managers/"; +import { + IBlockCheckpointManager, + IBlockManagerRegistry, + INetworkManager, + IRpcManager, + IViemClientManager, + NetworkUpdateListener, +} from "../../types/managers/"; import { LoggerInterface } from "../utils/"; -import { IBlockCheckpointManager } from "../../types/managers"; import { BlockManager } from "./BlockManager"; import { ManagerBase } from "./ManagerBase"; -import { NetworkManager } from "./NetworkManager"; -import { RpcManager } from "./RpcManager"; -import { ViemClientManager } from "./ViemClientManager"; export class BlockManagerRegistry extends ManagerBase @@ -19,18 +22,18 @@ export class BlockManagerRegistry private static instance: BlockManagerRegistry; private blockManagers: Map = new Map(); private blockCheckpointManager: IBlockCheckpointManager; - private networkManager: NetworkManager; - private viemClientManager: ViemClientManager; - private rpcManager: RpcManager; + private networkManager: INetworkManager; + private viemClientManager: IViemClientManager; + private rpcManager: IRpcManager; private logger: LoggerInterface; private config: BlockManagerRegistryConfig; private constructor( logger: LoggerInterface, blockCheckpointManager: IBlockCheckpointManager, - networkManager: NetworkManager, - viemClientManager: ViemClientManager, - rpcManager: RpcManager, + networkManager: INetworkManager, + viemClientManager: IViemClientManager, + rpcManager: IRpcManager, config: BlockManagerRegistryConfig, ) { super(); @@ -107,9 +110,9 @@ export class BlockManagerRegistry public static createInstance( logger: LoggerInterface, blockCheckpointManager: IBlockCheckpointManager, - networkManager: NetworkManager, - viemClientManager: ViemClientManager, - rpcManager: RpcManager, + networkManager: INetworkManager, + viemClientManager: IViemClientManager, + rpcManager: IRpcManager, config: BlockManagerRegistryConfig, ): BlockManagerRegistry { BlockManagerRegistry.instance = new BlockManagerRegistry( @@ -176,7 +179,7 @@ export class BlockManagerRegistry } this.logger.warn(`BlockManager for ${networkName} not found`); - return null; + return undefined; } public getAllBlockManagers(): BlockManager[] { diff --git a/src/common/managers/NonceManager.ts b/src/common/managers/NonceManager.ts index 1d9a6a9..e64faca 100644 --- a/src/common/managers/NonceManager.ts +++ b/src/common/managers/NonceManager.ts @@ -1,20 +1,11 @@ import { Mutex } from "async-mutex"; -import { Address, Client, createPublicClient } from "viem"; import { NonceManagerConfig } from "../../types/ManagerConfigs"; +import { IGetNonceParams, INonceManager, INonceManagerParams } from "../../types/managers"; import { LoggerInterface } from "../utils/Logger"; import { ManagerBase } from "./ManagerBase"; -interface INonceManagerParams { - address: Address; - chainId: number; -} - -interface IGetNonceParams extends INonceManagerParams { - client: Client; -} - -export class NonceManager extends ManagerBase { +export class NonceManager extends ManagerBase implements INonceManager { private static instance: NonceManager | null = null; private noncesMap: Record = {}; private mutexMap: Record = {}; @@ -80,8 +71,7 @@ export class NonceManager extends ManagerBase { } private async fetchNonce(params: IGetNonceParams) { - const publicClient = this.createPublicCLientFromGetNonceParams(params); - return await publicClient.getTransactionCount({ address: params.address }); + return await params.client.getTransactionCount({ address: params.address }); } private getMutex(chainId: number): Mutex { @@ -90,11 +80,4 @@ export class NonceManager extends ManagerBase { } return this.mutexMap[chainId]; } - - private createPublicCLientFromGetNonceParams(params: IGetNonceParams) { - return createPublicClient({ - transport: () => params.client.transport, - chain: params.client.chain, - }); - } } diff --git a/src/common/managers/TxManager.ts b/src/common/managers/TxManager.ts index 08d9aab..9ae1a39 100644 --- a/src/common/managers/TxManager.ts +++ b/src/common/managers/TxManager.ts @@ -9,15 +9,18 @@ import { import { ConceroNetwork } from "../../types/ConceroNetwork"; import { TxManagerConfig } from "../../types/ManagerConfigs"; -import { ITxManager, ITxMonitor } from "../../types/managers"; +import { + IBlockManagerRegistry, + INetworkManager, + ITxManager, + ITxMonitor, + IViemClientManager, +} from "../../types/managers"; import { ITxReader, LogQuery } from "../../types/managers/ITxReader"; import { ITxWriter, ManagedTx } from "../../types/managers/ITxWriter"; import { LoggerInterface } from "../utils/"; -import { BlockManagerRegistry } from "./BlockManagerRegistry"; import { ManagerBase } from "./ManagerBase"; -import { NetworkManager } from "./NetworkManager"; -import { ViemClientManager } from "./ViemClientManager"; // High-level interface for both reading & writing to the network export class TxManager extends ManagerBase implements ITxManager { @@ -26,17 +29,17 @@ export class TxManager extends ManagerBase implements ITxManager { private readonly txWriter: ITxWriter; private readonly txReader: ITxReader; private readonly txMonitor: ITxMonitor; - private readonly networkManager: NetworkManager; - private readonly viemClientManager: ViemClientManager; - private readonly blockManagerRegistry: BlockManagerRegistry; + private readonly networkManager: INetworkManager; + private readonly viemClientManager: IViemClientManager; + private readonly blockManagerRegistry: IBlockManagerRegistry; private logger: LoggerInterface; private config: TxManagerConfig; private constructor( logger: LoggerInterface, - networkManager: NetworkManager, - viemClientManager: ViemClientManager, - blockManagerRegistry: BlockManagerRegistry, + networkManager: INetworkManager, + viemClientManager: IViemClientManager, + blockManagerRegistry: IBlockManagerRegistry, txWriter: ITxWriter, txReader: ITxReader, txMonitor: ITxMonitor, @@ -55,9 +58,9 @@ export class TxManager extends ManagerBase implements ITxManager { public static createInstance( logger: LoggerInterface, - networkManager: NetworkManager, - viemClientManager: ViemClientManager, - blockManagerRegistry: BlockManagerRegistry, + networkManager: INetworkManager, + viemClientManager: IViemClientManager, + blockManagerRegistry: IBlockManagerRegistry, txWriter: ITxWriter, txReader: ITxReader, txMonitor: ITxMonitor, diff --git a/src/common/managers/TxMonitor.ts b/src/common/managers/TxMonitor.ts index ee61b5b..1f96c49 100644 --- a/src/common/managers/TxMonitor.ts +++ b/src/common/managers/TxMonitor.ts @@ -1,11 +1,9 @@ import { ConceroNetwork } from "../../types/ConceroNetwork"; import { TxMonitorConfig } from "../../types/ManagerConfigs"; -import { ITxMonitor, MonitoredTransaction } from "../../types/managers"; +import { ITxMonitor, IViemClientManager, MonitoredTransaction } from "../../types/managers"; import { ManagedTx } from "../../types/managers/ITxWriter"; import { LoggerInterface } from "../utils"; -import { ViemClientManager } from "./ViemClientManager"; - enum TransactionStatus { Pending = "pending", Confirmed = "confirmed", @@ -18,7 +16,7 @@ enum TransactionStatus { export class TxMonitor implements ITxMonitor { private static instance: TxMonitor | undefined; private transactions: Map = new Map(); - private viemClientManager: ViemClientManager; + private viemClientManager: IViemClientManager; private disposed: boolean = false; private txFinalityCallback: (txHash: string, chainName: string) => void; private txReorgCallback: (txHash: string, chainName: string) => Promise; @@ -26,7 +24,7 @@ export class TxMonitor implements ITxMonitor { constructor( logger: LoggerInterface, - viemClientManager: ViemClientManager, + viemClientManager: IViemClientManager, txFinalityCallback: (txHash: string, chainName: string) => void, txReorgCallback: (txHash: string, chainName: string) => Promise, config: TxMonitorConfig, @@ -40,7 +38,7 @@ export class TxMonitor implements ITxMonitor { public static createInstance( logger: LoggerInterface, - viemClientManager: ViemClientManager, + viemClientManager: IViemClientManager, txFinalityCallback: (txHash: string, chainName: string) => void, txReorgCallback: (txHash: string, chainName: string) => Promise, config: TxMonitorConfig, diff --git a/src/common/managers/TxReader.ts b/src/common/managers/TxReader.ts index 25c2fbe..40c7c81 100644 --- a/src/common/managers/TxReader.ts +++ b/src/common/managers/TxReader.ts @@ -4,13 +4,10 @@ import { v4 as uuidv4 } from "uuid"; import { ConceroNetwork } from "../../types/ConceroNetwork"; import { TxReaderConfig } from "../../types/ManagerConfigs"; +import { IBlockManagerRegistry, INetworkManager, IViemClientManager } from "../../types/managers"; import { ITxReader, LogQuery, LogWatcher } from "../../types/managers/ITxReader"; import { LoggerInterface } from "../utils"; -import { BlockManagerRegistry } from "./BlockManagerRegistry"; -import { NetworkManager } from "./NetworkManager"; -import { ViemClientManager } from "./ViemClientManager"; - // Handles all log-reading operations for all networks export class TxReader implements ITxReader { private static instance: TxReader | undefined; @@ -20,15 +17,15 @@ export class TxReader implements ITxReader { private logger: LoggerInterface; private config: TxReaderConfig; - private networkManager: NetworkManager; - private viemClientManager: ViemClientManager; - private blockManagerRegistry: BlockManagerRegistry; + private networkManager: INetworkManager; + private viemClientManager: IViemClientManager; + private blockManagerRegistry: IBlockManagerRegistry; private constructor( logger: LoggerInterface, - networkManager: NetworkManager, - viemClientManager: ViemClientManager, - blockManagerRegistry: BlockManagerRegistry, + networkManager: INetworkManager, + viemClientManager: IViemClientManager, + blockManagerRegistry: IBlockManagerRegistry, config: TxReaderConfig, ) { this.networkManager = networkManager; @@ -40,9 +37,9 @@ export class TxReader implements ITxReader { public static createInstance( logger: LoggerInterface, - networkManager: NetworkManager, - viemClientManager: ViemClientManager, - blockManagerRegistry: BlockManagerRegistry, + networkManager: INetworkManager, + viemClientManager: IViemClientManager, + blockManagerRegistry: IBlockManagerRegistry, config: TxReaderConfig, ): TxReader { TxReader.instance = new TxReader( @@ -78,7 +75,7 @@ export class TxReader implements ITxReader { } const unwatcher = blockManager.watchBlocks({ - onBlockRange: async (startBlock, endBlock) => { + onBlockRange: async (startBlock: bigint, endBlock: bigint) => { await this.fetchLogsForWatchers(network.name, startBlock, endBlock); }, }); @@ -148,7 +145,9 @@ export class TxReader implements ITxReader { for (const [contractAddress, contractWatchers] of watchersByContract) { try { - const events = contractWatchers.map(w => w.event); + const events = contractWatchers + .map(w => w.event) + .filter((event): event is AbiEvent => event !== undefined); const logs = await this.getContractLogs( contractAddress, fromBlock, @@ -161,7 +160,7 @@ export class TxReader implements ITxReader { const logsByEvent = new Map(); for (const log of logs) { - const eventName = log.eventName || ""; + const eventName = (log as any).eventName || ""; const logId = `${log.transactionHash}:${log.logIndex}`; // Skip logs we've already seen @@ -253,12 +252,9 @@ export class TxReader implements ITxReader { fromBlock: query.fromBlock, toBlock: query.toBlock, event: query.event, + ...(query.args && { args: query.args }), }; - if (query.args) { - filter.args = query.args; - } - const logs = await publicClient.getLogs(filter); // console.log(query, logs); diff --git a/src/common/managers/TxWriter.ts b/src/common/managers/TxWriter.ts index 697e1f2..187b075 100644 --- a/src/common/managers/TxWriter.ts +++ b/src/common/managers/TxWriter.ts @@ -4,12 +4,10 @@ import { v4 as uuidv4 } from "uuid"; import { ConceroNetwork } from "../../types/ConceroNetwork"; import { TxWriterConfig } from "../../types/ManagerConfigs"; +import { INetworkManager, IViemClientManager } from "../../types/managers"; import { ITxWriter, ManagedTx, TxSubmissionParams } from "../../types/managers/ITxWriter"; import { callContract, LoggerInterface } from "../utils"; -import { NetworkManager } from "./NetworkManager"; -import { ViemClientManager } from "./ViemClientManager"; - enum TxType { DEFAULT = "default", MESSAGE = "message", @@ -35,15 +33,15 @@ export class TxWriter implements ITxWriter { [TxType.ADMIN, new Set()], ]); - private networkManager: NetworkManager; - private viemClientManager: ViemClientManager; + private networkManager: INetworkManager; + private viemClientManager: IViemClientManager; private logger: LoggerInterface; private config: TxWriterConfig; private constructor( logger: LoggerInterface, - networkManager: NetworkManager, - viemClientManager: ViemClientManager, + networkManager: INetworkManager, + viemClientManager: IViemClientManager, config: TxWriterConfig, ) { this.networkManager = networkManager; @@ -54,8 +52,8 @@ export class TxWriter implements ITxWriter { public static createInstance( logger: LoggerInterface, - networkManager: NetworkManager, - viemClientManager: ViemClientManager, + networkManager: INetworkManager, + viemClientManager: IViemClientManager, config: TxWriterConfig, ): TxWriter { TxWriter.instance = new TxWriter(logger, networkManager, viemClientManager, config); diff --git a/src/types/managers/IDbManager.ts b/src/types/managers/IDbManager.ts new file mode 100644 index 0000000..c88a034 --- /dev/null +++ b/src/types/managers/IDbManager.ts @@ -0,0 +1,11 @@ +import { PrismaClient } from "@prisma/client"; + +/** + * Interface for database management operations. + * Note: The current implementation uses static methods, but this interface + * represents the contract for database operations. + */ +export interface IDbManager { + getClient(): PrismaClient; + disconnect(): Promise; +} diff --git a/src/types/managers/INonceManager.ts b/src/types/managers/INonceManager.ts new file mode 100644 index 0000000..45a050d --- /dev/null +++ b/src/types/managers/INonceManager.ts @@ -0,0 +1,19 @@ +import { Address, PublicClient } from "viem"; + +export interface INonceManagerParams { + address: Address; + chainId: number; +} + +export interface IGetNonceParams extends INonceManagerParams { + client: PublicClient; +} + +export interface INonceManager { + get(params: IGetNonceParams): Promise; + consume(params: IGetNonceParams): Promise; + reset(params: INonceManagerParams): void; + set(params: INonceManagerParams, nonce: number): void; + initialize(): Promise; + dispose(): void; +} diff --git a/src/types/managers/index.ts b/src/types/managers/index.ts index 991c2f7..3dfe2b8 100644 --- a/src/types/managers/index.ts +++ b/src/types/managers/index.ts @@ -3,8 +3,11 @@ export { IBlockManager } from "./IBlockManager"; export { IBlockManagerRegistry } from "./IBlockManagerRegistry"; export { IDeploymentsManager } from "./IDeploymentsManager"; export { INetworkManager } from "./INetworkManager"; +export { IGetNonceParams, INonceManager, INonceManagerParams } from "./INonceManager"; export { IRpcManager } from "./IRpcManager"; export { ITxManager } from "./ITxManager"; export { ITxMonitor, MonitoredTransaction } from "./ITxMonitor"; +export { ITxReader, LogQuery, LogWatcher } from "./ITxReader"; +export { ITxWriter, ManagedTx, TxSubmissionParams } from "./ITxWriter"; export { IViemClientManager } from "./IViemClientManager"; export { NetworkUpdateListener } from "./NetworkUpdateListener"; From bfb90c8815e0dea6ab1a5d34e8fa08fb9d983a8b Mon Sep 17 00:00:00 2001 From: Oleg Date: Sun, 20 Jul 2025 19:43:11 +0100 Subject: [PATCH 07/11] upd --- src/common/managers/NetworkManager.ts | 6 +++++- src/common/managers/Singleton.ts | 13 ------------- src/common/managers/index.ts | 1 - src/common/utils/Logger.ts | 2 +- src/common/utils/fetchNetworkConfigs.ts | 16 +++++++++------- src/common/utils/initializeManagers.ts | 1 + src/types/ManagerConfigs.ts | 1 + 7 files changed, 17 insertions(+), 23 deletions(-) delete mode 100644 src/common/managers/Singleton.ts diff --git a/src/common/managers/NetworkManager.ts b/src/common/managers/NetworkManager.ts index 0a09fec..88b6961 100644 --- a/src/common/managers/NetworkManager.ts +++ b/src/common/managers/NetworkManager.ts @@ -1,3 +1,4 @@ +import { globalConfig } from "../../constants"; import { ConceroNetwork } from "../../types/ConceroNetwork"; import { NetworkManagerConfig } from "../../types/ManagerConfigs"; import { INetworkManager, NetworkUpdateListener } from "../../types/managers"; @@ -171,7 +172,10 @@ export class NetworkManager extends ManagerBase implements INetworkManager { } else { try { const { mainnetNetworks: fetchedMainnet, testnetNetworks: fetchedTestnet } = - await fetchNetworkConfigs(this.config.networkMode); + await fetchNetworkConfigs(this.config.networkMode, { + mainnet: globalConfig.URLS.V2_NETWORKS.MAINNET, + testnet: globalConfig.URLS.V2_NETWORKS.TESTNET, + }); const hasMainnetNetworks = Object.keys(fetchedMainnet).length > 0; const hasTestnetNetworks = Object.keys(fetchedTestnet).length > 0; diff --git a/src/common/managers/Singleton.ts b/src/common/managers/Singleton.ts deleted file mode 100644 index 29d02de..0000000 --- a/src/common/managers/Singleton.ts +++ /dev/null @@ -1,13 +0,0 @@ -export abstract class Singleton { - protected constructor() {} - - public static getInstance( - this: (new (...args: any[]) => T) & { instance?: any }, - ...args: any[] - ): T { - if (!this.instance) { - this.instance = new this(...args); - } - return this.instance; - } -} diff --git a/src/common/managers/index.ts b/src/common/managers/index.ts index 53d1245..a645118 100644 --- a/src/common/managers/index.ts +++ b/src/common/managers/index.ts @@ -8,7 +8,6 @@ export { ManagerBase } from "./ManagerBase"; export { NetworkManager } from "./NetworkManager"; export { NonceManager } from "./NonceManager"; export { RpcManager } from "./RpcManager"; -export { Singleton } from "./Singleton"; export { TxManager } from "./TxManager"; export { TxMonitor } from "./TxMonitor"; export { TxReader } from "./TxReader"; diff --git a/src/common/utils/Logger.ts b/src/common/utils/Logger.ts index 7cfa857..1d31280 100644 --- a/src/common/utils/Logger.ts +++ b/src/common/utils/Logger.ts @@ -77,7 +77,7 @@ export class Logger extends ManagerBase { ], }); - if (process.env.NODE_ENV !== "production") { + if (this.config.enableConsoleTransport) { logger.add( new winston.transports.Console({ level: "debug", diff --git a/src/common/utils/fetchNetworkConfigs.ts b/src/common/utils/fetchNetworkConfigs.ts index 95b805f..1cffaa9 100644 --- a/src/common/utils/fetchNetworkConfigs.ts +++ b/src/common/utils/fetchNetworkConfigs.ts @@ -1,9 +1,8 @@ -import { globalConfig } from "../../constants"; import { ChainDefinition, createViemChain } from "./createViemChain"; import { HttpClient } from "./HttpClient"; import { Logger } from "./Logger"; -export interface NetworkDetail { +export interface V2Network { name: string; chainId: number; chainSelector: number; @@ -35,6 +34,7 @@ export interface NetworkConfigs { export async function fetchNetworkConfigs( networkMode: "mainnet" | "testnet" | "localhost" = "testnet", + urls?: { mainnet: string; testnet: string }, ): Promise { const logger = Logger.getInstance().getLogger("NetworkConfig"); const httpClient = HttpClient.getInstance(); @@ -49,16 +49,18 @@ export async function fetchNetworkConfigs( } if (networkMode === "mainnet") { - const mainnetData = await httpClient.get(globalConfig.URLS.V2_NETWORKS.MAINNET); + if (!urls?.mainnet) throw new Error("Mainnet URL is required"); + const mainnetData = await httpClient.get(urls.mainnet); mainnetNetworks = processNetworkData( - mainnetData as Record, + mainnetData as Record, false, logger, ); } else if (networkMode === "testnet") { - const testnetData = await httpClient.get(globalConfig.URLS.V2_NETWORKS.TESTNET); + if (!urls?.testnet) throw new Error("Testnet URL is required"); + const testnetData = await httpClient.get(urls.testnet); testnetNetworks = processNetworkData( - testnetData as Record, + testnetData as Record, true, logger, ); @@ -75,7 +77,7 @@ export async function fetchNetworkConfigs( } function processNetworkData( - networkData: Record, + networkData: Record, isTestnet: boolean, logger: ReturnType, ): Record { diff --git a/src/common/utils/initializeManagers.ts b/src/common/utils/initializeManagers.ts index bda5676..952efaa 100644 --- a/src/common/utils/initializeManagers.ts +++ b/src/common/utils/initializeManagers.ts @@ -24,6 +24,7 @@ export async function initializeManagers(): Promise { logMaxFiles: globalConfig.LOGGER.LOG_MAX_FILES, logLevelDefault: globalConfig.LOGGER.LOG_LEVEL_DEFAULT, logLevelsGranular: globalConfig.LOGGER.LOG_LEVELS_GRANULAR, + enableConsoleTransport: process.env.NODE_ENV !== "production", }); await logger.initialize(); diff --git a/src/types/ManagerConfigs.ts b/src/types/ManagerConfigs.ts index c0aa3ba..5d46837 100644 --- a/src/types/ManagerConfigs.ts +++ b/src/types/ManagerConfigs.ts @@ -84,6 +84,7 @@ export interface LoggerConfig extends BaseManagerConfig { logMaxFiles: string | number; logLevelDefault: string; logLevelsGranular: Record; + enableConsoleTransport?: boolean; } /** Configuration for HttpClient */ From 44f50fbf56b00594da2dac30f044989cd5a70ecd Mon Sep 17 00:00:00 2001 From: Oleg Date: Sun, 20 Jul 2025 21:55:56 +0100 Subject: [PATCH 08/11] upd --- bun.lock | 45 ++- package.json | 4 +- .../eventListener/setupEventListener.ts | 2 +- src/common/managers/BlockManagerRegistry.ts | 220 ------------ src/common/managers/DeploymentManager.ts | 200 ----------- src/common/managers/NetworkManager.ts | 340 ------------------ src/common/managers/NonceManager.ts | 83 ----- src/common/managers/RpcManager.ts | 106 ------ src/common/managers/ViemClientManager.ts | 158 -------- src/common/managers/index.ts | 9 +- src/common/utils/HttpClient.ts | 131 ------- src/common/utils/Logger.ts | 176 --------- src/common/utils/asyncRetry.ts | 3 +- src/common/utils/callContract.ts | 2 +- src/common/utils/checkGas.ts | 5 +- src/common/utils/customHttpTransport.ts | 2 +- src/common/utils/fetchNetworkConfigs.ts | 116 ------ src/common/utils/index.ts | 2 - src/common/utils/initializeManagers.ts | 33 +- src/relayer-a/businessLogic/ensureDeposit.ts | 8 +- .../ensureOperatorIsRegistered.ts | 9 +- .../businessLogic/requestCLFMessageReport.ts | 8 +- .../businessLogic/submitCLFMessageReport.ts | 8 +- .../eventListener/setupEventListeners.ts | 3 +- src/relayer-a/index.ts | 2 +- 25 files changed, 83 insertions(+), 1592 deletions(-) delete mode 100644 src/common/managers/BlockManagerRegistry.ts delete mode 100644 src/common/managers/DeploymentManager.ts delete mode 100644 src/common/managers/NetworkManager.ts delete mode 100644 src/common/managers/NonceManager.ts delete mode 100644 src/common/managers/RpcManager.ts delete mode 100644 src/common/managers/ViemClientManager.ts delete mode 100644 src/common/utils/HttpClient.ts delete mode 100644 src/common/utils/Logger.ts delete mode 100644 src/common/utils/fetchNetworkConfigs.ts diff --git a/bun.lock b/bun.lock index c504b85..c1343bc 100644 --- a/bun.lock +++ b/bun.lock @@ -5,6 +5,7 @@ "name": "concero-v2-operators", "dependencies": { "@concero/contract-utils": "github:concero/contract-utils", + "@concero/operator-utils": "github:concero/operator-utils", "@prisma/client": "^5.12.0", "@slack/web-api": "^7.9.1", "@types/jest": "^29.5.14", @@ -16,7 +17,7 @@ "prisma": "^5.12.0", "ts-jest": "^29.3.2", "uuid": "^11.1.0", - "viem": "2.24.1", + "viem": "2.33.0", "winston": "^3.17.0", "winston-daily-rotate-file": "^5.0.0", }, @@ -114,6 +115,8 @@ "@concero/contract-utils": ["@concero/contract-utils@github:concero/contract-utils#c10d675", { "dependencies": { "viem": "2.26.2" } }, "concero-contract-utils-c10d675"], + "@concero/operator-utils": ["@concero/operator-utils@github:concero/operator-utils#f03f597", { "dependencies": { "axios": "^1.10.0", "viem": "^2.33.0", "winston": "^3.17.0", "winston-daily-rotate-file": "^5.0.0" } }, "concero-operator-utils-f03f597"], + "@dabh/diagnostics": ["@dabh/diagnostics@2.0.3", "", { "dependencies": { "colorspace": "1.1.x", "enabled": "2.0.x", "kuler": "^2.0.0" } }, "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA=="], "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.6", "", { "os": "aix", "cpu": "ppc64" }, "sha512-ShbM/3XxwuxjFiuVBHA+d3j5dyac0aEVVq1oluIDf71hUw0aRF59dV/efUsIwFnR6m8JNM2FjZOzmaZ8yG61kw=="], @@ -238,6 +241,8 @@ "@mole-inc/bin-wrapper": ["@mole-inc/bin-wrapper@8.0.1", "", { "dependencies": { "bin-check": "^4.1.0", "bin-version-check": "^5.0.0", "content-disposition": "^0.5.4", "ext-name": "^5.0.0", "file-type": "^17.1.6", "filenamify": "^5.0.2", "got": "^11.8.5", "os-filter-obj": "^2.0.0" } }, "sha512-sTGoeZnjI8N4KS+sW2AN95gDBErhAguvkw/tWdCjeM8bvxpz5lqrnd0vOJABA1A+Ic3zED7PYoLP/RANLgVotA=="], + "@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], + "@noble/curves": ["@noble/curves@1.2.0", "", { "dependencies": { "@noble/hashes": "1.3.2" } }, "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw=="], "@noble/hashes": ["@noble/hashes@1.3.2", "", {}, "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ=="], @@ -264,9 +269,9 @@ "@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], - "@scure/bip32": ["@scure/bip32@1.6.2", "", { "dependencies": { "@noble/curves": "~1.8.1", "@noble/hashes": "~1.7.1", "@scure/base": "~1.2.2" } }, "sha512-t96EPDMbtGgtb7onKKqxRLfE5g05k7uHnHRM2xdE6BP/ZmxaLtPek4J4KfVn/90IQNrU1IOAqMgiDtUdtbe3nw=="], + "@scure/bip32": ["@scure/bip32@1.7.0", "", { "dependencies": { "@noble/curves": "~1.9.0", "@noble/hashes": "~1.8.0", "@scure/base": "~1.2.5" } }, "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw=="], - "@scure/bip39": ["@scure/bip39@1.5.4", "", { "dependencies": { "@noble/hashes": "~1.7.1", "@scure/base": "~1.2.4" } }, "sha512-TFM4ni0vKvCfBpohoh+/lY05i9gRbSwXWngAsF4CABQxoaOHijxuaZ2R6cStDQ5CHtHO9aGJTr4ksVJASRRyMA=="], + "@scure/bip39": ["@scure/bip39@1.6.0", "", { "dependencies": { "@noble/hashes": "~1.8.0", "@scure/base": "~1.2.5" } }, "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A=="], "@sinclair/typebox": ["@sinclair/typebox@0.27.8", "", {}, "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA=="], @@ -736,7 +741,7 @@ "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], - "isows": ["isows@1.0.6", "", { "peerDependencies": { "ws": "*" } }, "sha512-lPHCayd40oW98/I0uvgaHKWCSvkzY27LjWLbtzOm64yQ+G3Q5npjjbdppU65iZXkK1Zt+kH9pfegli0AYfwYYw=="], + "isows": ["isows@1.0.7", "", { "peerDependencies": { "ws": "*" } }, "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg=="], "istanbul-lib-coverage": ["istanbul-lib-coverage@3.2.2", "", {}, "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg=="], @@ -944,7 +949,7 @@ "os-filter-obj": ["os-filter-obj@2.0.0", "", { "dependencies": { "arch": "^2.1.0" } }, "sha512-uksVLsqG3pVdzzPvmAHpBK0wKxYItuzZr7SziusRPoz67tGV8rL1szZ6IdeUrbqLjGDwApBtN29eEE3IqGHOjg=="], - "ox": ["ox@0.6.9", "", { "dependencies": { "@adraffy/ens-normalize": "^1.10.1", "@noble/curves": "^1.6.0", "@noble/hashes": "^1.5.0", "@scure/bip32": "^1.5.0", "@scure/bip39": "^1.4.0", "abitype": "^1.0.6", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-wi5ShvzE4eOcTwQVsIPdFr+8ycyX+5le/96iAJutaZAvCes1J0+RvpEPg5QDPDiaR0XQQAvZVl7AwqQcINuUug=="], + "ox": ["ox@0.8.1", "", { "dependencies": { "@adraffy/ens-normalize": "^1.11.0", "@noble/ciphers": "^1.3.0", "@noble/curves": "^1.9.1", "@noble/hashes": "^1.8.0", "@scure/bip32": "^1.7.0", "@scure/bip39": "^1.6.0", "abitype": "^1.0.8", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-e+z5epnzV+Zuz91YYujecW8cF01mzmrUtWotJ0oEPym/G82uccs7q0WDHTYL3eiONbTUEvcZrptAKLgTBD3u2A=="], "p-cancelable": ["p-cancelable@2.1.1", "", {}, "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg=="], @@ -1150,7 +1155,7 @@ "v8-to-istanbul": ["v8-to-istanbul@9.3.0", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.12", "@types/istanbul-lib-coverage": "^2.0.1", "convert-source-map": "^2.0.0" } }, "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA=="], - "viem": ["viem@2.24.1", "", { "dependencies": { "@noble/curves": "1.8.1", "@noble/hashes": "1.7.1", "@scure/bip32": "1.6.2", "@scure/bip39": "1.5.4", "abitype": "1.0.8", "isows": "1.0.6", "ox": "0.6.9", "ws": "8.18.1" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-xptFlc081SIPz+ZNDeb0XS/Nn5PU28onq+im+UxEAPCXTIuL1kfw1GTnV8NhbUNoEONnrwcZNqoI0AT0ADF5XQ=="], + "viem": ["viem@2.33.0", "", { "dependencies": { "@noble/curves": "1.9.2", "@noble/hashes": "1.8.0", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "abitype": "1.0.8", "isows": "1.0.7", "ox": "0.8.1", "ws": "8.18.2" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-SxBM3CmeU+LWLlBclV9MPdbuFV8mQEl0NeRc9iyYU4a7Xb5sr5oku3s/bRGTPpEP+1hCAHYpM09/ui3/dQ6EsA=="], "walker": ["walker@1.0.8", "", { "dependencies": { "makeerror": "1.0.12" } }, "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ=="], @@ -1188,6 +1193,8 @@ "@concero/contract-utils/viem": ["viem@2.26.2", "", { "dependencies": { "@noble/curves": "1.8.1", "@noble/hashes": "1.7.1", "@scure/bip32": "1.6.2", "@scure/bip39": "1.5.4", "abitype": "1.0.8", "isows": "1.0.6", "ox": "0.6.9", "ws": "8.18.1" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-+yXSl1n+jV/Kn/zpETiNq0WOcINXti29nxdPIONvvNh+Es0VfeusW8bb2okVfa55pmuc8kOCOpB5wq3ZIUCTSA=="], + "@concero/operator-utils/axios": ["axios@1.10.0", "", { "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", "proxy-from-env": "^1.1.0" } }, "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw=="], + "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], "@eslint/eslintrc/globals": ["globals@14.0.0", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="], @@ -1202,11 +1209,11 @@ "@istanbuljs/load-nyc-config/js-yaml": ["js-yaml@3.14.1", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g=="], - "@scure/bip32/@noble/curves": ["@noble/curves@1.8.1", "", { "dependencies": { "@noble/hashes": "1.7.1" } }, "sha512-warwspo+UYUPep0Q+vtdVB4Ugn8GGQj8iyB3gnRWsztmUHTI3S1nhdiWNsPUGL0vud7JlRRk1XEu7Lq1KGTnMQ=="], + "@scure/bip32/@noble/curves": ["@noble/curves@1.9.2", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-HxngEd2XUcg9xi20JkwlLCtYwfoFw4JGkuZpT+WlsPD4gB/cxkvTD8fSsoAnphGZhFdZYKeQIPCuFlWPm1uE0g=="], - "@scure/bip32/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], + "@scure/bip32/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "@scure/bip39/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], + "@scure/bip39/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], "@swc/cli/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], @@ -1240,9 +1247,9 @@ "ox/@adraffy/ens-normalize": ["@adraffy/ens-normalize@1.11.0", "", {}, "sha512-/3DDPKHqqIqxUULp8yP4zODUY1i+2xvVWsv8A79xGWdCAG+8sb0hRh0Rk2QyOJUnnbyPUAZYcpBuRe3nS2OIUg=="], - "ox/@noble/curves": ["@noble/curves@1.8.1", "", { "dependencies": { "@noble/hashes": "1.7.1" } }, "sha512-warwspo+UYUPep0Q+vtdVB4Ugn8GGQj8iyB3gnRWsztmUHTI3S1nhdiWNsPUGL0vud7JlRRk1XEu7Lq1KGTnMQ=="], + "ox/@noble/curves": ["@noble/curves@1.9.2", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-HxngEd2XUcg9xi20JkwlLCtYwfoFw4JGkuZpT+WlsPD4gB/cxkvTD8fSsoAnphGZhFdZYKeQIPCuFlWPm1uE0g=="], - "ox/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], + "ox/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], "p-queue/eventemitter3": ["eventemitter3@4.0.7", "", {}, "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw=="], @@ -1258,11 +1265,11 @@ "trim-repeated/escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="], - "viem/@noble/curves": ["@noble/curves@1.8.1", "", { "dependencies": { "@noble/hashes": "1.7.1" } }, "sha512-warwspo+UYUPep0Q+vtdVB4Ugn8GGQj8iyB3gnRWsztmUHTI3S1nhdiWNsPUGL0vud7JlRRk1XEu7Lq1KGTnMQ=="], + "viem/@noble/curves": ["@noble/curves@1.9.2", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-HxngEd2XUcg9xi20JkwlLCtYwfoFw4JGkuZpT+WlsPD4gB/cxkvTD8fSsoAnphGZhFdZYKeQIPCuFlWPm1uE0g=="], - "viem/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], + "viem/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "viem/ws": ["ws@8.18.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w=="], + "viem/ws": ["ws@8.18.2", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ=="], "wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], @@ -1270,6 +1277,14 @@ "@concero/contract-utils/viem/@noble/hashes": ["@noble/hashes@1.7.1", "", {}, "sha512-B8XBPsn4vT/KJAGqDzbwztd+6Yte3P4V7iafm24bxgDe/mlRuK6xmWPuCNrKt2vDafZ8MfJLlchDG/vYafQEjQ=="], + "@concero/contract-utils/viem/@scure/bip32": ["@scure/bip32@1.6.2", "", { "dependencies": { "@noble/curves": "~1.8.1", "@noble/hashes": "~1.7.1", "@scure/base": "~1.2.2" } }, "sha512-t96EPDMbtGgtb7onKKqxRLfE5g05k7uHnHRM2xdE6BP/ZmxaLtPek4J4KfVn/90IQNrU1IOAqMgiDtUdtbe3nw=="], + + "@concero/contract-utils/viem/@scure/bip39": ["@scure/bip39@1.5.4", "", { "dependencies": { "@noble/hashes": "~1.7.1", "@scure/base": "~1.2.4" } }, "sha512-TFM4ni0vKvCfBpohoh+/lY05i9gRbSwXWngAsF4CABQxoaOHijxuaZ2R6cStDQ5CHtHO9aGJTr4ksVJASRRyMA=="], + + "@concero/contract-utils/viem/isows": ["isows@1.0.6", "", { "peerDependencies": { "ws": "*" } }, "sha512-lPHCayd40oW98/I0uvgaHKWCSvkzY27LjWLbtzOm64yQ+G3Q5npjjbdppU65iZXkK1Zt+kH9pfegli0AYfwYYw=="], + + "@concero/contract-utils/viem/ox": ["ox@0.6.9", "", { "dependencies": { "@adraffy/ens-normalize": "^1.10.1", "@noble/curves": "^1.6.0", "@noble/hashes": "^1.5.0", "@scure/bip32": "^1.5.0", "@scure/bip39": "^1.4.0", "abitype": "^1.0.6", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-wi5ShvzE4eOcTwQVsIPdFr+8ycyX+5le/96iAJutaZAvCes1J0+RvpEPg5QDPDiaR0XQQAvZVl7AwqQcINuUug=="], + "@concero/contract-utils/viem/ws": ["ws@8.18.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w=="], "@istanbuljs/load-nyc-config/find-up/locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="], @@ -1296,6 +1311,8 @@ "pkg-dir/find-up/locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="], + "@concero/contract-utils/viem/ox/@adraffy/ens-normalize": ["@adraffy/ens-normalize@1.11.0", "", {}, "sha512-/3DDPKHqqIqxUULp8yP4zODUY1i+2xvVWsv8A79xGWdCAG+8sb0hRh0Rk2QyOJUnnbyPUAZYcpBuRe3nS2OIUg=="], + "@istanbuljs/load-nyc-config/find-up/locate-path/p-locate": ["p-locate@4.1.0", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="], "bin-check/execa/cross-spawn/lru-cache": ["lru-cache@4.1.5", "", { "dependencies": { "pseudomap": "^1.0.2", "yallist": "^2.1.2" } }, "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g=="], diff --git a/package.json b/package.json index a5b8d0e..cab1ed5 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "build": "esbuild src/relayer-a/index.ts --bundle --platform=node --target=node22 --outdir=dist --format=esm", "lint": "eslint --config .eslint.config.mjs", "format": "prettier --config .prettierrc.json --write **/*.{ts,json}", + "start": "bun ./src/relayer-a/index.ts", "start:relayerA": "bun ./src/relayer-a/index.ts", "check-updates": "npx npm-check-updates", "prisma:reset": "npx prisma migrate reset", @@ -32,6 +33,7 @@ }, "dependencies": { "@concero/contract-utils": "github:concero/contract-utils", + "@concero/operator-utils": "github:concero/operator-utils", "@prisma/client": "^5.12.0", "@slack/web-api": "^7.9.1", "@types/jest": "^29.5.14", @@ -43,7 +45,7 @@ "prisma": "^5.12.0", "ts-jest": "^29.3.2", "uuid": "^11.1.0", - "viem": "2.24.1", + "viem": "2.33.0", "winston": "^3.17.0", "winston-daily-rotate-file": "^5.0.0" } diff --git a/src/common/eventListener/setupEventListener.ts b/src/common/eventListener/setupEventListener.ts index cfd1be2..b3960d9 100644 --- a/src/common/eventListener/setupEventListener.ts +++ b/src/common/eventListener/setupEventListener.ts @@ -1,8 +1,8 @@ import { AbiEvent, type Address, Log } from "viem"; +import { Logger } from "@concero/operator-utils"; import { ConceroNetwork } from "../../types/ConceroNetwork"; import { TxManager } from "../managers"; -import { Logger } from "../utils"; export interface EventListenerHandle { stop: () => void; diff --git a/src/common/managers/BlockManagerRegistry.ts b/src/common/managers/BlockManagerRegistry.ts deleted file mode 100644 index e1af8ed..0000000 --- a/src/common/managers/BlockManagerRegistry.ts +++ /dev/null @@ -1,220 +0,0 @@ -import { PublicClient } from "viem"; - -import { ConceroNetwork } from "../../types/ConceroNetwork"; -import { BlockManagerRegistryConfig } from "../../types/ManagerConfigs"; -import { - IBlockCheckpointManager, - IBlockManagerRegistry, - INetworkManager, - IRpcManager, - IViemClientManager, - NetworkUpdateListener, -} from "../../types/managers/"; -import { LoggerInterface } from "../utils/"; - -import { BlockManager } from "./BlockManager"; -import { ManagerBase } from "./ManagerBase"; - -export class BlockManagerRegistry - extends ManagerBase - implements IBlockManagerRegistry, NetworkUpdateListener -{ - private static instance: BlockManagerRegistry; - private blockManagers: Map = new Map(); - private blockCheckpointManager: IBlockCheckpointManager; - private networkManager: INetworkManager; - private viemClientManager: IViemClientManager; - private rpcManager: IRpcManager; - private logger: LoggerInterface; - private config: BlockManagerRegistryConfig; - - private constructor( - logger: LoggerInterface, - blockCheckpointManager: IBlockCheckpointManager, - networkManager: INetworkManager, - viemClientManager: IViemClientManager, - rpcManager: IRpcManager, - config: BlockManagerRegistryConfig, - ) { - super(); - this.logger = logger; - this.blockCheckpointManager = blockCheckpointManager; - this.networkManager = networkManager; - this.viemClientManager = viemClientManager; - this.rpcManager = rpcManager; - this.config = config; - } - - public async onNetworksUpdated(networks: ConceroNetwork[]): Promise { - this.logger.info(`Networks updated, syncing BlockManagers for ${networks.length} networks`); - try { - await this.updateBlockManagers(networks); - } catch (error) { - this.logger.error("Failed to sync BlockManagers after network update", error); - throw error; - } - } - - private async ensureBlockManagerForNetwork( - network: ConceroNetwork, - ): Promise { - // If we already have a BlockManager for this network, return it - if (this.blockManagers.has(network.name)) { - this.logger.debug(`Using existing BlockManager for network ${network.name}`); - return this.blockManagers.get(network.name)!; - } - - try { - const { publicClient } = this.viemClientManager.getClients(network); - - // Create the BlockManager - const blockManager = await this.createBlockManager(network, publicClient); - return blockManager; - } catch (error) { - this.logger.warn(`Failed to create BlockManager for network ${network.name}`, error); - return null; - } - } - - private async updateBlockManagers(networks: ConceroNetwork[]): Promise { - if (!this.initialized) return; - - this.logger.info(`Syncing BlockManagers for ${networks.length} active networks`); - const currentNetworkNames = new Set(this.blockManagers.keys()); - const newNetworkNames = new Set(networks.map(network => network.name)); - - // Remove BlockManagers for networks that are no longer active - for (const networkName of currentNetworkNames) { - if (!newNetworkNames.has(networkName)) { - this.logger.info(`Removing BlockManager for inactive network ${networkName}`); - const blockManager = this.blockManagers.get(networkName); - if (blockManager && "dispose" in blockManager) { - (blockManager as any).dispose(); - } - this.blockManagers.delete(networkName); - } - } - - // Create BlockManagers for new networks - const newNetworks = networks.filter(network => !currentNetworkNames.has(network.name)); - if (newNetworks.length > 0) { - this.logger.debug(`Creating ${newNetworks.length} new BlockManagers`); - - const results = await Promise.all( - newNetworks.map(network => this.ensureBlockManagerForNetwork(network)), - ); - } - } - - //TODO: attempt to refactor createInstance to a base class - public static createInstance( - logger: LoggerInterface, - blockCheckpointManager: IBlockCheckpointManager, - networkManager: INetworkManager, - viemClientManager: IViemClientManager, - rpcManager: IRpcManager, - config: BlockManagerRegistryConfig, - ): BlockManagerRegistry { - BlockManagerRegistry.instance = new BlockManagerRegistry( - logger, - blockCheckpointManager, - networkManager, - viemClientManager, - rpcManager, - config, - ); - return BlockManagerRegistry.instance; - } - - public static getInstance(): BlockManagerRegistry { - if (!BlockManagerRegistry.instance) { - throw new Error( - "BlockManagerRegistry is not initialized. Call createInstance() first.", - ); - } - return BlockManagerRegistry.instance; - } - - public async initialize(): Promise { - if (this.initialized) return; - - try { - await super.initialize(); - this.logger.debug("Initialized"); - } catch (error) { - this.logger.error("Failed to initialize", error); - throw error; - } - } - - public async createBlockManager( - network: ConceroNetwork, - publicClient: PublicClient, - ): Promise { - if (this.blockManagers.has(network.name)) { - return this.blockManagers.get(network.name)!; - } - - const blockManager = await BlockManager.create( - network, - publicClient, - this.blockCheckpointManager, - this.logger, - { - pollingIntervalMs: this.config.blockManagerConfig.pollingIntervalMs, - catchupBatchSize: this.config.blockManagerConfig.catchupBatchSize, - useCheckpoints: this.config.blockManagerConfig.useCheckpoints, - }, - ); - - this.blockManagers.set(network.name, blockManager); - this.logger.debug(`Created BlockManager for network ${network.name}`); - - return blockManager; - } - - public getBlockManager(networkName: string): BlockManager | undefined { - if (this.blockManagers.has(networkName)) { - return this.blockManagers.get(networkName)!; - } - - this.logger.warn(`BlockManager for ${networkName} not found`); - return undefined; - } - - public getAllBlockManagers(): BlockManager[] { - return Array.from(this.blockManagers.values()); - } - - public getAllManagedNetworks(): string[] { - return Array.from(this.blockManagers.keys()); - } - - public async getLatestBlockForChain(networkName: string): Promise { - const blockManager = this.getBlockManager(networkName); - if (!blockManager) { - this.logger.error(`BlockManager for ${networkName} not found`); - return null; - } - - return blockManager.getLatestBlock(); - } - - public override dispose(): void { - if (this.initialized) { - this.networkManager.unregisterUpdateListener(this); - - // Properly dispose all block managers - for (const [networkName, blockManager] of this.blockManagers.entries()) { - if ("dispose" in blockManager) { - (blockManager as any).dispose(); - } - this.logger.debug(`Disposed BlockManager for ${networkName}`); - } - - this.blockManagers.clear(); - super.dispose(); - this.logger.debug("Disposed"); - } - } -} diff --git a/src/common/managers/DeploymentManager.ts b/src/common/managers/DeploymentManager.ts deleted file mode 100644 index 06e5d51..0000000 --- a/src/common/managers/DeploymentManager.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { Address } from "viem"; - -import { ConceroNetwork } from "../../types/ConceroNetwork"; -import { DeploymentManagerConfig } from "../../types/ManagerConfigs"; -import { IDeploymentsManager, NetworkUpdateListener } from "../../types/managers"; -import { getEnvVar } from "../utils/getEnvVar"; -import { HttpClient } from "../utils/HttpClient"; -import { LoggerInterface } from "../utils/Logger"; - -import { ManagerBase } from "./ManagerBase"; - -// Keeps updatable lists of ConceroVerifier and ConceroRouter contracts. -export class DeploymentManager - extends ManagerBase - implements IDeploymentsManager, NetworkUpdateListener -{ - private static instance: DeploymentManager; - - private conceroRoutersMapByChainName: Record = {}; - private conceroVerifier: Address | undefined; - private httpClient: HttpClient; - private logger: LoggerInterface; - private config: DeploymentManagerConfig; - - private constructor(logger: LoggerInterface, config: DeploymentManagerConfig) { - super(); - this.httpClient = HttpClient.getInstance(); - this.logger = logger; - this.config = config; - } - - public static createInstance( - logger: LoggerInterface, - config: DeploymentManagerConfig, - ): DeploymentManager { - DeploymentManager.instance = new DeploymentManager(logger, config); - return DeploymentManager.instance; - } - - public static getInstance(): DeploymentManager { - if (!DeploymentManager.instance) { - throw new Error("DeploymentManager is not initialized. Call createInstance() first."); - } - return DeploymentManager.instance; - } - - public async initialize(): Promise { - if (this.initialized) return; - try { - await super.initialize(); - this.logger.debug("Initialized"); - } catch (error) { - this.logger.error("Failed to initialize:", error); - throw error; - } - } - - async getRouterByChainName(chainName: string): Promise
{ - if (this.isLocalhostEnv()) { - return getEnvVar("CONCERO_ROUTER_PROXY_LOCALHOST") as Address; - } - - const router = this.conceroRoutersMapByChainName[chainName]; - - if (!router) { - throw new Error(`Router not found for chain: ${chainName}`); - } - - return router; - } - - async getConceroRouters(): Promise> { - if (this.isLocalhostEnv()) { - return { - [getEnvVar("LOCALHOST_FORK_CHAIN_ID")]: getEnvVar( - "CONCERO_ROUTER_PROXY_LOCALHOST", - ) as Address, - }; - } - - const routers = this.conceroRoutersMapByChainName; - return routers; - } - - async getConceroVerifier(): Promise
{ - if (this.isLocalhostEnv()) { - return getEnvVar("CONCERO_VERIFIER_PROXY_LOCALHOST") as Address; - } - - if (this.conceroVerifier !== undefined) return this.conceroVerifier; - - await this.updateDeployments(); - - if (!this.conceroVerifier) { - throw new Error("Concero verifier address not found after update"); - } - - return this.conceroVerifier; - } - - async updateDeployments(networks?: ConceroNetwork[]): Promise { - const now = Date.now(); - - try { - const deployments = await this.httpClient.get(this.config.conceroDeploymentsUrl, { - responseType: "text", // Ensure Axios returns raw text - }); - - const deploymentsEnvArr = deployments.split("\n"); - - const conceroRouterDeploymentsEnv = deploymentsEnvArr.filter( - (d: string) => - d.startsWith("CONCERO_ROUTER_PROXY") && - !d.startsWith("CONCERO_ROUTER_PROXY_ADMIN"), - ); - - const routerMap: Record = {} as Record; - - // If networks are provided, create a set for efficient lookup - const activeNetworkNames = networks ? new Set(networks.map(n => n.name)) : null; - - // Remove deployments for networks that are no longer active - if (activeNetworkNames) { - const currentNetworkNames = Object.keys(this.conceroRoutersMapByChainName); - for (const networkName of currentNetworkNames) { - if (!activeNetworkNames.has(networkName)) { - delete this.conceroRoutersMapByChainName[networkName]; - this.logger.debug( - `Removed deployment for inactive network: ${networkName}`, - ); - } - } - } - - for (const deploymentEnv of conceroRouterDeploymentsEnv) { - const [name, address] = deploymentEnv.split("="); - const networkName = this.extractNetworkName(name); - if (networkName) { - // If networks are provided, only store deployments for active networks - if (!activeNetworkNames || activeNetworkNames.has(networkName)) { - routerMap[networkName as string] = address as Address; - } - } - } - - // Update the deployments - Object.assign(this.conceroRoutersMapByChainName, routerMap); - - const verifierEntry = deploymentsEnvArr.find((d: string) => { - const networkSuffix = - this.config.networkMode === "testnet" ? "ARBITRUM_SEPOLIA" : "ARBITRUM"; - return d.startsWith(`CONCERO_VERIFIER_PROXY_${networkSuffix}`); - }); - - if (verifierEntry) { - this.conceroVerifier = verifierEntry.split("=")[1] as Address; - } - - this.lastUpdateTime = now; - this.logger.debug("Deployments updated"); - } catch (error) { - this.logger.error("Failed to update deployments:", error); - throw new Error( - `Failed to update deployments: ${error instanceof Error ? error.message : String(error)}`, - ); - } - } - - async onNetworksUpdated(networks: ConceroNetwork[]): Promise { - // this.logger.debug("Received onNetworksUpdated"); - try { - await this.updateDeployments(networks); - } catch (err) { - this.logger.error("Failed to update deployments after network update:", err); - throw err; - } - } - - private extractNetworkName(key: string): string | null { - const prefix = "CONCERO_ROUTER_PROXY_"; - - const parts = key.slice(prefix.length).toLowerCase().split("_"); - return ( - parts[0] + - parts - .slice(1) - .map(part => part.charAt(0).toUpperCase() + part.slice(1)) - .join("") - ); - } - - private isLocalhostEnv(): boolean { - return this.config.networkMode === "localhost"; - } - - public override dispose(): void { - super.dispose(); - this.logger.debug("Disposed"); - } -} diff --git a/src/common/managers/NetworkManager.ts b/src/common/managers/NetworkManager.ts deleted file mode 100644 index 88b6961..0000000 --- a/src/common/managers/NetworkManager.ts +++ /dev/null @@ -1,340 +0,0 @@ -import { globalConfig } from "../../constants"; -import { ConceroNetwork } from "../../types/ConceroNetwork"; -import { NetworkManagerConfig } from "../../types/ManagerConfigs"; -import { INetworkManager, NetworkUpdateListener } from "../../types/managers"; -import { fetchNetworkConfigs } from "../utils"; -import { getEnvVar, localhostViemChain, LoggerInterface } from "../utils/"; - -import { ManagerBase } from "./ManagerBase"; - -export class NetworkManager extends ManagerBase implements INetworkManager { - private static instance: NetworkManager; - - private mainnetNetworks: Record = {}; - private testnetNetworks: Record = {}; - private allNetworks: Record = {}; - private activeNetworks: ConceroNetwork[] = []; - private updateIntervalId: NodeJS.Timeout | null = null; - - private updateListeners: NetworkUpdateListener[] = []; - private logger: LoggerInterface; - private config: NetworkManagerConfig; - - private constructor(logger: LoggerInterface, config: NetworkManagerConfig) { - super(); - this.config = config; - this.logger = logger; - } - - public static getInstance(): NetworkManager { - return NetworkManager.instance; - } - - public static createInstance( - logger: LoggerInterface, - config: NetworkManagerConfig, - ): NetworkManager { - this.instance = new NetworkManager(logger, config); - return this.instance; - } - - public async initialize(): Promise { - if (this.initialized) return; - - try { - await this.updateNetworks(); - this.setupUpdateCycle(); - this.initialized = true; - this.logger.debug("Initialized"); - } catch (error) { - this.logger.error("Failed to initialize networks:", error); - throw error; - } - } - - public registerUpdateListener(listener: NetworkUpdateListener): void { - const existingIndex = this.updateListeners.findIndex( - existing => existing.constructor.name === listener.constructor.name, - ); - - if (existingIndex === -1) { - this.updateListeners.push(listener); - } else { - this.logger.warn(`Update listener already registered: ${listener.constructor.name}`); - } - } - - public unregisterUpdateListener(listener: NetworkUpdateListener): void { - const index = this.updateListeners.indexOf(listener); - if (index !== -1) { - this.updateListeners.splice(index, 1); - } - } - - public getMainnetNetworks(): Record { - return { ...this.mainnetNetworks }; - } - - public getTestnetNetworks(): Record { - return { ...this.testnetNetworks }; - } - - public getAllNetworks(): Record { - return { ...this.allNetworks }; - } - - public getActiveNetworks(): ConceroNetwork[] { - return [...this.activeNetworks]; - } - - public getNetworkById(chainId: number): ConceroNetwork { - const network = Object.values(this.allNetworks).find(network => network.id === chainId); - if (!network) { - throw new Error(`Network with chain ID ${chainId} not found`); - } - return network; - } - - public getNetworkByName(name: string): ConceroNetwork { - const network = Object.values(this.allNetworks).find(network => network.name === name); - if (!network) { - throw new Error(`Network with name "${name}" not found`); - } - return network; - } - - public getNetworkBySelector(selector: string): ConceroNetwork { - const network = Object.values(this.allNetworks).find( - network => network.chainSelector === selector, - ); - if (!network) { - throw new Error(`Network with selector "${selector}" not found`); - } - return network; - } - - public getVerifierNetwork(): ConceroNetwork { - if (this.config.networkMode === "mainnet") { - return this.mainnetNetworks["arbitrum"]; - } else if (this.config.networkMode === "testnet") { - return this.testnetNetworks["arbitrumSepolia"]; - } else if (this.config.networkMode === "localhost") { - const localNetwork = this.testnetNetworks["localhost"]; - - if (!localNetwork) { - this.logger.error( - `Available testnet networks: ${Object.keys(this.testnetNetworks).join(", ")}`, - ); - throw new Error("Localhost network not found in testnetNetworks"); - } - - this.logger.debug( - `Using localhost network: ${localNetwork.name} (id: ${localNetwork.id})`, - ); - return localNetwork; - } else { - throw new Error(`Unsupported network mode: ${this.config.networkMode}`); - } - } - - public async forceUpdate(): Promise { - await this.updateNetworks(); - } - - private setupUpdateCycle(): void { - if (this.updateIntervalId) { - clearInterval(this.updateIntervalId); - } - - this.updateIntervalId = setInterval( - () => - this.updateNetworks().catch(err => - this.logger.error("Network update failed:", err), - ), - this.config.networkUpdateIntervalMs, - ); - } - - private async updateNetworks(): Promise { - let networksFetched = false; - try { - const operatorPK = getEnvVar("OPERATOR_PRIVATE_KEY"); - - if (this.config.networkMode === "localhost") { - // In localhost mode, skip fetching remote network configs - this.mainnetNetworks = {}; - const localhostNetworks = this.getTestingNetworks(operatorPK); - this.testnetNetworks = localhostNetworks; - this.logger.debug( - `Using localhost networks only: ${Object.keys(localhostNetworks).join(", ")}`, - ); - networksFetched = true; - } else { - try { - const { mainnetNetworks: fetchedMainnet, testnetNetworks: fetchedTestnet } = - await fetchNetworkConfigs(this.config.networkMode, { - mainnet: globalConfig.URLS.V2_NETWORKS.MAINNET, - testnet: globalConfig.URLS.V2_NETWORKS.TESTNET, - }); - - const hasMainnetNetworks = Object.keys(fetchedMainnet).length > 0; - const hasTestnetNetworks = Object.keys(fetchedTestnet).length > 0; - - if (hasMainnetNetworks) { - this.mainnetNetworks = this.createNetworkConfig(fetchedMainnet, "mainnet", [ - operatorPK, - ]); - } else { - this.logger.warn( - "No mainnet networks fetched, keeping existing mainnet networks", - ); - } - - if (hasTestnetNetworks) { - this.testnetNetworks = this.createNetworkConfig(fetchedTestnet, "testnet", [ - operatorPK, - ]); - } else { - this.logger.warn( - "No testnet networks fetched, keeping existing testnet networks", - ); - } - - networksFetched = true; - } catch (error) { - this.logger.warn( - "Failed to fetch network configurations. Will retry on next update cycle:", - error, - ); - if (Object.keys(this.allNetworks).length === 0) { - this.logger.error( - "No network configurations available. Unable to initialize services.", - ); - } - } - } - - this.allNetworks = { ...this.testnetNetworks, ...this.mainnetNetworks }; - - const filteredNetworks = this.filterNetworks(this.config.networkMode); - - if (networksFetched) { - this.activeNetworks = filteredNetworks; - this.logger.debug( - `Networks updated - Active networks: ${this.activeNetworks.length} (${this.activeNetworks.map(n => n.name).join(", ")})`, - ); - } - - if (networksFetched) { - await this.notifyListeners(); - } - } catch (error) { - this.logger.error("Failed to update networks:", error); - } - } - - private async notifyListeners(): Promise { - for (const listener of this.updateListeners) { - try { - await listener.onNetworksUpdated(this.activeNetworks); - } catch (error) { - this.logger.error("Error in network update listener:", error); - } - } - } - - public async triggerInitialUpdates(): Promise { - this.logger.debug("Triggering initial updates for all listeners sequentially"); - - for (const listener of this.updateListeners) { - try { - this.logger.debug(`Triggering initial update for ${listener.constructor.name}`); - await listener.onNetworksUpdated(this.activeNetworks); - this.logger.debug(`Completed initial update for ${listener.constructor.name}`); - } catch (error) { - this.logger.error( - `Error in initial update for ${listener.constructor.name}:`, - error, - ); - throw error; // Fail fast if initial updates fail - } - } - - this.logger.debug("Completed all initial updates"); - } - - private createNetworkConfig( - networks: Record, - networkType: "mainnet" | "testnet" | "localhost", - accounts: string[], - ): Record { - return Object.fromEntries( - Object.entries(networks).map(([key, network]) => { - const networkKey = key as T; - return [ - networkKey, - { - name: network.name || networkKey, - type: networkType, - id: network.chainId, - accounts, - chainSelector: network.chainSelector || network.chainId.toString(), - confirmations: this.config.defaultConfirmations, - viemChain: network.viemChain, - }, - ]; - }), - ) as Record; - } - - private getTestingNetworks(operatorPK: string): Record { - return { - localhost: { - name: "localhost", - type: "localhost", - id: 1, - accounts: [operatorPK], - chainSelector: "1", - confirmations: this.config.defaultConfirmations, - viemChain: localhostViemChain, - }, - }; - } - - private filterNetworks(networkType: "mainnet" | "testnet" | "localhost"): ConceroNetwork[] { - let networks: ConceroNetwork[] = []; - const ignoredIds = this.config.ignoredNetworkIds || []; - const whitelistedIds = this.config.whitelistedNetworkIds[networkType] || []; - - switch (networkType) { - case "localhost": - networks = Object.values( - this.getTestingNetworks(getEnvVar("OPERATOR_PRIVATE_KEY")), - ); - break; - case "testnet": - networks = Object.values(this.testnetNetworks); - break; - case "mainnet": - networks = Object.values(this.mainnetNetworks); - break; - } - - networks = networks.filter(network => !ignoredIds.includes(network.id)); - - if (whitelistedIds.length > 0) { - networks = networks.filter(network => whitelistedIds.includes(network.id)); - } - - return networks; - } - - public dispose(): void { - if (this.updateIntervalId) { - clearInterval(this.updateIntervalId); - this.updateIntervalId = null; - } - this.updateListeners = []; - super.dispose(); - } -} diff --git a/src/common/managers/NonceManager.ts b/src/common/managers/NonceManager.ts deleted file mode 100644 index e64faca..0000000 --- a/src/common/managers/NonceManager.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { Mutex } from "async-mutex"; - -import { NonceManagerConfig } from "../../types/ManagerConfigs"; -import { IGetNonceParams, INonceManager, INonceManagerParams } from "../../types/managers"; -import { LoggerInterface } from "../utils/Logger"; -import { ManagerBase } from "./ManagerBase"; - -export class NonceManager extends ManagerBase implements INonceManager { - private static instance: NonceManager | null = null; - private noncesMap: Record = {}; - private mutexMap: Record = {}; - private logger: LoggerInterface; - private config: NonceManagerConfig; - - protected constructor(logger: LoggerInterface, config: NonceManagerConfig) { - super(); - this.logger = logger; - this.config = config; - } - - static createInstance(logger: LoggerInterface, config: NonceManagerConfig): NonceManager { - if (!NonceManager.instance) { - NonceManager.instance = new NonceManager(logger, config); - } - return NonceManager.instance; - } - - static getInstance(): NonceManager { - if (!NonceManager.instance) { - throw new Error( - "NonceManager instance has not been created. Call createInstance() first.", - ); - } - return NonceManager.instance; - } - - static dispose(): void { - NonceManager.instance = null; - } - - async get(params: IGetNonceParams) { - const m = this.getMutex(params.chainId); - return m.runExclusive(async () => { - if (!this.noncesMap[params.chainId]) { - const actualNonce = await this.fetchNonce(params); - this.set(params, actualNonce); - return actualNonce; - } - return this.noncesMap[params.chainId]; - }); - } - - async consume(params: IGetNonceParams) { - const m = this.getMutex(params.chainId); - return m.runExclusive(async () => { - const nonce = this.noncesMap[params.chainId] - ? this.noncesMap[params.chainId] - : await this.fetchNonce(params); - - this.set(params, nonce + 1); - return nonce; - }); - } - - reset(params: INonceManagerParams) { - this.set(params, 0); - } - - set(params: INonceManagerParams, nonce: number) { - this.noncesMap[params.chainId] = nonce; - } - - private async fetchNonce(params: IGetNonceParams) { - return await params.client.getTransactionCount({ address: params.address }); - } - - private getMutex(chainId: number): Mutex { - if (!this.mutexMap[chainId]) { - this.mutexMap[chainId] = new Mutex(); - } - return this.mutexMap[chainId]; - } -} diff --git a/src/common/managers/RpcManager.ts b/src/common/managers/RpcManager.ts deleted file mode 100644 index a977d9a..0000000 --- a/src/common/managers/RpcManager.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { ConceroNetwork } from "../../types/ConceroNetwork"; -import { RpcManagerConfig } from "../../types/ManagerConfigs"; -import { IRpcManager, NetworkUpdateListener } from "../../types/managers"; -import { LoggerInterface } from "../utils/"; -import { HttpClient } from "../utils/HttpClient"; -import { ManagerBase } from "./ManagerBase"; - -// Watches @concero/rpcs and keeps an updatable list of RPC endpoints for networks -export class RpcManager extends ManagerBase implements IRpcManager, NetworkUpdateListener { - private static instance: RpcManager; - private httpClient: HttpClient; - private logger: LoggerInterface; - private config: RpcManagerConfig; - private rpcUrls: Record = {}; - - constructor(logger: LoggerInterface, config: RpcManagerConfig) { - super(); - this.httpClient = HttpClient.getInstance(); - this.logger = logger; - this.config = config; - } - - public static createInstance(logger: LoggerInterface, config: RpcManagerConfig): RpcManager { - RpcManager.instance = new RpcManager(logger, config); - return RpcManager.instance; - } - - public static getInstance(): RpcManager { - if (!RpcManager.instance) { - throw new Error("RpcManager is not initialized. Call createInstance() first."); - } - return RpcManager.instance; - } - - public async initialize(): Promise { - if (this.initialized) return; - - await super.initialize(); - this.logger.debug("Initialized"); - } - - public async ensureRpcsForNetwork(network: ConceroNetwork): Promise { - if (!this.rpcUrls[network.name] || this.rpcUrls[network.name].length === 0) { - await this.updateRpcs([network]); - } - } - - public async updateRpcsForNetworks(networks: ConceroNetwork[]): Promise { - await this.updateRpcs(networks); - } - - public async updateRpcs(networks: ConceroNetwork[]): Promise { - try { - const url = `${this.config.conceroRpcsUrl}/${this.config.networkMode}.json`; - - const response = - await this.httpClient.get< - Record - >(url); - - if (!response) { - throw new Error("Failed to fetch RPC data"); - } - - // Create a set of active network names for efficient lookup - const activeNetworkNames = new Set(networks.map(n => n.name)); - - // Remove RPCs for networks that are no longer active - const currentNetworkNames = Object.keys(this.rpcUrls); - for (const networkName of currentNetworkNames) { - if (!activeNetworkNames.has(networkName)) { - delete this.rpcUrls[networkName]; - this.logger.debug(`Removed RPCs for inactive network: ${networkName}`); - } - } - - // Only store RPCs for active networks - const activeNetworkRpcs = Object.entries(response) - .filter(([networkName]) => activeNetworkNames.has(networkName)) - .map(([networkName, data]) => [networkName, data.rpcUrls || []]); - - // Update RPCs for active networks - for (const [networkName, rpcUrls] of activeNetworkRpcs) { - this.rpcUrls[networkName] = rpcUrls as string[]; - } - - this.logger.debug(`Updated RPCs for ${activeNetworkRpcs.length} active networks`); - } catch (error) { - this.logger.error("Failed to update RPCs:", error); - throw error; - } - } - - public getRpcsForNetwork(networkName: string): string[] { - return this.rpcUrls[networkName] || []; - } - - public async onNetworksUpdated(networks: ConceroNetwork[]): Promise { - try { - await this.updateRpcs(networks); - } catch (err) { - this.logger.error("Failed to update RPCs after network update:", err); - throw err; - } - } -} diff --git a/src/common/managers/ViemClientManager.ts b/src/common/managers/ViemClientManager.ts deleted file mode 100644 index 95b2fbd..0000000 --- a/src/common/managers/ViemClientManager.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { createPublicClient, createWalletClient, fallback, PublicClient, WalletClient } from "viem"; -import { privateKeyToAccount } from "viem/accounts"; -import type { PrivateKeyAccount } from "viem/accounts/types"; - -import { ConceroNetwork } from "../../types/ConceroNetwork"; -import { ViemClientManagerConfig } from "../../types/ManagerConfigs"; -import { IRpcManager, NetworkUpdateListener } from "../../types/managers"; -import { createCustomHttpTransport, getEnvVar, LoggerInterface } from "../utils"; - -import { ManagerBase } from "./ManagerBase"; - -export interface ViemClients { - walletClient: WalletClient; - publicClient: PublicClient; - // TODO: do we really use this account? walletClient already has the account - account: PrivateKeyAccount; -} -// Creates & updates Viem Fallback Clients for each network -export class ViemClientManager extends ManagerBase implements NetworkUpdateListener { - private static instance: ViemClientManager; - private clients: Map = new Map(); - private rpcManager: IRpcManager; - private logger: LoggerInterface; - - private config: ViemClientManagerConfig; - - private constructor( - logger: LoggerInterface, - rpcManager: IRpcManager, - config: ViemClientManagerConfig, - ) { - super(); - this.rpcManager = rpcManager; - this.logger = logger; - this.config = config; - } - - public static createInstance( - logger: LoggerInterface, - rpcManager: IRpcManager, - config: ViemClientManagerConfig, - ): ViemClientManager { - ViemClientManager.instance = new ViemClientManager(logger, rpcManager, config); - return ViemClientManager.instance; - } - public static getInstance(): ViemClientManager { - if (!ViemClientManager.instance) { - throw new Error("ViemClientManager is not initialized. Call createInstance() first."); - } - return ViemClientManager.instance; - } - - public async initialize(): Promise { - if (this.initialized) return; - - await super.initialize(); - this.logger.debug("Initialized"); - } - - private createTransport(chain: ConceroNetwork) { - const rpcUrls = this.rpcManager.getRpcsForNetwork(chain.name); - - if (!rpcUrls || rpcUrls.length === 0) { - throw new Error(`No RPC URLs available for chain ${chain.name}`); - } - - return fallback( - rpcUrls.map(url => createCustomHttpTransport(url)), - this.config.fallbackTransportOptions, - ); - } - - private initializeClients(chain: ConceroNetwork): ViemClients { - const privateKey = getEnvVar("OPERATOR_PRIVATE_KEY"); - const account = privateKeyToAccount(`0x${privateKey}`); - const transport = this.createTransport(chain); - - const publicClient = createPublicClient({ - transport, - chain: chain.viemChain, - batch: { multicall: true }, - }); - const walletClient = createWalletClient({ - transport, - chain: chain.viemChain, - account, - }); - - return { - publicClient, - walletClient, - account, - }; - } - - public getClients(chain: ConceroNetwork): ViemClients { - if (!this.initialized) { - throw new Error("ViemClientManager not properly initialized"); - } - - if (!chain) { - throw new Error("Cannot get clients: chain parameter is undefined or null"); - } - - if (!chain.name) { - this.logger.error(`Invalid chain object provided: ${JSON.stringify(chain)}`); - throw new Error("Cannot get clients: chain.name is missing"); - } - - const cachedClients = this.clients.get(chain.name); - if (cachedClients) { - return cachedClients; - } - - this.logger.debug(`Creating new clients for chain: ${chain.name} (id: ${chain.id})`); - const newClients = this.initializeClients(chain); - this.clients.set(chain.name, newClients); - - return newClients; - } - - // hook from NetworkManager - public async onNetworksUpdated(networks: ConceroNetwork[]): Promise { - // Create a set of active network names for efficient lookup - const activeNetworkNames = new Set(networks.map(n => n.name)); - - // Remove clients for networks that are no longer active - const currentNetworkNames = Array.from(this.clients.keys()); - for (const networkName of currentNetworkNames) { - if (!activeNetworkNames.has(networkName)) { - this.clients.delete(networkName); - this.logger.debug(`Removed clients for inactive network: ${networkName}`); - } - } - - // Update clients for active networks - await this.updateClientsForNetworks(networks); - } - - public async updateClientsForNetworks(networks: ConceroNetwork[]): Promise { - for (const network of networks) { - try { - const newClient = this.initializeClients(network); - this.clients.set(network.name, newClient); - this.logger.debug(`Updated clients for chain ${network.name}`); - } catch (error) { - this.logger.error(`Failed to update clients for chain ${network.name}`, error); - } - } - } - - public override dispose(): void { - this.clients.clear(); - super.dispose(); - ViemClientManager.instance = undefined as any; - this.logger.debug("Disposed"); - } -} diff --git a/src/common/managers/index.ts b/src/common/managers/index.ts index a645118..0c37674 100644 --- a/src/common/managers/index.ts +++ b/src/common/managers/index.ts @@ -1,15 +1,12 @@ export { initializeManagers } from "../utils/initializeManagers"; export { BlockCheckpointManager } from "./BlockCheckpointManager"; export { BlockManager } from "./BlockManager"; -export { BlockManagerRegistry } from "./BlockManagerRegistry"; + export { DbManager } from "./DbManager"; -export { DeploymentManager } from "./DeploymentManager"; + export { ManagerBase } from "./ManagerBase"; -export { NetworkManager } from "./NetworkManager"; -export { NonceManager } from "./NonceManager"; -export { RpcManager } from "./RpcManager"; + export { TxManager } from "./TxManager"; export { TxMonitor } from "./TxMonitor"; export { TxReader } from "./TxReader"; export { TxWriter } from "./TxWriter"; -export { ViemClientManager } from "./ViemClientManager"; diff --git a/src/common/utils/HttpClient.ts b/src/common/utils/HttpClient.ts deleted file mode 100644 index 318ae7f..0000000 --- a/src/common/utils/HttpClient.ts +++ /dev/null @@ -1,131 +0,0 @@ -import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"; - -import { AppErrorEnum } from "../../constants"; -import { HttpClientConfig } from "../../types/ManagerConfigs"; -import { ManagerBase } from "../managers"; - -import { AppError } from "./AppError"; -import { LoggerInterface } from "./Logger"; - -export class HttpClient extends ManagerBase { - private static instance?: HttpClient; - - private axiosInstance?: AxiosInstance; - private logger: LoggerInterface; - private config: HttpClientConfig; - - constructor(logger: LoggerInterface, config: HttpClientConfig) { - super(); - - this.logger = logger; - this.config = config; - } - - public static createInstance(logger: LoggerInterface, config: HttpClientConfig): HttpClient { - this.instance = new HttpClient(logger, config); - return this.instance; - } - - public static getInstance(): HttpClient { - return this.instance; - } - - public async initialize(): Promise { - if (this.initialized) { - return; - } - - try { - await this.setupAxiosInstance(); - await super.initialize(); - } catch (error) { - throw error; - } - } - - private async setupAxiosInstance(): Promise { - this.axiosInstance = axios.create({ - timeout: this.config.defaultTimeout, - }); - - this.axiosInstance.interceptors.response.use( - response => response, - async error => { - const config = error.config; - const logger = this.logger; - - if (config && config.__retryCount < this.config.maxRetries) { - config.__retryCount = config.__retryCount || 0; - config.__retryCount += 1; - - logger.warn( - `Retrying request to ${config.url}. Attempt ${config.__retryCount} of ${this.config.maxRetries}. Error: ${error.message}`, - ); - - await new Promise(resolve => setTimeout(resolve, this.config.retryDelay)); - - return this.axiosInstance!(config); - } - - logger.error( - `Request to ${config?.url} failed after ${config?.__retryCount || 0} attempts. Error: ${error.message}`, - ); - throw new AppError(AppErrorEnum.FailedHTTPRequest, error); - }, - ); - } - - public dispose(): void { - this.axiosInstance = undefined; - super.dispose(); - } - - public static disposeInstances(): void { - if (HttpClient.instance) { - HttpClient.instance.dispose(); - HttpClient.instance = undefined; - } - } - - private async request( - method: "GET" | "POST", - url: string, - config: AxiosRequestConfig = {}, - body?: any, - ): Promise { - if (!this.initialized || !this.axiosInstance) { - throw new AppError( - AppErrorEnum.FailedHTTPRequest, - new Error("HttpClient not initialized"), - ); - } - - try { - this.logger.debug( - `${method} request to ${url} with config: ${JSON.stringify(config)} ${ - body ? `and body: ${JSON.stringify(body)}` : "" - }`, - ); - - const response: AxiosResponse = await this.axiosInstance.request({ - method, - url, - data: body, - ...config, - }); - - return response.data; - } catch (error) { - this.logger.error(`Request failed for ${url} with error:`, error); - throw new AppError(AppErrorEnum.FailedHTTPRequest, error); - } - } - - public async get(url: string, config: AxiosRequestConfig = {}): Promise { - return this.request("GET", url, config); - } - - public async post(url: string, body: any, config: AxiosRequestConfig = {}): Promise { - return this.request("POST", url, config, body); - } -} diff --git a/src/common/utils/Logger.ts b/src/common/utils/Logger.ts deleted file mode 100644 index 1d31280..0000000 --- a/src/common/utils/Logger.ts +++ /dev/null @@ -1,176 +0,0 @@ -import winston from "winston"; -import DailyRotateFile from "winston-daily-rotate-file"; - -import { LoggerConfig } from "../../types/ManagerConfigs"; -import { ManagerBase } from "../managers/ManagerBase"; - -export interface LoggerInterface { - error(message: any, ...meta: any[]): void; - warn(message: any, ...meta: any[]): void; - info(message: any, ...meta: any[]): void; - debug(message: any, ...meta: any[]): void; -} - -export class Logger extends ManagerBase { - private static instance: Logger; - private baseLogger: winston.Logger; - private consumerLoggers: Map = new Map(); - private config: LoggerConfig; - - private constructor(config: LoggerConfig) { - super(); - this.config = config; - this.baseLogger = this.createBaseLogger(); - } - - public static createInstance(config: LoggerConfig): Logger { - if (!Logger.instance) { - Logger.instance = new Logger(config); - } - return Logger.instance; - } - - public static getInstance(): Logger { - if (!Logger.instance) { - throw new Error("Logger is not initialized. Call createInstance() first."); - } - return Logger.instance; - } - - private createBaseLogger(): winston.Logger { - const logFormat = winston.format.combine( - winston.format.colorize({ level: true }), - winston.format.timestamp({ - format: "MM-DD HH:mm:ss", - }), - winston.format.printf(({ level, message, timestamp, consumer, ...meta }) => { - const prefix = consumer ? `${consumer}` : ""; - const formattedMessage = - typeof message === "object" ? JSON.stringify(message, null, 2) : message; - const formattedMeta = - meta && Object.keys(meta).length ? JSON.stringify(meta, null, 2) : ""; - - return `${timestamp} ${level} ${prefix}: ${formattedMessage} ${formattedMeta}`.trim(); - }), - ); - - const logger = winston.createLogger({ - level: "debug", // Allow all logs through at base logger level - format: winston.format.json(), - transports: [ - new DailyRotateFile({ - level: "debug", - dirname: this.config.logDir, - filename: "log-%DATE%.log", - datePattern: "YYYY-MM-DD", - maxSize: this.config.logMaxSize, - maxFiles: this.config.logMaxFiles, - }), - new DailyRotateFile({ - level: "error", - dirname: this.config.logDir, - filename: "error-%DATE%.log", - datePattern: "YYYY-MM-DD", - maxSize: this.config.logMaxSize, - maxFiles: this.config.logMaxFiles, - }), - ], - }); - - if (this.config.enableConsoleTransport) { - logger.add( - new winston.transports.Console({ - level: "debug", - format: logFormat, - }), - ); - } - - return logger; - } - - public async initialize(): Promise { - if (this.initialized) return; - super.initialize(); - this.getLogger("Logger").info("Initialized"); - } - - public getLogger(consumerName?: string): LoggerInterface { - const cacheKey = consumerName || "__default__"; - - if (this.consumerLoggers.has(cacheKey)) { - return this.consumerLoggers.get(cacheKey)!; - } - - const logger = this.createConsumerLogger(consumerName); - this.consumerLoggers.set(cacheKey, logger); - return logger; - } - - private createConsumerLogger(consumerName?: string): LoggerInterface { - const getLogLevel = (): string => { - if (!consumerName) { - return this.config.logLevelDefault; - } - - return this.config.logLevelsGranular[consumerName] || this.config.logLevelDefault; - }; - - // Map log levels to numeric values for comparison - const logLevelValue: Record = { - error: 0, - warn: 1, - info: 2, - debug: 3, - }; - - // Only log if the message level is <= configured level - const shouldLog = (messageLevel: string): boolean => { - const configuredLevel = getLogLevel(); - const configLevelValue = logLevelValue[configuredLevel] || 2; // Default to info - const messageLevelValue = logLevelValue[messageLevel] || 0; // Default to error - - return messageLevelValue <= configLevelValue; - }; - - const logLevel = getLogLevel(); - - return { - error: (message: any, ...meta: any[]) => { - this.baseLogger.error( - message, - consumerName ? { consumer: consumerName, ...meta } : meta, - ); - }, - warn: (message: any, ...meta: any[]) => { - if (shouldLog("warn")) { - this.baseLogger.warn( - message, - consumerName ? { consumer: consumerName, ...meta } : meta, - ); - } - }, - info: (message: any, ...meta: any[]) => { - if (shouldLog("info")) { - this.baseLogger.info( - message, - consumerName ? { consumer: consumerName, ...meta } : meta, - ); - } - }, - debug: (message: any, ...meta: any[]) => { - if (shouldLog("debug")) { - this.baseLogger.debug( - message, - consumerName ? { consumer: consumerName, ...meta } : meta, - ); - } - }, - }; - } - - public override dispose(): void { - this.consumerLoggers.clear(); - super.dispose(); - } -} diff --git a/src/common/utils/asyncRetry.ts b/src/common/utils/asyncRetry.ts index c04dbb2..ef28b07 100644 --- a/src/common/utils/asyncRetry.ts +++ b/src/common/utils/asyncRetry.ts @@ -1,4 +1,5 @@ -import { Logger } from "./Logger"; +import { Logger } from "@concero/operator-utils"; + import { sleep } from "./sleep"; export interface RetryOptions { diff --git a/src/common/utils/callContract.ts b/src/common/utils/callContract.ts index 0a3b6c8..34b2c61 100644 --- a/src/common/utils/callContract.ts +++ b/src/common/utils/callContract.ts @@ -1,7 +1,7 @@ import { Hash, type PublicClient, type SimulateContractParameters, type WalletClient } from "viem"; +import { NonceManager } from "@concero/operator-utils"; import { AppErrorEnum, globalConfig } from "../../constants"; -import { NonceManager } from "../managers"; import confirmations from "../../constants/confirmations.json"; import { IConfirmations } from "../../types/Confirmations"; diff --git a/src/common/utils/checkGas.ts b/src/common/utils/checkGas.ts index ee851ca..bde56d4 100644 --- a/src/common/utils/checkGas.ts +++ b/src/common/utils/checkGas.ts @@ -2,11 +2,8 @@ import { Address, formatUnits, PublicClient } from "viem"; import { WebClient } from "@slack/web-api"; +import { HttpClient, Logger, NetworkManager, ViemClientManager } from "@concero/operator-utils"; import { globalConfig } from "../../constants"; -import { NetworkManager, ViemClientManager } from "../managers"; - -import { HttpClient } from "./HttpClient"; -import { Logger } from "./logger"; const SAFE_TXS_COUNT_FOR_OPERATOR_BALANCE = 15n; diff --git a/src/common/utils/customHttpTransport.ts b/src/common/utils/customHttpTransport.ts index c75b230..782d793 100644 --- a/src/common/utils/customHttpTransport.ts +++ b/src/common/utils/customHttpTransport.ts @@ -1,6 +1,6 @@ import { Transport, http } from "viem"; -import { Logger } from "./Logger"; +import { Logger } from "@concero/operator-utils"; export function createCustomHttpTransport(url: string): Transport { const logger = Logger.getInstance().getLogger("ViemTransport"); diff --git a/src/common/utils/fetchNetworkConfigs.ts b/src/common/utils/fetchNetworkConfigs.ts deleted file mode 100644 index 1cffaa9..0000000 --- a/src/common/utils/fetchNetworkConfigs.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { ChainDefinition, createViemChain } from "./createViemChain"; -import { HttpClient } from "./HttpClient"; -import { Logger } from "./Logger"; - -export interface V2Network { - name: string; - chainId: number; - chainSelector: number; - rpcUrls: string[]; - blockExplorers: { - name: string; - url: string; - apiUrl: string; - }[]; - faucets?: string[]; - nativeCurrency?: { - name: string; - symbol: string; - decimals: number; - }; -} - -export interface ProcessedNetwork { - name: string; - chainId: number; - chainSelector: string; - viemChain: ReturnType; -} - -export interface NetworkConfigs { - mainnetNetworks: Record; - testnetNetworks: Record; -} - -export async function fetchNetworkConfigs( - networkMode: "mainnet" | "testnet" | "localhost" = "testnet", - urls?: { mainnet: string; testnet: string }, -): Promise { - const logger = Logger.getInstance().getLogger("NetworkConfig"); - const httpClient = HttpClient.getInstance(); - - try { - let mainnetNetworks: Record = {}; - let testnetNetworks: Record = {}; - - if (networkMode === "localhost") { - // For localhost mode, return empty networks as they are handled separately - return { mainnetNetworks, testnetNetworks }; - } - - if (networkMode === "mainnet") { - if (!urls?.mainnet) throw new Error("Mainnet URL is required"); - const mainnetData = await httpClient.get(urls.mainnet); - mainnetNetworks = processNetworkData( - mainnetData as Record, - false, - logger, - ); - } else if (networkMode === "testnet") { - if (!urls?.testnet) throw new Error("Testnet URL is required"); - const testnetData = await httpClient.get(urls.testnet); - testnetNetworks = processNetworkData( - testnetData as Record, - true, - logger, - ); - } - - return { - mainnetNetworks, - testnetNetworks, - }; - } catch (error: unknown) { - logger.error(`Failed to fetch ${networkMode} network configurations:`, error); - throw error; - } -} - -function processNetworkData( - networkData: Record, - isTestnet: boolean, - logger: ReturnType, -): Record { - const processedNetworks: Record = {}; - - for (const [networkName, details] of Object.entries(networkData)) { - try { - const chainDefinition: ChainDefinition = { - id: details.chainId, - name: details.name, - rpcUrls: details.rpcUrls, - blockExplorer: details.blockExplorers[0] - ? { - name: details.blockExplorers[0].name, - url: details.blockExplorers[0].url, - } - : undefined, - isTestnet, - }; - - processedNetworks[networkName] = { - name: details.name, - chainId: details.chainId, - chainSelector: details.chainSelector.toString(), - viemChain: createViemChain(chainDefinition), - }; - } catch (error: unknown) { - const networkType = isTestnet ? "testnet" : "mainnet"; - logger.warn( - `Failed to process ${networkType} network ${networkName}: ${error instanceof Error ? error.message : String(error)}`, - ); - } - } - - return processedNetworks; -} diff --git a/src/common/utils/index.ts b/src/common/utils/index.ts index 7181f27..9812e2d 100644 --- a/src/common/utils/index.ts +++ b/src/common/utils/index.ts @@ -7,10 +7,8 @@ export { createViemChain } from "./createViemChain"; export { createCustomHttpTransport } from "./customHttpTransport"; export { decodeCLFReport } from "./decoders/decodeCLFReport"; export { decodeMessageReportResult } from "./decoders/decodeMessageReportResult"; -export { fetchNetworkConfigs } from "./fetchNetworkConfigs"; export * as formatting from "./formatting"; export { getEnvAddress, getEnvVar } from "./getEnvVar"; export { getGranularLogLevels } from "./getGranularLogLevels"; export { getOptionalEnvVar } from "./getOptionalEnvVar"; export { localhostViemChain } from "./localhostViemChain"; -export { Logger, type LoggerInterface } from "./Logger"; diff --git a/src/common/utils/initializeManagers.ts b/src/common/utils/initializeManagers.ts index 952efaa..3b9e5e8 100644 --- a/src/common/utils/initializeManagers.ts +++ b/src/common/utils/initializeManagers.ts @@ -1,20 +1,15 @@ import { - BlockCheckpointManager, BlockManagerRegistry, DeploymentManager, + HttpClient, + Logger, NetworkManager, NonceManager, RpcManager, - TxManager, - TxMonitor, - TxReader, - TxWriter, ViemClientManager, -} from "../managers"; - +} from "@concero/operator-utils"; import { globalConfig } from "../../constants"; -import { HttpClient } from "./HttpClient"; -import { Logger } from "./Logger"; +import { BlockCheckpointManager, TxManager, TxMonitor, TxReader, TxWriter } from "../managers"; /** Initialize all managers in the correct dependency order */ export async function initializeManagers(): Promise { @@ -58,13 +53,19 @@ export async function initializeManagers(): Promise { networkMode: globalConfig.NETWORK_MODE as "mainnet" | "testnet" | "localhost", }, ); - const networkManager = NetworkManager.createInstance(logger.getLogger("NetworkManager"), { - networkUpdateIntervalMs: globalConfig.NETWORK_MANAGER.NETWORK_UPDATE_INTERVAL_MS, - networkMode: globalConfig.NETWORK_MODE as "mainnet" | "testnet" | "localhost", - ignoredNetworkIds: globalConfig.IGNORED_NETWORK_IDS, - whitelistedNetworkIds: globalConfig.WHITELISTED_NETWORK_IDS, - defaultConfirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS, - }); + const networkManager = NetworkManager.createInstance( + logger.getLogger("NetworkManager"), + httpClient, + { + networkUpdateIntervalMs: globalConfig.NETWORK_MANAGER.NETWORK_UPDATE_INTERVAL_MS, + networkMode: globalConfig.NETWORK_MODE as "mainnet" | "testnet" | "localhost", + ignoredNetworkIds: globalConfig.IGNORED_NETWORK_IDS, + whitelistedNetworkIds: globalConfig.WHITELISTED_NETWORK_IDS, + defaultConfirmations: globalConfig.TX_MANAGER.DEFAULT_CONFIRMATIONS, + mainnetUrl: globalConfig.URLS.V2_NETWORKS.MAINNET, + testnetUrl: globalConfig.URLS.V2_NETWORKS.TESTNET, + }, + ); const blockCheckpointManager = BlockCheckpointManager.createInstance( logger.getLogger("BlockCheckpointManager"), { diff --git a/src/relayer-a/businessLogic/ensureDeposit.ts b/src/relayer-a/businessLogic/ensureDeposit.ts index 7b6fad5..1b8024f 100644 --- a/src/relayer-a/businessLogic/ensureDeposit.ts +++ b/src/relayer-a/businessLogic/ensureDeposit.ts @@ -1,8 +1,12 @@ import { Hash, PublicClient } from "viem"; -import { DeploymentManager, NetworkManager, ViemClientManager } from "../../common/managers"; +import { + DeploymentManager, + Logger, + NetworkManager, + ViemClientManager, +} from "@concero/operator-utils"; import { callContract } from "../../common/utils"; -import { Logger } from "../../common/utils/"; import { globalConfig } from "../../constants"; diff --git a/src/relayer-a/businessLogic/ensureOperatorIsRegistered.ts b/src/relayer-a/businessLogic/ensureOperatorIsRegistered.ts index 8def4c5..9474598 100644 --- a/src/relayer-a/businessLogic/ensureOperatorIsRegistered.ts +++ b/src/relayer-a/businessLogic/ensureOperatorIsRegistered.ts @@ -1,6 +1,11 @@ +import { + DeploymentManager, + Logger, + NetworkManager, + ViemClientManager, +} from "@concero/operator-utils"; import { Hash, isHex, Log, PublicClient, WalletClient, type Address } from "viem"; -import { DeploymentManager, NetworkManager, ViemClientManager } from "../../common/managers"; -import { callContract, Logger } from "../../common/utils"; +import { callContract } from "../../common/utils"; import { getAbiItem } from "viem"; import { eventEmitter, globalConfig } from "../../constants"; diff --git a/src/relayer-a/businessLogic/requestCLFMessageReport.ts b/src/relayer-a/businessLogic/requestCLFMessageReport.ts index 9a816c2..8aacaf8 100644 --- a/src/relayer-a/businessLogic/requestCLFMessageReport.ts +++ b/src/relayer-a/businessLogic/requestCLFMessageReport.ts @@ -1,13 +1,13 @@ import { Log, PublicClient, WalletClient, encodeAbiParameters, keccak256 } from "viem"; -import { decodeLogs } from "../../common/eventListener/decodeLogs"; import { DeploymentManager, + Logger, NetworkManager, - TxManager, ViemClientManager, -} from "../../common/managers"; -import { Logger } from "../../common/utils"; +} from "@concero/operator-utils"; +import { decodeLogs } from "../../common/eventListener/decodeLogs"; +import { TxManager } from "../../common/managers"; import { eventEmitter, globalConfig } from "../../constants"; import { ConceroNetwork } from "../../types/ConceroNetwork"; diff --git a/src/relayer-a/businessLogic/submitCLFMessageReport.ts b/src/relayer-a/businessLogic/submitCLFMessageReport.ts index d235cd0..4defb8d 100644 --- a/src/relayer-a/businessLogic/submitCLFMessageReport.ts +++ b/src/relayer-a/businessLogic/submitCLFMessageReport.ts @@ -1,15 +1,15 @@ import { Log, decodeAbiParameters, getAbiItem } from "viem"; -import { decodeLogs } from "../../common/eventListener/decodeLogs"; import { BlockManagerRegistry, DeploymentManager, + Logger, NetworkManager, - TxManager, ViemClientManager, -} from "../../common/managers"; +} from "@concero/operator-utils"; +import { decodeLogs } from "../../common/eventListener/decodeLogs"; +import { TxManager } from "../../common/managers"; import { decodeCLFReport, decodeMessageReportResult } from "../../common/utils"; -import { Logger } from "../../common/utils/"; import { DecodedMessageReportResult } from "../../common/utils/decoders/types"; import { globalConfig } from "../../constants"; diff --git a/src/relayer-a/eventListener/setupEventListeners.ts b/src/relayer-a/eventListener/setupEventListeners.ts index 77dabdf..a91cca0 100644 --- a/src/relayer-a/eventListener/setupEventListeners.ts +++ b/src/relayer-a/eventListener/setupEventListeners.ts @@ -1,8 +1,7 @@ import { AbiEvent, getAbiItem } from "viem"; +import { DeploymentManager, Logger, NetworkManager } from "@concero/operator-utils"; import { setupEventListener } from "../../common/eventListener/setupEventListener"; -import { DeploymentManager, NetworkManager } from "../../common/managers"; -import { Logger } from "../../common/utils"; import { globalConfig } from "../../constants"; diff --git a/src/relayer-a/index.ts b/src/relayer-a/index.ts index 43bef38..b3c78b5 100644 --- a/src/relayer-a/index.ts +++ b/src/relayer-a/index.ts @@ -1,6 +1,6 @@ import "../common/utils/configureDotEnv"; -import { BlockManagerRegistry } from "../common/managers"; +import { BlockManagerRegistry } from "@concero/operator-utils"; import { AppError, checkGas } from "../common/utils"; import { initializeManagers } from "../common/utils/initializeManagers"; import { AppErrorEnum } from "../constants"; From 9b39b89789da2318e9801c81b6c89b975924815f Mon Sep 17 00:00:00 2001 From: Oleg Date: Sun, 20 Jul 2025 21:58:19 +0100 Subject: [PATCH 09/11] upd --- src/common/managers/BlockManager.ts | 265 ---------------------------- src/common/managers/index.ts | 4 - 2 files changed, 269 deletions(-) delete mode 100644 src/common/managers/BlockManager.ts diff --git a/src/common/managers/BlockManager.ts b/src/common/managers/BlockManager.ts deleted file mode 100644 index 6919337..0000000 --- a/src/common/managers/BlockManager.ts +++ /dev/null @@ -1,265 +0,0 @@ -import { PublicClient } from "viem"; - -import { ConceroNetwork } from "../../types/ConceroNetwork"; -import { BlockManagerConfig } from "../../types/ManagerConfigs"; -import { IBlockManager } from "../../types/managers"; -import { LoggerInterface } from "../utils"; - -import { IBlockCheckpointManager } from "../../types/managers"; - -/** - * BlockManager encapsulates block processing and canonical block emission for a single network. - * It handles both the polling for new blocks and notifying registered handlers about block ranges. - */ - -/** Options for watching blocks */ -type WatchBlocksOptions = { - onBlockRange: (startBlock: bigint, endBlock: bigint) => Promise; - onError?: (err: unknown) => void; -}; - -type BlockRangeHandler = { - id: string; - onBlockRange: (startBlock: bigint, endBlock: bigint) => Promise; - onError?: (err: unknown) => void; -}; - -export class BlockManager implements IBlockManager { - private lastProcessedBlockNumber: bigint; - private latestBlock: bigint | null = null; - public readonly publicClient: PublicClient; - private network: ConceroNetwork; - private blockCheckpointManager: IBlockCheckpointManager; - private blockRangeHandlers: Map = new Map(); - - protected logger: LoggerInterface; - private config: BlockManagerConfig; - - private isDisposed: boolean = false; - private isPolling: boolean = false; - private pollingIntervalMs: number; - private pollingTimeout: NodeJS.Timeout | null = null; - - private constructor( - initialBlock: bigint, - network: ConceroNetwork, - publicClient: PublicClient, - blockCheckpointManager: IBlockCheckpointManager, - logger: LoggerInterface, - config: BlockManagerConfig, - ) { - this.lastProcessedBlockNumber = initialBlock; - this.publicClient = publicClient; - this.network = network; - this.blockCheckpointManager = blockCheckpointManager; - this.logger = logger; - this.config = config; - this.pollingIntervalMs = config.pollingIntervalMs; - } - - static async create( - network: ConceroNetwork, - publicClient: PublicClient, - blockCheckpointManager: IBlockCheckpointManager, - logger: LoggerInterface, - config: BlockManagerConfig, - ): Promise { - let initialBlock: bigint; - const staticLogger = logger; - - if (!config.useCheckpoints) { - initialBlock = await publicClient.getBlockNumber(); - staticLogger.debug( - `${network.name}: Checkpoints disabled. Starting from current chain tip: ${initialBlock}`, - ); - } else { - const savedBlock = await blockCheckpointManager.getCheckpoint(network); - if (savedBlock !== undefined) { - staticLogger.info( - `${network.name}: Resuming from previously saved block ${savedBlock}`, - ); - initialBlock = savedBlock; - } else { - initialBlock = await publicClient.getBlockNumber(); - staticLogger.debug( - `${network.name}: No checkpoint found. Starting from current chain tip: ${initialBlock}`, - ); - } - } - - staticLogger.debug( - `${network.name}: Creating new instance with initial block ${initialBlock}`, - ); - - const blockManager = new BlockManager( - initialBlock, - network, - publicClient, - blockCheckpointManager, - logger, - config, - ); - - return blockManager; - } - - public async startPolling(): Promise { - if (this.isPolling) { - this.logger.debug(`${this.network.name}: Already polling, ignoring start request`); - return; - } - - this.isPolling = true; - - await this.performCatchup(); - await this.poll(); - } - - private stopPolling(): void { - if (!this.isPolling) { - return; - } - - this.logger.info(`${this.network.name}: Stopping block polling`); - this.isPolling = false; - - if (this.pollingTimeout) { - clearTimeout(this.pollingTimeout); - this.pollingTimeout = null; - } - } - - private async poll(): Promise { - if (!this.isPolling || this.isDisposed) { - return; - } - - try { - this.latestBlock = await this.publicClient.getBlockNumber(); - - if (this.latestBlock > this.lastProcessedBlockNumber) { - const startBlock = this.lastProcessedBlockNumber + 1n; - - await this.processBlockRange(startBlock, this.latestBlock); - } - } catch (error) { - this.logger.error(`${this.network.name}: Error in poll cycle:`, error); - } finally { - if (this.isPolling && !this.isDisposed) { - this.pollingTimeout = setTimeout(() => this.poll(), this.pollingIntervalMs); - } - } - } - - public async getLatestBlock(): Promise { - return this.latestBlock; - } - - /** - * Process a range of blocks by: - * 1. Notifying all registered handlers about the new block range - * 2. Updating the last processed block checkpoint - */ - private async processBlockRange(startBlock: bigint, endBlock: bigint): Promise { - this.logger.debug( - `${this.network.name}: Processing ${this.latestBlock - startBlock + 1n} new blocks from ${startBlock} to ${this.latestBlock}`, - ); - - if (this.blockRangeHandlers.size > 0) { - // this.logger.debug( - // `${this.network.name}: Notifying ${this.blockRangeHandlers.size} handlers about blocks ${startBlock} - ${endBlock}`, - // ); - - for (const handler of this.blockRangeHandlers.values()) { - try { - await handler.onBlockRange(startBlock, endBlock); - } catch (error) { - this.logger.error( - `${this.network.name}: Error in block range handler ${handler.id}:`, - error, - ); - if (handler.onError) { - handler.onError(error); - } - } - } - } - await this.updateLastProcessedBlock(endBlock); - } - - /** - * Update the last processed block checkpoint - */ - private async updateLastProcessedBlock(blockNumber: bigint): Promise { - // this.logger.debug( - // `${this.network.name}: Updating last processed block to ${blockNumber} (previous: ${this.lastProcessedBlockNumber})`, - // ); - await this.blockCheckpointManager.updateLastProcessedBlock(this.network.name, blockNumber); - this.lastProcessedBlockNumber = blockNumber; - } - - /** - * Initiates a catchup process from the current processed block to the latest block. - * This is typically called during initialization. - */ - private async performCatchup(): Promise { - if (this.isDisposed) { - this.logger.debug(`${this.network.name}: Already disposed, skipping catchup`); - return; - } - - try { - this.latestBlock = await this.publicClient.getBlockNumber(); - let currentBlock: bigint = this.lastProcessedBlockNumber; - - this.logger.debug( - `${this.network.name}: Starting catchup from block ${currentBlock}, Chain tip: ${this.latestBlock}`, - ); - - while (currentBlock < this.latestBlock && !this.isDisposed) { - const startBlock = currentBlock + 1n; - const endBlock = - startBlock + this.config.catchupBatchSize - 1n > this.latestBlock - ? this.latestBlock - : startBlock + this.config.catchupBatchSize - 1n; - - // Process this block range (will notify handlers) - await this.processBlockRange(startBlock, endBlock); - currentBlock = endBlock; - } - } catch (err) { - this.logger.error(`${this.network.name}:`, err); - } - } - - /** - * Registers a handler that will be called when new blocks are processed. - * Returns an unregister function. - */ - public watchBlocks(options: WatchBlocksOptions): () => void { - const { onBlockRange, onError } = options; - const handlerId = Math.random().toString(36).substring(2, 15); - - // this.logger.debug( - // `${this.network.name}: Registered block range handler ${handlerId}`, - // ); - - this.blockRangeHandlers.set(handlerId, { - id: handlerId, - onBlockRange, - onError, - }); - - return () => { - this.logger.info(`${this.network.name}: Unregistered block range handler ${handlerId}`); - this.blockRangeHandlers.delete(handlerId); - }; - } - - public dispose(): void { - this.isDisposed = true; - this.stopPolling(); - this.blockRangeHandlers.clear(); - this.logger.debug(`${this.network.name}: Disposed`); - } -} diff --git a/src/common/managers/index.ts b/src/common/managers/index.ts index 0c37674..33b7a88 100644 --- a/src/common/managers/index.ts +++ b/src/common/managers/index.ts @@ -1,11 +1,7 @@ export { initializeManagers } from "../utils/initializeManagers"; export { BlockCheckpointManager } from "./BlockCheckpointManager"; -export { BlockManager } from "./BlockManager"; - export { DbManager } from "./DbManager"; - export { ManagerBase } from "./ManagerBase"; - export { TxManager } from "./TxManager"; export { TxMonitor } from "./TxMonitor"; export { TxReader } from "./TxReader"; From df6c1dfa198ba5e9e48b9acf05e78f8c44908a0a Mon Sep 17 00:00:00 2001 From: Oleg Date: Sun, 20 Jul 2025 21:58:55 +0100 Subject: [PATCH 10/11] strict versions --- package.json | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index cab1ed5..60f4bf0 100644 --- a/package.json +++ b/package.json @@ -34,19 +34,19 @@ "dependencies": { "@concero/contract-utils": "github:concero/contract-utils", "@concero/operator-utils": "github:concero/operator-utils", - "@prisma/client": "^5.12.0", - "@slack/web-api": "^7.9.1", - "@types/jest": "^29.5.14", - "async-mutex": "^0.5.0", - "axios": "^1.8.4", - "dotenv": "^16.4.7", - "ethers": "^6.13.5", - "jest": "^29.7.0", - "prisma": "^5.12.0", - "ts-jest": "^29.3.2", - "uuid": "^11.1.0", + "@prisma/client": "5.12.0", + "@slack/web-api": "7.9.1", + "@types/jest": "29.5.14", + "async-mutex": "0.5.0", + "axios": "1.8.4", + "dotenv": "16.4.7", + "ethers": "6.13.5", + "jest": "29.7.0", + "prisma": "5.12.0", + "ts-jest": "29.3.2", + "uuid": "11.1.0", "viem": "2.33.0", - "winston": "^3.17.0", - "winston-daily-rotate-file": "^5.0.0" + "winston": "3.17.0", + "winston-daily-rotate-file": "5.0.0" } } From 25be64cbde543c5810de1c98ab2a4a94c446d85e Mon Sep 17 00:00:00 2001 From: Roman Yarlykov Date: Tue, 22 Jul 2025 20:28:35 +0500 Subject: [PATCH 11/11] feature: retry for missing blocks - when for some reason the contract logs were lost --- bun.lock | 52 +++--- prisma/block-checkpoints.db | Bin 24576 -> 32768 bytes prisma/schema.prisma | 13 ++ src/common/managers/TxReader.ts | 287 +++++++++++++++++++++++++++----- src/types/managers/ITxReader.ts | 6 + 5 files changed, 292 insertions(+), 66 deletions(-) diff --git a/bun.lock b/bun.lock index c1343bc..5449efd 100644 --- a/bun.lock +++ b/bun.lock @@ -6,20 +6,20 @@ "dependencies": { "@concero/contract-utils": "github:concero/contract-utils", "@concero/operator-utils": "github:concero/operator-utils", - "@prisma/client": "^5.12.0", - "@slack/web-api": "^7.9.1", - "@types/jest": "^29.5.14", - "async-mutex": "^0.5.0", - "axios": "^1.8.4", - "dotenv": "^16.4.7", - "ethers": "^6.13.5", - "jest": "^29.7.0", - "prisma": "^5.12.0", - "ts-jest": "^29.3.2", - "uuid": "^11.1.0", + "@prisma/client": "5.12.0", + "@slack/web-api": "7.9.1", + "@types/jest": "29.5.14", + "async-mutex": "0.5.0", + "axios": "1.8.4", + "dotenv": "16.4.7", + "ethers": "6.13.5", + "jest": "29.7.0", + "prisma": "5.12.0", + "ts-jest": "29.3.2", + "uuid": "11.1.0", "viem": "2.33.0", - "winston": "^3.17.0", - "winston-daily-rotate-file": "^5.0.0", + "winston": "3.17.0", + "winston-daily-rotate-file": "5.0.0", }, "devDependencies": { "@trivago/prettier-plugin-sort-imports": "^5.2.2", @@ -255,17 +255,17 @@ "@pkgr/core": ["@pkgr/core@0.2.7", "", {}, "sha512-YLT9Zo3oNPJoBjBc4q8G2mjU4tqIbf5CEOORbUUr48dCD9q3umJ3IPlVqOqDakPfd2HuwccBaqlGhN4Gmr5OWg=="], - "@prisma/client": ["@prisma/client@5.22.0", "", { "peerDependencies": { "prisma": "*" }, "optionalPeers": ["prisma"] }, "sha512-M0SVXfyHnQREBKxCgyo7sffrKttwE6R8PMq330MIUF0pTwjUhLbW84pFDlf06B27XyCR++VtjugEnIHdr07SVA=="], + "@prisma/client": ["@prisma/client@5.12.0", "", { "peerDependencies": { "prisma": "*" }, "optionalPeers": ["prisma"] }, "sha512-bk/+KPpRm0+IzqFCtAxrj+/TNiHzulspnO+OkysaYY/atc/eX0Gx8V3tTLxbHKVX0LKD4Hi8KKCcSbU1U72n7Q=="], - "@prisma/debug": ["@prisma/debug@5.22.0", "", {}, "sha512-AUt44v3YJeggO2ZU5BkXI7M4hu9BF2zzH2iF2V5pyXT/lRTyWiElZ7It+bRH1EshoMRxHgpYg4VB6rCM+mG5jQ=="], + "@prisma/debug": ["@prisma/debug@5.12.0", "", {}, "sha512-wK3fQLxPLMqf5riT5ZIhl8NffPSzFUwtzFX5CH7z/oI9Swmo9UhQlUgZABIVgdXSJ5OAlmRcDZtDKaMApIl8sg=="], - "@prisma/engines": ["@prisma/engines@5.22.0", "", { "dependencies": { "@prisma/debug": "5.22.0", "@prisma/engines-version": "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2", "@prisma/fetch-engine": "5.22.0", "@prisma/get-platform": "5.22.0" } }, "sha512-UNjfslWhAt06kVL3CjkuYpHAWSO6L4kDCVPegV6itt7nD1kSJavd3vhgAEhjglLJJKEdJ7oIqDJ+yHk6qO8gPA=="], + "@prisma/engines": ["@prisma/engines@5.12.0", "", { "dependencies": { "@prisma/debug": "5.12.0", "@prisma/engines-version": "5.12.0-21.473ed3124229e22d881cb7addf559799debae1ab", "@prisma/fetch-engine": "5.12.0", "@prisma/get-platform": "5.12.0" } }, "sha512-rFNRul9JGu0d3tf8etBgmDQ4NVoDwgGrRguvQOc8i+c6g7xPjRuu4aKzMMvHWUuccvRx5+fs1KMBxQ0x2THt+Q=="], - "@prisma/engines-version": ["@prisma/engines-version@5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2", "", {}, "sha512-2PTmxFR2yHW/eB3uqWtcgRcgAbG1rwG9ZriSvQw+nnb7c4uCr3RAcGMb6/zfE88SKlC1Nj2ziUvc96Z379mHgQ=="], + "@prisma/engines-version": ["@prisma/engines-version@5.12.0-21.473ed3124229e22d881cb7addf559799debae1ab", "", {}, "sha512-6yvO8s80Tym61aB4QNtYZfWVmE3pwqe807jEtzm8C5VDe7nw8O1FGX3TXUaXmWV0fQTIAfRbeL2Gwrndabp/0g=="], - "@prisma/fetch-engine": ["@prisma/fetch-engine@5.22.0", "", { "dependencies": { "@prisma/debug": "5.22.0", "@prisma/engines-version": "5.22.0-44.605197351a3c8bdd595af2d2a9bc3025bca48ea2", "@prisma/get-platform": "5.22.0" } }, "sha512-bkrD/Mc2fSvkQBV5EpoFcZ87AvOgDxbG99488a5cexp5Ccny+UM6MAe/UFkUC0wLYD9+9befNOqGiIJhhq+HbA=="], + "@prisma/fetch-engine": ["@prisma/fetch-engine@5.12.0", "", { "dependencies": { "@prisma/debug": "5.12.0", "@prisma/engines-version": "5.12.0-21.473ed3124229e22d881cb7addf559799debae1ab", "@prisma/get-platform": "5.12.0" } }, "sha512-qkHQbZ1hspvOwcImvqY4yj7+FUlw0+uP+6tu3g24V4ULHOXLLkvr5ZZc6vy26OF0hkbD3kcDJCeutFis3poKgg=="], - "@prisma/get-platform": ["@prisma/get-platform@5.22.0", "", { "dependencies": { "@prisma/debug": "5.22.0" } }, "sha512-pHhpQdr1UPFpt+zFfnPazhulaZYCUqeIcPpJViYoq9R+D/yw4fjE+CtnsnKzPYm0ddUbeXUzjGVGIRVgPDCk4Q=="], + "@prisma/get-platform": ["@prisma/get-platform@5.12.0", "", { "dependencies": { "@prisma/debug": "5.12.0" } }, "sha512-81Ptv9YJnwTArEBPQ2Lvu58sZPxy4OixKxVVgysFan6A3bFP7q8gIg15WTjsRuH4WXh6B667EM9sqoMTNu0fLQ=="], "@scure/base": ["@scure/base@1.2.6", "", {}, "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg=="], @@ -285,7 +285,7 @@ "@slack/types": ["@slack/types@2.14.0", "", {}, "sha512-n0EGm7ENQRxlXbgKSrQZL69grzg1gHLAVd+GlRVQJ1NSORo0FrApR7wql/gaKdu2n4TO83Sq/AmeUOqD60aXUA=="], - "@slack/web-api": ["@slack/web-api@7.9.2", "", { "dependencies": { "@slack/logger": "^4.0.0", "@slack/types": "^2.9.0", "@types/node": ">=18.0.0", "@types/retry": "0.12.0", "axios": "^1.8.3", "eventemitter3": "^5.0.1", "form-data": "^4.0.0", "is-electron": "2.2.2", "is-stream": "^2", "p-queue": "^6", "p-retry": "^4", "retry": "^0.13.1" } }, "sha512-3HoDwV6+ZSTfV+DsbnUd82GlZY0a+DPXuHQHpxWTqgxjM3JWZyGiwR+ov3d2M16pWiMzA+l58UJ5lm1znGq0yA=="], + "@slack/web-api": ["@slack/web-api@7.9.1", "", { "dependencies": { "@slack/logger": "^4.0.0", "@slack/types": "^2.9.0", "@types/node": ">=18.0.0", "@types/retry": "0.12.0", "axios": "^1.8.3", "eventemitter3": "^5.0.1", "form-data": "^4.0.0", "is-electron": "2.2.2", "is-stream": "^2", "p-queue": "^6", "p-retry": "^4", "retry": "^0.13.1" } }, "sha512-qMcb1oWw3Y/KlUIVJhkI8+NcQXq1lNymwf+ewk93ggZsGd6iuz9ObQsOEbvlqlx1J+wd8DmIm3DORGKs0fcKdg=="], "@swc/cli": ["@swc/cli@0.1.65", "", { "dependencies": { "@mole-inc/bin-wrapper": "^8.0.1", "commander": "^7.1.0", "fast-glob": "^3.2.5", "minimatch": "^9.0.3", "semver": "^7.3.8", "slash": "3.0.0", "source-map": "^0.7.3" }, "peerDependencies": { "@swc/core": "^1.2.66", "chokidar": "^3.5.1" }, "optionalPeers": ["chokidar"], "bin": { "swc": "bin/swc.js", "swcx": "bin/swcx.js", "spack": "bin/spack.js" } }, "sha512-4NcgsvJVHhA7trDnMmkGLLvWMHu2kSy+qHx6QwRhhJhdiYdNUrhdp+ERxen73sYtaeEOYeLJcWrQ60nzKi6rpg=="], @@ -421,7 +421,7 @@ "asynckit": ["asynckit@0.4.0", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="], - "axios": ["axios@1.9.0", "", { "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", "proxy-from-env": "^1.1.0" } }, "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg=="], + "axios": ["axios@1.8.4", "", { "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", "proxy-from-env": "^1.1.0" } }, "sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw=="], "babel-jest": ["babel-jest@29.7.0", "", { "dependencies": { "@jest/transform": "^29.7.0", "@types/babel__core": "^7.1.14", "babel-plugin-istanbul": "^6.1.1", "babel-preset-jest": "^29.6.3", "chalk": "^4.0.0", "graceful-fs": "^4.2.9", "slash": "^3.0.0" }, "peerDependencies": { "@babel/core": "^7.8.0" } }, "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg=="], @@ -539,7 +539,7 @@ "diff-sequences": ["diff-sequences@29.6.3", "", {}, "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q=="], - "dotenv": ["dotenv@16.5.0", "", {}, "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg=="], + "dotenv": ["dotenv@16.4.7", "", {}, "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ=="], "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], @@ -591,7 +591,7 @@ "esutils": ["esutils@2.0.3", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="], - "ethers": ["ethers@6.14.3", "", { "dependencies": { "@adraffy/ens-normalize": "1.10.1", "@noble/curves": "1.2.0", "@noble/hashes": "1.3.2", "@types/node": "22.7.5", "aes-js": "4.0.0-beta.5", "tslib": "2.7.0", "ws": "8.17.1" } }, "sha512-qq7ft/oCJohoTcsNPFaXSQUm457MA5iWqkf1Mb11ujONdg7jBI6sAOrHaTi3j0CBqIGFSCeR/RMc+qwRRub7IA=="], + "ethers": ["ethers@6.13.5", "", { "dependencies": { "@adraffy/ens-normalize": "1.10.1", "@noble/curves": "1.2.0", "@noble/hashes": "1.3.2", "@types/node": "22.7.5", "aes-js": "4.0.0-beta.5", "tslib": "2.7.0", "ws": "8.17.1" } }, "sha512-+knKNieu5EKRThQJWwqaJ10a6HE9sSehGeqWN65//wE7j47ZpFhKAnHB/JJFibwwg61I/koxaPsXbXpD/skNOQ=="], "event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="], @@ -1003,7 +1003,7 @@ "pretty-format": ["pretty-format@29.7.0", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="], - "prisma": ["prisma@5.22.0", "", { "dependencies": { "@prisma/engines": "5.22.0" }, "optionalDependencies": { "fsevents": "2.3.3" }, "bin": { "prisma": "build/index.js" } }, "sha512-vtpjW3XuYCSnMsNVBjLMNkTj6OZbudcPPTPYHqX0CJfpcdWciI1dM8uHETwmDxxiqEwCIE6WvXucWUetJgfu/A=="], + "prisma": ["prisma@5.12.0", "", { "dependencies": { "@prisma/engines": "5.12.0" }, "bin": { "prisma": "build/index.js" } }, "sha512-zxw4WSIvpsyNbpv8r7Fxgm7nwTFVmD6wbN6VuH13lClOceSANDOMl4jO3oxE6VzhjxmnEJqOGZjON2T2UpmLag=="], "process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="], @@ -1129,7 +1129,7 @@ "ts-api-utils": ["ts-api-utils@2.1.0", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ=="], - "ts-jest": ["ts-jest@29.3.4", "", { "dependencies": { "bs-logger": "^0.2.6", "ejs": "^3.1.10", "fast-json-stable-stringify": "^2.1.0", "jest-util": "^29.0.0", "json5": "^2.2.3", "lodash.memoize": "^4.1.2", "make-error": "^1.3.6", "semver": "^7.7.2", "type-fest": "^4.41.0", "yargs-parser": "^21.1.1" }, "peerDependencies": { "@babel/core": ">=7.0.0-beta.0 <8", "@jest/transform": "^29.0.0", "@jest/types": "^29.0.0", "babel-jest": "^29.0.0", "jest": "^29.0.0", "typescript": ">=4.3 <6" }, "optionalPeers": ["@babel/core", "@jest/transform", "@jest/types", "babel-jest"], "bin": { "ts-jest": "cli.js" } }, "sha512-Iqbrm8IXOmV+ggWHOTEbjwyCf2xZlUMv5npExksXohL+tk8va4Fjhb+X2+Rt9NBmgO7bJ8WpnMLOwih/DnMlFA=="], + "ts-jest": ["ts-jest@29.3.2", "", { "dependencies": { "bs-logger": "^0.2.6", "ejs": "^3.1.10", "fast-json-stable-stringify": "^2.1.0", "jest-util": "^29.0.0", "json5": "^2.2.3", "lodash.memoize": "^4.1.2", "make-error": "^1.3.6", "semver": "^7.7.1", "type-fest": "^4.39.1", "yargs-parser": "^21.1.1" }, "peerDependencies": { "@babel/core": ">=7.0.0-beta.0 <8", "@jest/transform": "^29.0.0", "@jest/types": "^29.0.0", "babel-jest": "^29.0.0", "jest": "^29.0.0", "typescript": ">=4.3 <6" }, "optionalPeers": ["@babel/core", "@jest/transform", "@jest/types", "babel-jest"], "bin": { "ts-jest": "cli.js" } }, "sha512-bJJkrWc6PjFVz5g2DGCNUo8z7oFEYaz1xP1NpeDU7KNLMWPpEyV8Chbpkn8xjzgRDpQhnGMyvyldoL7h8JXyug=="], "tslib": ["tslib@2.7.0", "", {}, "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA=="], @@ -1215,6 +1215,8 @@ "@scure/bip39/@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], + "@slack/web-api/axios": ["axios@1.10.0", "", { "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", "proxy-from-env": "^1.1.0" } }, "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw=="], + "@swc/cli/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], "@typescript-eslint/typescript-estree/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], diff --git a/prisma/block-checkpoints.db b/prisma/block-checkpoints.db index c0b6654f20f5bc51903d57a85b191c5ccdd61079..a51e0e02d8226ef007a1a272ef36d5d2c78c2dd0 100644 GIT binary patch literal 32768 zcmeI5Pi)&%7{KlP>7UTnh#e{+F^b& zcVJQ|a7G9aCnN-SB#<@%*J*+qhXK2AILKUm#Idh$_T&VJu+UhEQalO1&T))bn zH?Q)=TJ=J?0=m}BO7+bCMFY?Is(A%2>0j0_jMwE*p@+5Om&)hBfw-1IjUQ1=eZTFm zL5q@2nmyElPXqr(slC$*4yoX>xl*jHR(WCIvrkDt-6F^?L)%x&Yv#})ejr?`t*-+E zD=gip7S}Fja=oea$kckX=?#WSPuqs5YlfiZZAn$~ifTx3M7+E#dX8#1L{>CKCW%9+|C0{;8ra z2#O>XEEr!2qJoVKv}=OxZcP-51$3b1Id# zNtX`FZk;|Gm8E96KjHoV9R{BM?;lh3&@2)_0!RP}AOR$R1dsp{Kmter2_OL^a0CJ` zu*n=7TSDbTBDu)M*0Lyqt`pPag5muCB=;l3{mA{r{dNRnD1ro#01`j~NB{{S0VIF~ zkN^@u0!RP}93O!b@Vp(<8vP^BLO6U z1dsp{Kmter2_OL^fCP{L5;zJ0_LWm4m3nn*be6lYt1HrqOp2mpJF?<=x&!Or5mi-m zy%+iIq^55V50Q|VOxNjx) zq%G_!u4y|&hlTr8wII5pA$T?{%V%iXQV~`XbX>Yr5^Q2-dinFPwI65c?dxFa&Az4B z^SiJs7^+loR9#V4bQu;TG*@I;Do|2fy;xLqI9akqSuKh%|NnE?zIdFak0!$R|IzdR zZ7#>%4l|gL01`j~NB{{S0VIF~kN^@u0!RP}Jlh0*O{Lh8SLaVYyf6X$J_IFCJ$jG^ NMP*R*)Pn<){{X4~UJw8P literal 24576 zcmeI4eQX3fK)Q|QehCxRp39)~B3n8?N z{J0xScKq%E`OVbr-+Y(WxaZUbUVH~}d)`6(tKzo94_3vtpMw#Ol&X*MPWQn{V$(hQ@s-nr> zL$205Gcr1rl031!8ZIk$lgx;HmTjUX&-FVsJ%jTc`WtF`XA+irnC|?JG@iO|Bs-On#f00e*l5C8)IAp$nfG-qv|>qm&&eW+iS7v-4TH$0Fy)He_xPV@~8#FBl3@(?a8 zDu;$~K~`{bFd--U2L=;~#r{Hku%IOKLqh|LN-VDo=ko+N&DiKR0W6AhXEH;ox9LkZ;S1d;uZzl6%#A}GWU;_d`00;m9 zAOHk_01yBIKmZ5;0U!VbZZQHqZ1&&!c!7TZ-?isgNPJ!Vk$6eGAeO`_F)r>G-W6UG zzAtPFwt$6Ep<8I;|G>Y*KgWNH*ZCQ~pKl3V4_pge4r~P01G&KAKyc4rNg3FH01yBI zKmZ5;0U!VbfB+EqKM@GpQ4V$cxuT($@w`&eODbkw{LWp>lYhU*_+zKt%b}>Bt7@ve zj8)AIm{eFAPOdO^t$D?7<%u1X;)7T*ln5{G*H9C3P+d{-WbU#Iek;gH?o z$fiuq*|p)Jr#9QEy!_js9V9Z#trg8xO|Ho^8?R7x=~|oJP8zeEtQ&6QqxR>hw)mBh z-RcxBW6dfl?!1*3zei=|-VXZ?4n_Rjnrg^Z)pEyWEZj@=LUWtl!l46%i=x)F<`XY` zi)!+0hkd(~yNu0c^6W%SM^~O3rh5LnZMNv-s#?+Q+xvKeYWV(;Eo{wK*Azl~TGgoNU5U z(@l3y?`?jQ${(2s+MIK#ED=#P$Cg!G(9xfN_Zg}#e6`*7JF7@?$#sI&C0+APJh0%1 zp^)u!D&teQgf-&wzpr{i^__g%pz{37ooAh^EU#M5xLqPY+y6Y(XFu3+#sP*aigN*t zRSiounU-mR$}?YVUw1l_Yj>4&9VzRp%zWons-+JHA9Ti?FJaSic}!n@mx|M8I@g@O zdWBf;$-@t>{*7RU>Qf&Jt~$vjRa4x11N}6#mx@Pm+lsSFc`aWXFWde4n^gMHc-!f% z#V07_(Gp%$eCM-As5H6RS#??}*0N$KRktPj#Kldjf8gbI%b80ao7)%NW3OGN+TkAu zO=mb|UBd-;bq<{UC>7uTLeOwTGEHpEle@9HiqX@rRvqzup@_5YWn~GI&b3_ahd&@{ zD--HuoH1d8EP$~+rrpIi4wCQxFZHZ%`TyTSB7NE)HXr~5fB+Bx0zd!=00AHX1b_e# z00KbZ)+TT#!$w)pzrH|^{Dk`dyZCh^c8GrxUlRTzKFePgcZ)~FQ^MDUcHxTngz$4A z&%Ys@;@3q*h>E}DUlE@dkBKqi_xyEXj{maouy~%oD12TxEHvHPh+y0pfp)f){~1@-`Q!(6aJ t56x{u!D(8;V1zIDa{i void> = new Map(); private logger: LoggerInterface; private config: TxReaderConfig; + private prisma = DbManager.getClient(); private networkManager: INetworkManager; private viemClientManager: IViemClientManager; @@ -122,6 +124,8 @@ export class TxReader implements ITxReader { fromBlock: bigint, toBlock: bigint, ): Promise { + await this.processPendingFailedBlocks(chainName); + this.logger.debug(`fetching logs for blocks ${fromBlock} - ${toBlock}`); const watchersForChain = Array.from(this.logWatchers.values()).filter( watcher => watcher.chainName === chainName, @@ -156,52 +160,235 @@ export class TxReader implements ITxReader { network, ); - // Group logs by event name to process them in batches - const logsByEvent = new Map(); + // Process logs for watchers + await this.processLogsForWatchers(logs, contractWatchers, network, chainCache); + } catch (error) { + this.logger.error( + `Error fetching logs for ${contractAddress} on ${chainName}: ${error}`, + ); + + await this.saveFailedBlock( + chainName, + contractAddress, + fromBlock, + toBlock, + error as Error, + ); + } + } + } - for (const log of logs) { - const eventName = (log as any).eventName || ""; - const logId = `${log.transactionHash}:${log.logIndex}`; + private async processPendingFailedBlocks(chainName: string): Promise { + const failedBlocks = await this.prisma.failedLogFetch.findMany({ + where: { + network: chainName, + }, + orderBy: [{ fromBlock: "asc" }, { contractAddress: "asc" }], + }); - // Skip logs we've already seen - if (chainCache.has(logId)) continue; - chainCache.set(logId, log); + if (failedBlocks.length === 0) return; - const existingLogs = logsByEvent.get(eventName) || []; - existingLogs.push(log); - logsByEvent.set(eventName, existingLogs); - } + this.logger.debug( + `Processing ${failedBlocks.length} pending failed blocks for ${chainName}`, + ); - // Process logs for each watcher - for (const watcher of contractWatchers) { - const eventName = watcher.event?.name || ""; - const watcherLogs = logsByEvent.get(eventName) || []; - - if (watcherLogs.length > 0) { - // it's an experiment. roll it back if fails - watcher.callback(watcherLogs, network).catch(error => { - this.logger.error( - `Error in watcher callback (ID: ${watcher.id}):`, - error, - ); - }); - - // try { - // await watcher.callback(watcherLogs, network); - // } catch (error) { - // this.logger.error( - // `Error in watcher callback (ID: ${watcher.id}):`, - // error, - // ); - // } - } + // Group by block ranges for efficiency + const blockRanges = this.groupFailedBlocksByRange(failedBlocks); + + for (const range of blockRanges) { + await this.retryFailedRange(chainName, range); + } + } + + private async retryFailedRange(chainName: string, range: FailedBlockRange): Promise { + const network = this.networkManager.getNetworkByName(chainName); + if (!network) return; + + this.logger.debug( + `Retrying failed blocks ${range.fromBlock}-${range.toBlock} for ${range.contracts.size} contracts`, + ); + + for (const contractAddress of range.contracts) { + try { + // Get watchers for this contract + const contractWatchers = Array.from(this.logWatchers.values()).filter( + w => w.chainName === chainName && w.contractAddress === contractAddress, + ); + + if (contractWatchers.length === 0) { + // No watchers anymore, remove from failed + await this.removeFailedBlock( + chainName, + contractAddress, + range.fromBlock, + range.toBlock, + ); + continue; } + + const chainCache = this.cachedLogs.get(chainName)!; + + const events = contractWatchers + .map(w => w.event) + .filter((event): event is AbiEvent => event !== undefined); + + const logs = await this.getContractLogs( + contractAddress, + range.fromBlock, + range.toBlock, + events, + network, + ); + + // Process logs for watchers + await this.processLogsForWatchers(logs, contractWatchers, network, chainCache); + + // Success! Remove from failed + await this.removeFailedBlock( + chainName, + contractAddress, + range.fromBlock, + range.toBlock, + ); + + this.logger.info( + `Successfully retried failed blocks ${range.fromBlock}-${range.toBlock} for ${contractAddress}`, + ); } catch (error) { - this.logger.error( - `Error fetching logs for ${contractAddress} on ${chainName}:`, - error, + this.logger.warn( + `Retry failed for ${contractAddress} blocks ${range.fromBlock}-${range.toBlock}: ${error}`, + ); + // Increment retry count + await this.incrementRetryCount( + chainName, + contractAddress, + range.fromBlock, + range.toBlock, + ); + } + } + } + + private async processLogsForWatchers( + logs: Log[], + contractWatchers: LogWatcher[], + network: ConceroNetwork, + chainCache: Map, + ): Promise { + // Group logs by event name to process them in batches + const logsByEvent = new Map(); + + for (const log of logs) { + const eventName = (log as any).eventName || ""; + const logId = `${log.transactionHash}:${log.logIndex}`; + + // Skip logs we've already seen + if (chainCache.has(logId)) continue; + chainCache.set(logId, log); + + const existingLogs = logsByEvent.get(eventName) || []; + existingLogs.push(log); + logsByEvent.set(eventName, existingLogs); + } + + // Process logs for each watcher + for (const watcher of contractWatchers) { + const eventName = watcher.event?.name || ""; + const watcherLogs = logsByEvent.get(eventName) || []; + + if (watcherLogs.length > 0) { + watcher.callback(watcherLogs, network).catch(error => { + this.logger.error(`Error in watcher callback (ID: ${watcher.id}):`, error); + }); + } + } + } + + private async removeFailedBlock( + network: string, + contractAddress: string, + fromBlock: bigint, + toBlock: bigint, + ): Promise { + try { + const deleted = await this.prisma.failedLogFetch.deleteMany({ + where: { + network, + contractAddress, + fromBlock, + toBlock, + }, + }); + + if (deleted.count > 0) { + this.logger.debug( + `Removed ${deleted.count} failed block records for ${network}:${contractAddress} blocks ${fromBlock}-${toBlock}`, ); } + } catch (error) { + this.logger.error("Failed to remove successful block from failed list:", error); + } + } + + private async incrementRetryCount( + network: string, + contractAddress: string, + fromBlock: bigint, + toBlock: bigint, + ): Promise { + try { + await this.prisma.failedLogFetch.updateMany({ + where: { + network, + contractAddress, + fromBlock, + toBlock, + }, + data: { + retryCount: { increment: 1 }, + }, + }); + } catch (error) { + this.logger.error("Failed to increment retry count:", error); + } + } + + private async saveFailedBlock( + network: string, + contractAddress: string, + fromBlock: bigint, + toBlock: bigint, + error: Error, + ): Promise { + try { + await this.prisma.failedLogFetch.upsert({ + where: { + network_contractAddress_fromBlock_toBlock: { + network, + contractAddress, + fromBlock, + toBlock, + }, + }, + update: { + retryCount: { increment: 1 }, + errorMessage: error.message, + }, + create: { + network, + contractAddress, + fromBlock, + toBlock, + errorMessage: error.message, + retryCount: 0, + }, + }); + + this.logger.debug( + `Saved failed block for retry: ${network}:${contractAddress} blocks ${fromBlock}-${toBlock}`, + ); + } catch (dbError) { + this.logger.error("Failed to save failed block to DB:", dbError); } } @@ -217,6 +404,24 @@ export class TxReader implements ITxReader { return result; } + private groupFailedBlocksByRange(failedBlocks: any[]): FailedBlockRange[] { + const ranges = new Map(); + + for (const block of failedBlocks) { + const key = `${block.fromBlock}-${block.toBlock}`; + if (!ranges.has(key)) { + ranges.set(key, { + fromBlock: block.fromBlock, + toBlock: block.toBlock, + contracts: new Set(), + }); + } + ranges.get(key)!.contracts.add(block.contractAddress); + } + + return Array.from(ranges.values()); + } + private async getContractLogs( contractAddress: Address, fromBlock: bigint, @@ -260,8 +465,8 @@ export class TxReader implements ITxReader { // console.log(query, logs); return logs; } catch (error) { - this.logger.error(`Error fetching logs on ${network.name}:`, error); - return []; + this.logger.error(`Error fetching logs on ${network.name}: ${error}`); + throw error; } } diff --git a/src/types/managers/ITxReader.ts b/src/types/managers/ITxReader.ts index f36e656..faa82d9 100644 --- a/src/types/managers/ITxReader.ts +++ b/src/types/managers/ITxReader.ts @@ -18,6 +18,12 @@ export interface LogWatcher { callback: (logs: Log[], network: ConceroNetwork) => Promise; } +export interface FailedBlockRange { + fromBlock: bigint; + toBlock: bigint; + contracts: Set
; +} + export interface ITxReader { getLogs(query: LogQuery, network: ConceroNetwork): Promise;